Skip to content

Commit

Permalink
syntax cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
simagix committed Oct 9, 2021
1 parent 469f687 commit 7770f90
Show file tree
Hide file tree
Showing 37 changed files with 141 additions and 207 deletions.
4 changes: 2 additions & 2 deletions analytics/diagnostic.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func (d *DiagnosticData) readDiagnosticFiles(filenames []string) error {
d.SystemMetricsList = append(d.SystemMetricsList, diagDataMap[key].SystemMetricsList...)
d.ReplSetStatusList = append(d.ReplSetStatusList, diagDataMap[key].ReplSetStatusList...)
}
log.Println(len(filenames), "files loaded, time spent:", time.Now().Sub(btime))
log.Println(len(filenames), "files loaded, time spent:", time.Since(btime))
return err
}

Expand Down Expand Up @@ -242,7 +242,7 @@ func (d *DiagnosticData) readDiagnosticFile(filename string) (DiagnosticData, er
var m runtime.MemStats
runtime.ReadMemStats(&m)
mem := fmt.Sprintf("Memory Alloc = %v MiB, TotalAlloc = %v MiB", m.Alloc/(1024*1024), m.TotalAlloc/(1024*1024))
log.Println(filename, "blocks:", len(metrics.Data), ", time:", time.Now().Sub(btm), mem)
log.Println(filename, "blocks:", len(metrics.Data), ", time:", time.Since(btm), mem)
return diagData, err
}

