forked from MongoDB-Cowboys/Monalize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monalize.go
321 lines (278 loc) · 9.21 KB
/
monalize.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package main
import (
"bytes"
"context"
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
var jsonDocuments []map[string]interface{}
var byteDocuments []byte
var bsonDocument bson.D
var jsonDocument map[string]interface{}
var temporaryBytes []byte
const ShellToUse = "bash"
func Shellout(command string) (error, string, string) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command(ShellToUse, "-c", command)
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return err, stdout.String(), stderr.String()
}
var (
Database = Teal
Collections = Yellow
Index = Red
Current = Magenta
COLLSCAN = Green
Info = Purple
)
var (
Black = Color("\033[1;30m%s\033[0m")
Red = Color("\033[1;31m%s\033[0m")
Green = Color("\033[1;32m%s\033[0m")
Yellow = Color("\033[1;33m%s\033[0m")
Purple = Color("\033[1;34m%s\033[0m")
Magenta = Color("\033[1;35m%s\033[0m")
Teal = Color("\033[1;36m%s\033[0m")
White = Color("\033[1;37m%s\033[0m")
)
func Color(colorString string) func(...interface{}) string {
sprint := func(args ...interface{}) string {
return fmt.Sprintf(colorString,
fmt.Sprint(args...))
}
return sprint
}
func currentlog(db_uri, logpath string) { // func make log files with slow queries and send files to ftp server. Clear history.
fmt.Println(Info("Search slow query..."))
err, out, errout := Shellout("mongo " + db_uri + " --eval " + `'db.currentOp({"secs_running": {$gte: 1}})'`)
if err != nil {
log.Printf("error: %v\n", err)
}
fmt.Println("--- stdout ---")
fmt.Println(Current(out))
fmt.Println("--- stderr ---")
fmt.Println(errout)
fmt.Println(Info("Monitoring logs mongodb..."))
err, output, errout := Shellout("cat " + logpath + " | grep COLLSCAN > colout.txt")
if err != nil {
log.Printf("error: %v\n", err)
}
fmt.Println("--- stdout ---")
fmt.Println(COLLSCAN(output))
fmt.Println("--- stderr ---")
fmt.Println(errout)
err, history, errout := Shellout("history -c")
if err != nil {
log.Printf("error: %v\n", err)
}
fmt.Println(Index("History cleaned"))
fmt.Println(Index("Done"))
_ = history
}
func typeofobject(x interface{}) { //func to display type object
fmt.Sprintf("%T", x)
}
func arrgsToString(strArray []string) string { // func to convert to string
return strings.Join(strArray, " ")
}
func tocsvExport(data [][]string) error { // func for export data to csv file
file, err := os.Create("result.csv")
if err != nil {
return err
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
for _, value := range data {
if err := writer.Write(value); err != nil {
return err
}
}
return nil
}
func CloseHandler() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\r- Ctrl+C pressed in Terminal")
DeleteFiles()
os.Exit(0)
}()
}
// DeleteFiles is used to simulate a 'clean up' function to run on shutdown. Because
// it's just an example it doesn't have any error handling.
func DeleteFiles() {
fmt.Println("- Run Clean Up - Delete Our Files")
_ = os.Remove("result.csv")
_ = os.Remove("colout.txt")
fmt.Println("- Good bye!")
}
func jsonToStr(args string) string { // function that edits and returns readable indexes
reg, err := regexp.Compile(`"`)
if err != nil {
log.Fatal(err)
}
intres := strings.Replace(string(args), `{"$numberInt":`, "", -1)
floatres := strings.Replace(string(intres), `{"$numberDouble":`, "", -1)
result := reg.ReplaceAllString(floatres, "")
return strings.TrimSuffix(result, "}")
}
func main() {
data := [][]string{}
CloseHandler()
var db_uri string
var db_name string
var logpath string
var context_timeout int
flag.StringVar(&db_uri, "db_uri", "mongodb://localhost:27017", "Set custom url to connect to mongodb")
flag.StringVar(&db_name, "db_name", "", "Set target database, if nil then choose all databases")
flag.StringVar(&logpath, "logpath", "/var/log/mongodb/mongodb.log", "Set path to log file")
flag.IntVar(&context_timeout, "context_timeout", 10, "Set context timeout")
boolExcel := flag.Bool("excel", false, "Add this flag if you want to put the results in an Excel file")
flag.Parse()
client, err := mongo.NewClient(options.Client().ApplyURI(db_uri))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), time.Duration(context_timeout) * time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal("Connect to MongoDB is impossible. Check if it works and the entered data.")
}
var currentdb string // *Current database name* create for disable duplicate in excell
var currentcoll string // *Current collection name* create for disable duplicate in excell
var currentcnt string // *Current Count docs in collection* create for disable duplicate in excell
if db_name != "" {
col, err := client.Database(db_name).ListCollectionNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
fmt.Println(Database("- Database: ", db_name))
var dbs string = db_name // create for disable duplicate in excell
for x, z := range col {
c := client.Database(db_name).Collection(z)
duration := 10 * time.Second
batchSize := int32(10)
cur, err := c.Indexes().List(context.Background(), &options.ListIndexesOptions{&batchSize, &duration})
if err != nil {
log.Fatalf("Something went wrong listing %v", err)
}
count, err := client.Database(db_name).Collection(z).CountDocuments(context.Background(), bson.D{})
cnt := int(count)
str_cnt := strconv.Itoa(cnt) // convert int to str
fmt.Println(Collections("--- Collection: ", z, " Count: ", cnt))
for cur.Next(context.Background()) {
if z == currentcoll { // create for disable duplicate in excell
z = " "
}
currentcoll = z // create for disable duplicate in excell
index := (&bsonDocument)
err := cur.Decode(&index)
var jsonDocument map[string]interface{}
temporaryBytes, err = bson.MarshalExtJSON(bsonDocument, true, true)
err = json.Unmarshal(temporaryBytes, &jsonDocument)
var jsonKey map[string]interface{} = jsonDocument["key"].(map[string]interface{})
args, _ := json.Marshal(jsonKey) // marshal map[string]interface{} to str
fmt.Println(Index(jsonToStr(string(args))))
if *boolExcel == true {
if str_cnt == currentcnt { // create for disable duplicate in excell
str_cnt = " "
}
currentcnt = str_cnt // create for disable duplicate in excell
if dbs == currentdb { // create for disable duplicate in excell
dbs = " "
}
currentdb = dbs // create for disable duplicate in excell
logStr := jsonToStr(string(args))
data = append(data, []string{dbs, currentcoll, str_cnt, logStr}) // append to csv
}
_ = err
}
_ = x
}
} else {
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
for i, s := range databases {
col, err := client.Database(s).ListCollectionNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
fmt.Println(Database(i, "- Database: ", s))
var dbs string = s // create for disable duplicate in excell
for x, z := range col {
c := client.Database(s).Collection(z)
duration := 10 * time.Second
batchSize := int32(10)
cur, err := c.Indexes().List(context.Background(), &options.ListIndexesOptions{&batchSize, &duration})
if err != nil {
log.Fatalf("Something went wrong listing %v", err)
}
count, err := client.Database(s).Collection(z).CountDocuments(context.Background(), bson.D{})
cnt := int(count)
str_cnt := strconv.Itoa(cnt) // convert int to str
fmt.Println(Collections("--- Collection: ", z, " Count: ", cnt))
for cur.Next(context.Background()) {
index := (&bsonDocument)
err := cur.Decode(&index)
var jsonDocument map[string]interface{}
temporaryBytes, err = bson.MarshalExtJSON(bsonDocument, true, true)
err = json.Unmarshal(temporaryBytes, &jsonDocument)
var jsonKey map[string]interface{} = jsonDocument["key"].(map[string]interface{})
args, _ := json.Marshal(jsonKey) // marshal map[string]interface{} to str
fmt.Println(Index(jsonToStr(string(args))))
if z == currentcoll { // create for disable duplicate in excell
z = " "
}
currentcoll = z // create for disable duplicate in excell
if *boolExcel == true {
if str_cnt == currentcnt { // create for disable duplicate in excell
str_cnt = " "
}
currentcnt = str_cnt // create for disable duplicate in excell
if dbs == currentdb { // create for disable duplicate in excell
dbs = " "
}
currentdb = dbs // create for disable duplicate in excell
logStr := jsonToStr(string(args))
data = append(data, []string{dbs, currentcoll, str_cnt, logStr}) // append to csv
}
_ = err
}
_ = x
}
}
}
if *boolExcel == true {
if err := tocsvExport(data); err != nil { // this code return data to csv
log.Fatal(err)
}
}
currentlog(db_uri, logpath)
}