| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package mongo |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi" |
| 10 | ) |
| 11 | |
| 12 | func (c *Collector) collectDbStats(mx map[string]int64) error { |
| 13 | if c.dbSelector == nil { |
| 14 | c.Debug("'database' selector not set, skip collecting database statistics") |
| 15 | return nil |
| 16 | } |
| 17 | |
| 18 | allDBs, err := c.conn.listDatabaseNames() |
| 19 | if err != nil { |
| 20 | return fmt.Errorf("cannot get database names: %v", err) |
| 21 | } |
| 22 | |
| 23 | c.Debugf("all databases on the server: '%v'", allDBs) |
| 24 | |
| 25 | var dbs []string |
| 26 | for _, db := range allDBs { |
| 27 | if c.dbSelector.MatchString(db) { |
| 28 | dbs = append(dbs, db) |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | if len(allDBs) != len(dbs) { |
| 33 | c.Debugf("databases remaining after filtering: %v", dbs) |
| 34 | } |
| 35 | |
| 36 | seen := make(map[string]bool) |
| 37 | for _, db := range dbs { |
| 38 | s, err := c.conn.dbStats(db) |
| 39 | if err != nil { |
| 40 | return fmt.Errorf("dbStats command failed: %v", err) |
| 41 | } |
| 42 | |
| 43 | seen[db] = true |
| 44 | |
| 45 | mx["database_"+db+"_collections"] = s.Collections |
| 46 | mx["database_"+db+"_views"] = s.Views |
| 47 | mx["database_"+db+"_indexes"] = s.Indexes |
| 48 | mx["database_"+db+"_documents"] = s.Objects |
| 49 | mx["database_"+db+"_data_size"] = s.DataSize |
| 50 | mx["database_"+db+"_index_size"] = s.IndexSize |
| 51 | mx["database_"+db+"_storage_size"] = s.StorageSize |
| 52 | } |
| 53 | |
| 54 | for db := range seen { |
| 55 | if !c.databases[db] { |
| 56 | c.databases[db] = true |
| 57 | c.Debugf("new database '%s': creating charts", db) |
| 58 | c.addDatabaseCharts(db) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | for db := range c.databases { |
| 63 | if !seen[db] { |
| 64 | delete(c.databases, db) |
| 65 | c.Debugf("stale database '%s': removing charts", db) |
| 66 | c.removeDatabaseCharts(db) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | func (c *Collector) addDatabaseCharts(name string) { |
| 74 | charts := chartsTmplDatabase.Copy() |
| 75 | |
| 76 | for _, chart := range *charts { |
| 77 | chart.ID = fmt.Sprintf(chart.ID, name) |
| 78 | chart.Labels = []collectorapi.Label{ |
| 79 | {Key: "database", Value: name}, |
| 80 | } |
| 81 | for _, dim := range chart.Dims { |
| 82 | dim.ID = fmt.Sprintf(dim.ID, name) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | if err := c.Charts().Add(*charts...); err != nil { |
| 87 | c.Warning(err) |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | func (c *Collector) removeDatabaseCharts(name string) { |
| 92 | px := fmt.Sprintf("%s%s_", chartPxDatabase, name) |
| 93 | |
| 94 | for _, chart := range *c.Charts() { |
| 95 | if strings.HasPrefix(chart.ID, px) { |
| 96 | chart.MarkRemove() |
| 97 | chart.MarkNotCreated() |
| 98 | } |
| 99 | } |
| 100 | } |