Expand Down
8 changes: 4 additions & 4 deletions comparison.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (p *Comparison) compare() error {
}
// compare a few key metrics
codeDefault := mdb.CodeDefault
if p.nocolor == true {
if p.nocolor {
codeDefault = ""
}
printer := message.NewPrinter(language.English)
Expand All @@ -156,7 +156,7 @@ func (p *Comparison) compare() error {
gox.GetStorageSize(db.Stats.DataSize), p.getColor(db.Stats.DataSize, dbMap[db.Name].Stats.DataSize), gox.GetStorageSize(dbMap[db.Name].Stats.DataSize), codeDefault))
p.Logger.Info(printer.Sprintf(" ├─Average Data Size: \t%12s%v\t%12s%v",
gox.GetStorageSize(db.Stats.AvgObjSize), p.getColor(db.Stats.AvgObjSize, dbMap[db.Name].Stats.AvgObjSize), gox.GetStorageSize(dbMap[db.Name].Stats.AvgObjSize), codeDefault))
p.Logger.Info(fmt.Sprintf(" └─Number of indexes:"))
p.Logger.Info(" └─Number of indexes:")
for _, coll := range db.Collections {
length := 0
if val, ok := collMap[coll.NS]; ok {
Expand All @@ -169,7 +169,7 @@ func (p *Comparison) compare() error {
}

func (p *Comparison) getColor(a int64, b int64) string {
if p.nocolor == true {
if p.nocolor {
if a != b {
return " ≠"
}
Expand All @@ -184,7 +184,7 @@ func (p *Comparison) getColor(a int64, b int64) string {
// OutputBSON writes bson data to a file
func (p *Comparison) OutputBSON() error {
if p.TargetStats.HostInfo.System.Hostname == "" {
result := `Roles 'clusterMonitor' and 'readAnyDatabase' are required`
result := `roles 'clusterMonitor' and 'readAnyDatabase' are required`
return errors.New(result)
}
var err error
Expand Down
8 changes: 4 additions & 4 deletions keyhole.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func Run(fullVersion string) {
fmt.Println(card.GetSummary(summary))
}
return
} else if *changeStreams == true {
} else if *changeStreams {
stream := mdb.NewChangeStream()
stream.SetCollection(*collection)
stream.SetDatabase(connString.Database)
Expand Down Expand Up @@ -240,7 +240,7 @@ func Run(fullVersion string) {
log.Fatal(err)
}
return
} else if *schema == true {
} else if *schema {
if *collection == "" {
log.Fatal("usage: keyhole [-v] --schema --collection collection_name <mongodb_uri>")
}
Expand All @@ -251,7 +251,7 @@ func Run(fullVersion string) {
}
fmt.Println(str)
return
} else if *seed == true {
} else if *seed {
f := NewSeed()
f.SetCollection(*collection)
f.SetDatabase(connString.Database)
Expand All @@ -276,7 +276,7 @@ func Run(fullVersion string) {
addr := fmt.Sprintf(":%d", *port)
log.Println(http.ListenAndServe(addr, nil))
}()
if *wt == true {
if *wt {
fmt.Println(clusterSummary)
log.Printf("URL: http://localhost:%d/wt\n", *port)
MonitorWiredTigerCache(fullVersion, client)
Expand Down
5 changes: 4 additions & 1 deletion maobi.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ func GenerateMaobiReport(maobiURL string, data []byte, ofile string) error {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
fileWriter, err := bodyWriter.CreateFormFile("file", ofile)
if err != nil {
return err
}
fileWriter.Write(data)
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
Expand All @@ -54,6 +57,6 @@ func GenerateMaobiReport(maobiURL string, data []byte, ofile string) error {
return err
}
ioutil.WriteFile(filename, body, 0644)
fmt.Println(fmt.Sprintf(`HTML report written to %v`, filename))
fmt.Printf("HTML report written to %v\n", filename)
return err
}
4 changes: 2 additions & 2 deletions mdb/cardinality.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (card *Cardinality) GetCardinalityArray(database string, collection string,
}
return summary, err
}
if cur.Next(ctx) == false {
if !cur.Next(ctx) {
cur.Close(ctx)
return summary, err
}
Expand Down Expand Up @@ -135,7 +135,7 @@ func (card *Cardinality) GetCardinalityArray(database string, collection string,
return summary, err
}
defer cur.Close(ctx)
if cur.Next(ctx) == false {
if !cur.Next(ctx) {
return summary, err
}
doc = bson.M{}
Expand Down
4 changes: 1 addition & 3 deletions mdb/cardinality_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,12 @@ import (
"testing"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)

func TestGetCardinalityArray(t *testing.T) {
var err error
var summary CardinalitySummary
var client *mongo.Client
client = getMongoClient()
var client = getMongoClient()
defer client.Disconnect(context.Background())

card := NewCardinality(client)
Expand Down
9 changes: 3 additions & 6 deletions mdb/change_streams_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ func TestChangeStreamClient(t *testing.T) {
t.Fatal(err)
}
client = getMongoClient()
var pipeline []bson.D
pipeline = mongo.Pipeline{}
var pipeline = mongo.Pipeline{}
c := client.Database(cs.Database).Collection(collection)
c.InsertOne(ctx, bson.M{"city": "Atlanta"})

Expand All @@ -62,8 +61,7 @@ func TestChangeStreamDatabase(t *testing.T) {
t.Fatal(err)
}
client = getMongoClient()
var pipeline []bson.D
pipeline = mongo.Pipeline{}
var pipeline = mongo.Pipeline{}
c := client.Database(cs.Database).Collection(collection)
c.InsertOne(ctx, bson.M{"city": "Atlanta"})

Expand Down Expand Up @@ -91,8 +89,7 @@ func TestChangeStreamCollection(t *testing.T) {
t.Fatal(err)
}
client = getMongoClient()
var pipeline []bson.D
pipeline = mongo.Pipeline{}
var pipeline = mongo.Pipeline{}
c := client.Database(cs.Database).Collection(collection)
c.InsertOne(ctx, bson.M{"city": "Atlanta"})

Expand Down
6 changes: 3 additions & 3 deletions mdb/cluster_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func (p *ClusterStats) GetClusterStats(client *mongo.Client, connString connstri

setName := p.ServerStatus.Repl.SetName
s := fmt.Sprintf(`%v/%v`, setName, strings.Join(p.ServerStatus.Repl.Hosts, ","))
oneShard := []Shard{Shard{ID: setName, State: 1, Host: s}}
oneShard := []Shard{{ID: setName, State: 1, Host: s}}
if p.Shards, err = p.GetServersStatsSummary(oneShard, connString); err != nil {
p.Logger.Error(err)
}
Expand Down Expand Up @@ -245,7 +245,7 @@ func (p *ClusterStats) OutputBSON() (string, []byte, error) {
var data []byte
var ofile string
if p.HostInfo.System.Hostname == "" {
result := `Roles 'clusterMonitor' and 'readAnyDatabase' are required`
result := `roles 'clusterMonitor' and 'readAnyDatabase' are required`
return ofile, data, errors.New(result)
}
if data, err = bson.Marshal(p); err != nil {
Expand All @@ -265,6 +265,6 @@ func (p *ClusterStats) OutputBSON() (string, []byte, error) {
if err = gox.OutputGzipped(data, ofile); err != nil {
return ofile, data, err
}
fmt.Println(fmt.Sprintf(`bson data written to %v`, ofile))
fmt.Printf("bson data written to %v\n", ofile)
return ofile, data, err
}
3 changes: 1 addition & 2 deletions mdb/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ func RunAdminCommand(client *mongo.Client, command string) (bson.M, error) {
// RunCommandOnDB execute admin Command at given database
func RunCommandOnDB(client *mongo.Client, command string, db string) (bson.M, error) {
var result = bson.M{}
var err error
err = client.Database(db).RunCommand(context.Background(), bson.D{{Key: command, Value: 1}}).Decode(&result)
var err = client.Database(db).RunCommand(context.Background(), bson.D{{Key: command, Value: 1}}).Decode(&result)
return result, err
}
14 changes: 7 additions & 7 deletions mdb/databases_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func (p *DatabaseStats) GetAllDatabasesStats(client *mongo.Client) ([]Database,
var sampleDoc bson.M
opts := options.Find()
opts.SetLimit(5) // get 5 samples and choose the max_size()
opts.SetHint(bson.D{{"_id", 1}})
opts.SetHint(bson.D{{Key: "_id", Value: 1}})
if cursor, err = collection.Find(ctx, bson.D{{}}, opts); err != nil {
p.Logger.Error(err.Error())
return
Expand All @@ -198,7 +198,7 @@ func (p *DatabaseStats) GetAllDatabasesStats(client *mongo.Client) ([]Database,
if sampleDoc == nil {
p.Logger.Debug("no sample doc available")
}
if p.redaction == true {
if p.redaction {
redact := NewRedactor()
walker := gox.NewMapWalker(redact.callback)
buf, _ := bson.Marshal(walker.Walk(sampleDoc))
Expand All @@ -213,7 +213,7 @@ func (p *DatabaseStats) GetAllDatabasesStats(client *mongo.Client) ([]Database,
var stats bson.M
client.Database(db.Name).RunCommand(ctx, bson.D{{Key: "collStats", Value: collectionName}}).Decode(&stats)
chunks := []Chunk{}
if stats["shards"] != nil && p.verbose == true {
if stats["shards"] != nil && p.verbose {
keys := []string{}

for k := range stats["shards"].(primitive.M) {
Expand Down Expand Up @@ -253,7 +253,7 @@ func (p *DatabaseStats) GetAllDatabasesStats(client *mongo.Client) ([]Database,
db.Collections = collections
databases = append(databases, db)
}
p.Logger.Debugf("GetAllDatabasesStats took %v", time.Now().Sub(t))
p.Logger.Debugf("GetAllDatabasesStats took %v", time.Since(t))
return databases, nil
}

Expand All @@ -280,7 +280,7 @@ func (p *DatabaseStats) collectChunksDistribution(client *mongo.Client, shard st
}
t := time.Now()
coll = client.Database("config").Collection("chunks")
if p.verbose == true {
if p.verbose {
p.Logger.Info(fmt.Sprintf(`collectChunksDistribution on %v %v ...`, shard, ns))
if cur, err = coll.Find(ctx, bson.M{"ns": ns, "shard": shard}); err != nil {
return chunk, nil
Expand Down Expand Up @@ -311,7 +311,7 @@ func (p *DatabaseStats) collectChunksDistribution(client *mongo.Client, shard st
{Key: "min", Value: chunk["min"]}, {Key: "max", Value: chunk["max"]},
{Key: "estimate", Value: true}}
client.Database("admin").RunCommand(ctx, cmd).Decode(&chunk)
if chunk["jumbo"] != nil && chunk["jumbo"].(bool) == true {
if chunk["jumbo"] != nil && chunk["jumbo"].(bool) {
jcount++
}
if chunk["numObjects"] != nil {
Expand All @@ -330,7 +330,7 @@ func (p *DatabaseStats) collectChunksDistribution(client *mongo.Client, shard st
remains -= length
}
wg.Wait()
dur := time.Now().Sub(t)
dur := time.Since(t)
msg := fmt.Sprintf("collectChunksDistribution used %v threads on %v %v took %v for %v chunks, rate: %v",
p.threads, shard, ns, dur, count, dur/time.Duration(count))
p.Logger.Info(msg)
Expand Down
4 changes: 2 additions & 2 deletions mdb/explain.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (e *Explain) ExecuteAllPlans(client *mongo.Client, filename string) error {
buffer, _, rerr := reader.ReadLine()
if rerr != nil {
break
} else if strings.HasSuffix(string(buffer), "ms") == false {
} else if !strings.HasSuffix(string(buffer), "ms") {
continue
}
if err = qe.ReadQueryShape(buffer); err != nil {
Expand Down Expand Up @@ -119,7 +119,7 @@ func (e *Explain) PrintExplainResults(filename string) error {
doc := bson.M{}
json.Unmarshal(data, &doc)
if doc["stdout"] == nil {
usage := "Usage: keyhole --explain <mongod.log> <uri> | <result.json.gz>"
usage := "usage: keyhole --explain <mongod.log> <uri> | <result.json.gz>"
return errors.New(usage)
}
fmt.Println(doc["stdout"])
Expand Down
Loading

0 comments on commit 7770f90

Please sign in to comment.