github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/mongo/mongometrics/txnmetrics.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package mongometrics 5 6 import ( 7 "github.com/prometheus/client_golang/prometheus" 8 "gopkg.in/mgo.v2/txn" 9 ) 10 11 const ( 12 databaseLabel = "database" 13 collectionLabel = "collection" 14 optypeLabel = "optype" 15 failedLabel = "failed" 16 ) 17 18 var ( 19 jujuMgoTxnLabelNames = []string{ 20 databaseLabel, 21 collectionLabel, 22 optypeLabel, 23 failedLabel, 24 } 25 ) 26 27 // TxnCollector is a prometheus.Collector that collects metrics about 28 // mgo/txn operations. 29 type TxnCollector struct { 30 txnOpsTotalCounter *prometheus.CounterVec 31 } 32 33 // NewTxnCollector returns a new TxnCollector. 34 func NewTxnCollector() *TxnCollector { 35 return &TxnCollector{ 36 prometheus.NewCounterVec( 37 prometheus.CounterOpts{ 38 Namespace: "juju", 39 Name: "mgo_txn_ops_total", 40 Help: "Total number of mgo/txn ops executed.", 41 }, 42 jujuMgoTxnLabelNames, 43 ), 44 } 45 } 46 47 // AfterRunTransaction is called when a mgo/txn transaction has run. 48 func (c *TxnCollector) AfterRunTransaction(dbName, modelUUID string, ops []txn.Op, err error) { 49 for _, op := range ops { 50 c.updateMetrics(dbName, op, err) 51 } 52 } 53 54 func (c *TxnCollector) updateMetrics(dbName string, op txn.Op, err error) { 55 var failed string 56 if err != nil { 57 failed = "failed" 58 } 59 var optype string 60 switch { 61 case op.Insert != nil: 62 optype = "insert" 63 case op.Update != nil: 64 optype = "update" 65 case op.Remove: 66 optype = "remove" 67 default: 68 optype = "assert" 69 } 70 c.txnOpsTotalCounter.With(prometheus.Labels{ 71 databaseLabel: dbName, 72 collectionLabel: op.C, 73 optypeLabel: optype, 74 failedLabel: failed, 75 }).Inc() 76 } 77 78 // Describe is part of the prometheus.Collector interface. 79 func (c *TxnCollector) Describe(ch chan<- *prometheus.Desc) { 80 c.txnOpsTotalCounter.Describe(ch) 81 } 82 83 // Collect is part of the prometheus.Collector interface. 84 func (c *TxnCollector) Collect(ch chan<- prometheus.Metric) { 85 c.txnOpsTotalCounter.Collect(ch) 86 }