-
Notifications
You must be signed in to change notification settings - Fork 431
/
Copy pathcommon.go
229 lines (183 loc) · 6.44 KB
/
common.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// mongodb_exporter
// Copyright (C) 2022 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"
"sort"
"strings"
"github.com/AlekSi/pointer"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var systemDBs = []string{"admin", "config", "local"} //nolint:gochecknoglobals
func listCollections(ctx context.Context, client *mongo.Client, database string, filterInNamespaces []string) ([]string, error) {
filter := bson.D{} // Default=empty -> list all collections
// if there is a filter with the list of collections we want, create a filter like
// $or: {
// {"$regex": "collection1"},
// {"$regex": "collection2"},
// }
if len(filterInNamespaces) > 0 {
matchExpressions := []bson.D{}
for _, namespace := range filterInNamespaces {
parts := strings.Split(namespace, ".") // db.collection.name.with.dots
if len(parts) > 1 {
// The part before the first dot is the database name.
// The rest is the collection name and it can have dots. We need to rebuild it.
collection := strings.Join(parts[1:], ".")
matchExpressions = append(matchExpressions,
bson.D{{Key: "name", Value: primitive.Regex{Pattern: collection, Options: "i"}}})
}
}
if len(matchExpressions) > 0 {
filter = bson.D{{Key: "$or", Value: matchExpressions}}
}
}
collections, err := client.Database(database).ListCollectionNames(ctx, filter)
if err != nil {
return nil, errors.Wrap(err, "cannot get the list of collections for discovery")
}
return collections, nil
}
// databases returns the list of databases matching the filters.
// - filterInNamespaces: Include only the database names matching the any of the regular expressions in this list.
//
// Case will be ignored because the function will automatically add the ignore case
// flag to the regular expression.
//
// - exclude: List of databases to be excluded. Useful to ignore system databases.
func databases(ctx context.Context, client *mongo.Client, filterInNamespaces []string, exclude []string) ([]string, error) {
opts := &options.ListDatabasesOptions{NameOnly: pointer.ToBool(true), AuthorizedDatabases: pointer.ToBool(true)}
filter := bson.D{}
if excludeFilter := makeExcludeFilter(exclude); excludeFilter != nil {
filter = append(filter, *excludeFilter)
}
if namespacesFilter := makeDBsFilter(filterInNamespaces); namespacesFilter != nil {
filter = append(filter, *namespacesFilter)
}
dbNames, err := client.ListDatabaseNames(ctx, filter, opts)
if err != nil {
return nil, errors.Wrap(err, "cannot get the database names list")
}
return dbNames, nil
}
func makeExcludeFilter(exclude []string) *primitive.E {
filterExpressions := []bson.D{}
for _, dbname := range exclude {
filterExpressions = append(filterExpressions,
bson.D{{Key: "name", Value: bson.D{{Key: "$ne", Value: dbname}}}},
)
}
if len(filterExpressions) == 0 {
return nil
}
return &primitive.E{Key: "$and", Value: filterExpressions}
}
func makeDBsFilter(filterInNamespaces []string) *primitive.E {
filterExpressions := []bson.D{}
nss := removeEmptyStrings(filterInNamespaces)
for _, namespace := range nss {
parts := strings.Split(namespace, ".")
filterExpressions = append(filterExpressions,
bson.D{{Key: "name", Value: bson.D{{Key: "$eq", Value: parts[0]}}}},
)
}
if len(filterExpressions) == 0 {
return nil
}
return &primitive.E{Key: "$or", Value: filterExpressions}
}
func removeEmptyStrings(items []string) []string {
cleanList := []string{}
for _, item := range items {
if item == "" {
continue
}
cleanList = append(cleanList, item)
}
return cleanList
}
func unique(slice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range slice {
if _, ok := keys[entry]; !ok {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func listAllCollections(ctx context.Context, client *mongo.Client, filterInNamespaces []string, excludeDBs []string) (map[string][]string, error) {
namespaces := make(map[string][]string)
dbs, err := databases(ctx, client, filterInNamespaces, excludeDBs)
if err != nil {
return nil, errors.Wrap(err, "cannot make the list of databases to list all collections")
}
filterNS := removeEmptyStrings(filterInNamespaces)
// If there are no specified namespaces to search for collections, it means all dbs should be included.
if len(filterNS) == 0 {
filterNS = append(filterNS, dbs...)
}
for _, db := range dbs {
for _, namespace := range filterNS {
parts := strings.Split(namespace, ".")
dbname := strings.TrimSpace(parts[0])
if dbname == "" || dbname != db {
continue
}
colls, err := listCollections(ctx, client, db, []string{namespace})
if err != nil {
return nil, errors.Wrapf(err, "cannot list the collections for %q", db)
}
if _, ok := namespaces[db]; !ok {
namespaces[db] = []string{}
}
namespaces[db] = append(namespaces[db], colls...)
}
}
// Make it testable.
for db, colls := range namespaces {
uc := unique(colls)
sort.Strings(uc)
namespaces[db] = uc
}
return namespaces, nil
}
func nonSystemCollectionsCount(ctx context.Context, client *mongo.Client, includeNamespaces []string, filterInCollections []string) (int, error) {
databases, err := databases(ctx, client, includeNamespaces, systemDBs)
if err != nil {
return 0, errors.Wrap(err, "cannot retrieve the collection names for count collections")
}
var count int
for _, dbname := range databases {
colls, err := listCollections(ctx, client, dbname, filterInCollections)
if err != nil {
return 0, errors.Wrap(err, "cannot get collections count")
}
count += len(colls)
}
return count, nil
}
func splitNamespace(ns string) (database, collection string) {
parts := strings.Split(ns, ".")
if len(parts) < 2 { // there is no collection?
return parts[0], ""
}
return parts[0], strings.Join(parts[1:], ".")
}