github-vet / github-vet/rangeloop-pointer-findings
simagix/keyhole: mdb/databases_stats.go; 124 LoC
- Dominant language
- No language data
- Stars
- 0
- Forks
- 0
- PR merge metrics
- PR metrics pending
Description
Found a possible issue in [simagix/keyhole](https://www.github.com/simagix/keyhole) at [mdb/databases_stats.go](https://github.com/simagix/keyhole/blob/9cbd4d41ad40eff9fd16ffb870012d6b0683ceb5/mdb/databases_stats.go#L133-L256)
Below is the message reported by the analyzer for this snippet of code. Beware that the analyzer only reports the first
issue it finds, so please do not limit your consideration to the contents of the below message.
> range-loop variable db used in defer or goroutine at line 170
[Click here to see the code in its original context.](https://github.com/simagix/keyhole/blob/9cbd4d41ad40eff9fd16ffb870012d6b0683ceb5/mdb/databases_stats.go#L133-L256)
Click here to show the 124 line(s) of Go which triggered the analyzer.
```go
for _, db := range listdb.Databases {
if db.Name == "admin" || db.Name == "config" || db.Name == "local" {
continue
}
if cur, err = client.Database(db.Name).ListCollections(ctx, bson.D{{}}); err != nil {
return listdb.Databases, err
}
defer cur.Close(ctx)
var collections = []Collection{}
ir := NewIndexStats(p.version)
ir.SetLogger(p.logger)
ir.SetVerbose(p.verbose)
collectionNames := []string{}
for cur.Next(ctx) {
var elem = bson.M{}
if err = cur.Decode(&elem); err != nil {
continue
}
coll := fmt.Sprintf("%v", elem["name"])
collType := fmt.Sprintf("%v", elem["type"])
if strings.Index(coll, "system.") == 0 || (elem["type"] != nil && collType != "collection") {
if p.verbose {
log.Println(fmt.Sprintf(`skip %v %v`, collType, coll))
}
continue
}
collectionNames = append(collectionNames, coll)
}
sort.Strings(collectionNames)
var wg = gox.NewWaitGroup(4) // runs in parallel
var mu sync.Mutex
for _, collectionName := range collectionNames {
wg.Add(1)
go func(client *mongo.Client, collectionName string) {
defer wg.Done()
ns := db.Name + "." + collectionName
if p.verbose {
msg := fmt.Sprintf(`collecting from %v`, ns)
p.logger.Log(msg)
}
collection := client.Database(db.Name).Collection(collectionName)
var cursor *mongo.Cursor
var sampleDoc bson.M
opts := options.Find()
opts.SetLimit(5) // get 5 samples and choose the max_size()
if cursor, err = collection.Find(ctx, bson.D{{}}, opts); err != nil {
log.Println(err.Error())
return
}
dsize := 0
for cursor.Next(ctx) {
var v bson.M
cursor.Decode(&v)
if buf, err := bson.Marshal(v); err != nil {
log.Println(err.Error())
continue
} else if len(buf) > dsize {
sampleDoc = v
dsize = len(buf)
}
}
if sampleDoc == nil {
if p.verbose {
log.Println("no sample doc available")
}
}
if p.redaction == true {
redact := NewRedactor()
walker := gox.NewMapWalker(redact.callback)
buf, _ := bson.Marshal(walker.Walk(sampleDoc))
bson.Unmarshal(buf, &sampleDoc)
}
indexes, err := ir.GetIndexesFromCollection(client, collection)
if err != nil {
log.Println(err)
}
// stats
var stats bson.M
client.Database(db.Name).RunCommand(ctx, bson.D{{Key: "collStats", Value: collectionName}}).Decode(&stats)
chunks := []Chunk{}
if stats["shards"] != nil {
keys := []string{}
for k := range stats["shards"].(primitive.M) {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
m := (stats["shards"].(primitive.M)[k]).(primitive.M)
delete(m, "$clusterTime")
delete(m, "$gleStats")
if chunk, cerr := p.collectChunksDistribution(client, k, ns); cerr != nil {
// log.Println(cerr)
} else {
chunk.Objects = toInt64(m["count"])
chunk.Size = toInt64(m["size"])
chunks = append(chunks, chunk)
}
}
}
mu.Lock()
collstats := Collection{NS: ns, Name: collectionName, Chunks: chunks, Document: sampleDoc,
Indexes: indexes}
data, _ := bson.Marshal(stats)
bson.Unmarshal(data, &collstats.Stats)
collections = append(collections, collstats)
mu.Unlock()
}(client, collectionName)
}
wg.Wait()
sort.Slice(collections, func(i, j int) bool {
return collections[i].Name < collections[j].Name
})
if err = client.Database(db.Name).RunCommand(ctx, bson.D{{Key: "dbStats", Value: 1}}).Decode(&db.Stats); err != nil {
log.Println(err.Error())
continue
}
db.Collections = collections
databases = append(databases, db)
}
```
Leave a reaction on this issue to contribute to the project by classifying this instance as a **Bug** :-1:, **Mitigated** :+1:, or **Desirable Behavior** :rocket:
See the descriptions of the classifications [here](https://github.com/github-vet/rangeclosure-findings#how-can-i-help) for more information.
commit ID: 9cbd4d41ad40eff9fd16ffb870012d6b0683ceb5
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.