/
topology_info.go
192 lines (156 loc) · 5.51 KB
/
topology_info.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// mongodb_exporter
// Copyright (C) 2017 Percona LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package exporter
import (
"context"
"fmt"
"sync"
"github.com/cprobe/cprobe/lib/logger"
"github.com/cprobe/cprobe/plugins/mongodb/internal/proto"
"github.com/cprobe/cprobe/plugins/mongodb/internal/util"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type mongoDBNodeType string
const (
labelClusterRole = "cl_role"
labelClusterID = "cl_id"
labelReplicasetName = "rs_nm"
labelReplicasetState = "rs_state"
typeIsDBGrid = "isdbgrid"
typeMongos mongoDBNodeType = "mongos"
typeMongod mongoDBNodeType = "mongod"
typeShardServer mongoDBNodeType = "shardsvr"
typeOther mongoDBNodeType = ""
)
type labelsGetter interface {
baseLabels() map[string]string
loadLabels(context.Context) error
}
// This is an object to make it posible to easily reload the labels in case of
// disconnection from the db. Just call loadLabels when required.
type topologyInfo struct {
// TODO: with https://jira.percona.com/browse/PMM-6435, replace this client pointer
// by a new connector, able to reconnect if needed. In case of reconnection, we should
// call loadLabels to refresh the labels because they might have changed
client *mongo.Client
rw sync.RWMutex
labels map[string]string
}
// ErrCannotGetTopologyLabels Cannot read topology labels.
var ErrCannotGetTopologyLabels = fmt.Errorf("cannot get topology labels")
func newTopologyInfo(ctx context.Context, client *mongo.Client) *topologyInfo {
ti := &topologyInfo{
client: client,
labels: make(map[string]string),
rw: sync.RWMutex{},
}
err := ti.loadLabels(ctx)
if err != nil {
logger.Warnf("cannot load topology labels: %s", err)
}
return ti
}
// baseLabels returns a copy of the topology labels because in some collectors like
// collstats collector, we must use these base labels and add the namespace or other labels.
func (t *topologyInfo) baseLabels() map[string]string {
c := map[string]string{}
t.rw.RLock()
for k, v := range t.labels {
c[k] = v
}
t.rw.RUnlock()
return c
}
// TopologyLabels reads several values from MongoDB instance like replicaset name, and other
// topology information and returns a map of labels used to better identify the current monitored instance.
func (t *topologyInfo) loadLabels(ctx context.Context) error {
t.rw.Lock()
defer t.rw.Unlock()
t.labels = make(map[string]string)
role, err := getClusterRole(ctx, t.client)
if err != nil {
return errors.Wrap(err, "cannot get node type for topology info")
}
t.labels[labelClusterRole] = role
// Standalone instances or mongos instances won't have a replicaset name
if rs, err := util.ReplicasetConfig(ctx, t.client); err == nil {
t.labels[labelReplicasetName] = rs.Config.ID
}
isArbiter, err := isArbiter(ctx, t.client)
if err != nil {
return err
}
cid, err := util.ClusterID(ctx, t.client)
if err != nil {
if !isArbiter { // arbiters don't have a cluster ID
return errors.Wrapf(ErrCannotGetTopologyLabels, "error getting cluster ID: %s", err)
}
}
t.labels[labelClusterID] = cid
// Standalone instances or mongos instances won't have a replicaset state
state, err := util.MyState(ctx, t.client)
if err == nil {
t.labels[labelReplicasetState] = fmt.Sprintf("%d", state)
}
return nil
}
func isArbiter(ctx context.Context, client *mongo.Client) (bool, error) {
doc := struct {
ArbiterOnly bool `bson:"arbiterOnly"`
}{}
if err := client.Database("admin").RunCommand(ctx, primitive.M{"isMaster": 1}).Decode(&doc); err != nil {
return false, errors.Wrap(err, "cannot check if the instance is an arbiter")
}
return doc.ArbiterOnly, nil
}
func getNodeType(ctx context.Context, client *mongo.Client) (mongoDBNodeType, error) {
md := proto.MasterDoc{}
if err := client.Database("admin").RunCommand(ctx, primitive.M{"isMaster": 1}).Decode(&md); err != nil {
return "", err
}
if md.SetName != nil || md.Hosts != nil {
return typeShardServer, nil
} else if md.Msg == typeIsDBGrid {
// isdbgrid is always the msg value when calling isMaster on a mongos
// see http://docs.mongodb.org/manual/core/sharded-cluster-query-router/
return typeMongos, nil
}
return typeMongod, nil
}
func getClusterRole(ctx context.Context, client *mongo.Client) (string, error) {
cmdOpts := primitive.M{}
// Not always we can get this info. For example, we cannot get this for hidden hosts so
// if there is an error, just ignore it
res := client.Database("admin").RunCommand(ctx, primitive.D{
{Key: "getCmdLineOpts", Value: 1},
{Key: "recordStats", Value: 1},
})
if res.Err() != nil {
return "", nil
}
if err := res.Decode(&cmdOpts); err != nil {
return "", errors.Wrap(err, "cannot decode getCmdLineOpts response")
}
if walkTo(cmdOpts, []string{"parsed", "sharding", "configDB"}) != nil {
return "mongos", nil
}
clusterRole := ""
if cr := walkTo(cmdOpts, []string{"parsed", "sharding", "clusterRole"}); cr != nil {
clusterRole, _ = cr.(string)
}
return clusterRole, nil
}