-
Notifications
You must be signed in to change notification settings - Fork 15
/
monit.go
1108 lines (1062 loc) · 32.9 KB
/
monit.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
// File : monit.go
// Author : Valentin Kuznetsov <vkuznet AT gmail dot com>
// Created : Fri, 03 Apr 2020 10:48:20 GMT
// Description: client for CERN MONIT infrastructure
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/go-stomp/stomp"
)
// Record represents MONIT return record {"response":...}
type Record map[string]interface{}
// DSRecordMaps represents data sources maps {ds1:{id: 1, ...}, ds2:{id:2, ...}}
type DSRecordMaps map[string]map[string]interface{}
// DSRecord represents record we write out
type DSRecord struct {
Id int `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Database string `json:"database"`
}
// DataSources provides list of MONIT datasources
var DataSources []DSRecord
// StompConfig represents stomp configuration. The configuration should contains
// either Login/Password or Key/Cert pair
type StompConfig struct {
Producer string `json:"producer"` // stomp producer name
URI string `json:"host_and_ports"` // stomp URI host:port
Login string `json:"username"` // stomp user name (optional)
Password string `json:"password"` // stomp password (optional)
Key string `json:"key"` // stomp user key (optional)
Cert string `json:"cert"` // stomp user certification (optional)
Topic string `json:"topic"` // stomp topic path
}
// helper function to provide string representation of Stomp Config
func (c *StompConfig) String() string {
return fmt.Sprintf("<StompConfig uri=%s producer=%s topic=%s>", c.URI, c.Producer, c.Topic)
}
// represents parameters needed to run queries
type Params struct {
URL string
DBName string
DBID int
Database string
DBType string
ESAPI string
ShortDBID int // index id in a short term storage cluster
LongDBID int // index id in a long term storage cluster
ShortURL string // request URL for short term cluster stats
LongURL string // request URL for long term cluster stats
Token string
Query string
Verbose int
Config StompConfig
Inject bool
}
// builder function to get default params for stats query
func NewStatsParams(url string, token string, q string, verbose int, config StompConfig, inject bool) *Params {
// per our discussion with MONIT team (RQF1647972)
// we only need to use some dbid for _stats ES API, here I use
// 9573, the id of monit_prod_cms-es-size_raw_elasticsearch datasource, and 9582
// the id of monit_prod_condor_agg_metric datasource
return &Params{
ShortDBID: 9573,
LongDBID: 9582,
ShortURL: fmt.Sprintf("%s/api/datasources/proxy/9573/monit_prod*/_stats/store", url),
LongURL: fmt.Sprintf("%s/api/datasources/proxy/9582/monit_prod*/_stats/store", url),
Token: token,
Query: q,
Verbose: verbose,
Config: config,
Inject: inject,
}
}
// builder function of params for queries
func NewParams(url string, token string, q string, dbname string, dbid int, database string, dbtype string, esapi string, verbose int) *Params {
return &Params{
URL: url,
Token: token,
Query: q,
DBName: dbname,
DBID: dbid,
Database: database,
DBType: dbtype,
ESAPI: esapi,
Verbose: verbose,
}
}
// helper function to print stats Params
func (sp *Params) PrintStatsParams() {
log.Println("short_term_url ", sp.ShortURL)
log.Println("long_term_url ", sp.LongURL)
log.Println("token ", sp.Token)
log.Println("query ", sp.Query)
log.Println("short_term_dbid", sp.ShortDBID)
log.Println("long_term_dbid ", sp.LongDBID)
log.Println("inject to MONIT", sp.Inject)
}
// helper function to print Params
func (p *Params) PrintParams() {
log.Println("url ", p.URL)
log.Println("token ", p.Token)
log.Println("query ", p.Query)
log.Println("dbname ", p.DBName)
log.Println("dbid ", p.DBID)
log.Println("database", p.Database)
log.Println("dbtype ", p.DBType)
log.Println("esapi ", p.ESAPI)
}
// helper function to either read file content or return given string
func read(r string) string {
if _, err := os.Stat(r); err == nil {
b, e := os.ReadFile(r)
if e != nil {
log.Fatalf("Unable to read data from file: %s, error: %s", r, e)
}
return strings.Replace(string(b), "\n", "", -1)
}
return r
}
// return CMS Monitoring datasources
func datasources(rurl, t string, verbose int) ([]DSRecord, error) {
uri := fmt.Sprintf("%s/api/datasources", rurl)
req, err := http.NewRequest("GET", uri, nil)
token := read(t)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
req.Header.Set("Content-type", "application/x-ndjson")
req.Header.Set("Accept", "application/json")
if verbose > 0 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("[DEBUG] response:", string(dump))
}
}
if resp.StatusCode == 403 {
if verbose > 1 {
log.Println("[DEBUG] User is not ADMIN")
}
// User got permission denied http 403, so do not send data
return nil, errors.New("not admin")
}
if verbose > 1 {
log.Println("[DEBUG] User is ADMIN")
}
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", rurl, err)
}
var records []DSRecord
defer resp.Body.Close()
// Deserialize the response into a map.
if err := json.NewDecoder(resp.Body).Decode(&records); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
//User is admin, so send the data with nil error
return records, nil
}
// Read CMS Monitoring datasources from given url path. Default is datasources file in CMSMonitoring repo.
func readDS(dsurl string, verbose int) []DSRecord {
var records []DSRecord
req, err := http.NewRequest("GET", dsurl, nil)
req.Header.Set("Content-type", "application/x-ndjson")
req.Header.Set("Accept", "application/json")
if verbose > 1 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("[DEBUG] request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", dsurl, err)
}
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("[DEBUG] response:", string(dump))
}
}
dsRecordMaps := make(DSRecordMaps)
defer resp.Body.Close()
// Deserialize the response into a map.
if err := json.NewDecoder(resp.Body).Decode(&dsRecordMaps); err != nil {
if verbose > 1 {
log.Fatalf("[DEBUG] Error parsing the response body: %s", err)
}
log.Fatalf("Error happened while getting Grafana datasources! Please report this error to admins.")
}
// Convert map of data sources to DSRecord struct list
for k, v := range dsRecordMaps {
r := new(DSRecord)
r.Type = fmt.Sprint(v["type"])
r.Id = int(v["id"].(float64))
r.Database = fmt.Sprint(v["database"])
r.Name = fmt.Sprint(k)
records = append(records, *r)
}
if verbose > 1 {
data, e := json.Marshal(records)
if e == nil {
log.Println("[DEBUG] DSRecord: \n" + string(data))
}
}
return records
}
// Write data sources to file. Datasources fetched from Grafana.
func writeDS(fname string) {
out := make(map[string]map[string]interface{})
for _, rec := range DataSources {
r := make(map[string]interface{})
r["type"] = rec.Type
r["id"] = rec.Id
r["database"] = rec.Database
out[rec.Name] = r
}
file, err := json.MarshalIndent(out, "", "\t")
if err == nil {
err = os.WriteFile(fname, file, 0644)
if err != nil {
log.Fatalf("Error writing to file: %s error: %s", fname, err)
}
}
}
// helper function to find MONIT datasource id
func findDataSource(pat string) (int, string, string) {
for _, r := range DataSources {
db := r.Database
if strings.Contains(db, "YYYY-MM-DD") {
db = strings.Replace(db, "YYYY-MM-DD", "", -1)
}
did := r.Id
dtype := r.Type
dbname := r.Name
if db == pat || dbname == pat || (strings.Contains(pat, "*") && strings.Contains(db, pat)) {
return did, db, dtype
}
}
return 0, "", ""
}
// helper function to send data to MONIT via StompAMQ and TLS
func sendDataToStompTLS(config StompConfig, data []byte, verbose int) {
contentType := "application/json"
x509cert, err := tls.LoadX509KeyPair(config.Cert, config.Key)
if err != nil {
log.Fatalf("failed to parse user certificates: %v", err)
}
certs := []tls.Certificate{x509cert}
conf := &tls.Config{Certificates: certs, InsecureSkipVerify: true}
conn, err := tls.Dial("tcp", config.URI, conf)
defer conn.Close()
if err != nil {
log.Fatalf("Unable to dial to %s, error %v", config.URI, err)
}
if verbose > 0 {
log.Printf("connected to StompAMQ server %s", config.URI)
}
stompConn, err := stomp.Connect(conn)
if err != nil {
log.Fatalf("Unable to connect to %s, error %v", config.URI, err)
}
defer stompConn.Disconnect()
if stompConn != nil {
err = stompConn.Send(config.Topic, contentType, data)
if err != nil {
log.Printf("unable to send data to %s, error %v", config.Topic, err)
}
if verbose > 0 {
log.Println("Send data to MONIT", string(data))
}
}
}
// helper function to send data to MONIT via StompAMQ (plain or TLS access is supported)
func sendDataToStomp(config StompConfig, data []byte, verbose int) {
contentType := "application/json"
conn, err := stomp.Dial("tcp",
config.URI,
stomp.ConnOpt.Login(config.Login, config.Password))
defer conn.Disconnect()
if err != nil {
log.Fatalf("Unable to connect to %s, error %v", config.URI, err)
}
if verbose > 0 {
log.Printf("connected to StompAMQ server %s", config.URI)
}
if conn != nil {
err = conn.Send(config.Topic, contentType, data)
if err != nil {
log.Printf("unable to send data to %s, error %v", config.Topic, err)
}
if verbose > 0 {
log.Println("Send data to MONIT", err, string(data))
}
}
}
// helper function to query InfluxDB
func queryIDB(base string, dbid int, dbname, query string, headers [][]string, verbose int) Record {
rurl := fmt.Sprintf("%s/api/datasources/proxy/%d/query?db=%s&q=%s", base, dbid, dbname, url.QueryEscape(query))
if verbose > 0 {
log.Println(rurl)
}
req, err := http.NewRequest("GET", rurl, nil)
if err != nil {
log.Fatalf("Unable to make request to %s, error: %s", rurl, err)
}
for _, v := range headers {
if len(v) == 2 {
req.Header.Add(v[0], v[1])
}
}
if verbose > 1 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", rurl, err)
}
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("response:", string(dump))
}
}
var data Record
defer resp.Body.Close()
// Deserialize the response into a map.
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
return data
}
// helper function to query ElasticSearch
func queryES(base string, dbid int, dbname, query, esapi string, headers [][]string, verbose int) Record {
// Method to query ES DB
// https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-multi-search.html
rurl := fmt.Sprintf("%s/api/datasources/proxy/%d/_msearch", base, dbid)
if esapi != "_msearch" && esapi != "" {
if strings.HasPrefix(esapi, "/") {
rurl = fmt.Sprintf("%s/api/datasources/proxy/%d%s", base, dbid, esapi)
} else {
rurl = fmt.Sprintf("%s/api/datasources/proxy/%d/%s", base, dbid, esapi)
}
}
dbname = strings.Replace(dbname, "[", "", -1)
dbname = strings.Replace(dbname, "]", "", -1)
dbname = strings.Replace(dbname, "_*", "", -1)
dbname = strings.Replace(dbname, "*", "", -1)
q := fmt.Sprintf("{\"search_type\": \"query_then_fetch\", \"index\": [\"%s*\"], \"ignore_unavailable\": true}\n%s\n", dbname, query)
if esapi != "_msearch" {
// if we provided with concrete API to use, e.g. _count
// we don't need to wrap the query
q = query
}
if verbose > 0 {
log.Println(rurl, "\n[User Query]:\n"+q)
}
req, err := http.NewRequest("GET", rurl, strings.NewReader(q))
if err != nil {
log.Fatalf("Unable to make request to %s, error: %s", rurl, err)
}
for _, v := range headers {
if len(v) == 2 {
req.Header.Add(v[0], v[1])
}
}
if esapi != "_msearch" {
// for concrete API use application/json content type
req.Header.Add("Content-type", "application/json")
} else {
// for _msearch (default) API we use specific json content type
req.Header.Add("Content-type", "application/x-ndjson")
}
if verbose > 1 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", rurl, err)
}
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("response: ", string(dump))
}
}
defer resp.Body.Close()
var data Record
// Deserialize the response into a map.
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Println("Please check your query!")
log.Fatalf("Error parsing the response body: %s", err)
}
return data
}
// helper function to query given URL
func queryURL(rurl string, headers [][]string, verbose int) Record {
if verbose > 0 {
log.Println(rurl)
}
req, err := http.NewRequest("GET", rurl, nil)
if err != nil {
log.Fatalf("Unable to make request to %s, error: %s", rurl, err)
}
for _, v := range headers {
if len(v) == 2 {
req.Header.Add(v[0], v[1])
}
}
if verbose > 1 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", rurl, err)
}
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("response: ", string(dump))
}
}
defer resp.Body.Close()
var data Record
// Deserialize the response into a map.
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
return data
}
// helper function to run ES/InfluxDB or MONIT query
func run(p *Params) Record {
var headers [][]string
bearer := fmt.Sprintf("Bearer %s", p.Token)
h := []string{"Authorization", bearer}
headers = append(headers, h)
h = []string{"Accept", "application/json"}
headers = append(headers, h)
q := strings.ToLower(p.Query)
if strings.Contains(q, "elasticsearch") {
return queryES(p.URL, p.DBID, p.Database, p.Query, p.ESAPI, headers, p.Verbose)
} else if strings.Contains(q, "query") {
return queryES(p.URL, p.DBID, p.Database, p.Query, p.ESAPI, headers, p.Verbose)
} else if strings.Contains(q, "select") {
return queryIDB(p.URL, p.DBID, p.Database, p.Query, headers, p.Verbose)
} else if strings.Contains(q, "show") {
return queryIDB(p.URL, p.DBID, p.Database, p.Query, headers, p.Verbose)
}
// perform query for given url
if p.Verbose > 0 {
log.Println("Run query for given URL:", p.URL)
}
return queryURL(p.URL, headers, p.Verbose)
}
// helper function to read single JSON or list of JSON records from
// given file name
func readRecords(fname string, verbose int) []Record {
data, err := os.ReadFile(fname)
if err != nil {
log.Fatalf("Unable to read, file: %s, error: %v\n", fname, err)
}
var out []Record
// let's probe if our data is a single JSON record
var rec Record
err = json.Unmarshal(data, &rec)
if err == nil {
out = append(out, rec)
} else {
// let's probe if our data is a list of JSON records
var records []Record
err = json.Unmarshal(data, &records)
if err == nil {
out = records
}
}
if verbose > 0 {
for _, r := range out {
raw, err := json.Marshal(r)
if err == nil {
log.Println(string(raw))
} else {
log.Printf("unable to marshal input data, %v, error %v", r, err)
}
}
}
return out
}
// helper function to parse stomp credentials, return StompConfig structure
func parseStompConfig(creds string) StompConfig {
raw, err := os.ReadFile(creds)
if err != nil {
log.Fatalf("Unable to read, file: %s, error: %v\n", creds, err)
}
var config StompConfig
err = json.Unmarshal(raw, &config)
if err != nil {
log.Fatalf("Unable to parse, file: %s, error: %v\n", creds, err)
}
return config
}
// helper function to inject given data record into MONIT with given credentials file
func injectData(config StompConfig, data []byte, verbose int) {
if config.Key != "" && config.Cert != "" {
if verbose > 0 {
log.Println("Use TLS method to conenct to Stomp endpoint")
}
sendDataToStompTLS(config, data, verbose)
} else if config.Login != "" && config.Password != "" {
if verbose > 0 {
log.Println("Use Login/Password method to connect to Stomp endpoint")
}
sendDataToStomp(config, data, verbose)
} else {
log.Fatalf("Provided configuration does not contain user credentials")
}
}
// helper function to inject list of records into MONIT infrastructure with
// given credentials file name
func injectRecords(config StompConfig, records []Record, verbose int, inject bool) {
if !inject {
if verbose > 0 {
for _, r := range records {
raw, err := json.Marshal(r)
if err == nil {
log.Println(string(raw))
}
}
}
return
}
if config.Topic == "" {
if verbose > 0 {
log.Printf("Empty StompConfig %s\n", config.String())
return
}
}
for _, r := range records {
raw, err := json.Marshal(r)
if err == nil {
injectData(config, raw, verbose)
}
}
}
// helper function to group ES Index
func groupESIndex(name string) string {
s := strings.Replace(name, "monit_prod_", "", 1)
s = strings.Split(s, "_raw_")[0]
return s
}
// helper function to parse stats meta-data
func parseStats(data map[string]interface{}, verbose int) []Record {
indices, ok := data["indices"].(map[string]interface{})
if !ok {
log.Fatalf("Invalid indices received from 'stats' query")
}
var cmsIndexes []string
for _, d := range DataSources {
db := d.Database
arr := strings.Split(db, "]")
for _, idx := range arr {
idx = strings.Replace(idx, "[", "", -1)
idx = strings.Replace(idx, "*", "", -1)
idx = strings.Trim(idx, " ")
if idx != "" {
cmsIndexes = append(cmsIndexes, idx)
}
}
}
if verbose > 0 {
log.Println("CMS indexes", cmsIndexes)
}
var out []Record
for k, v := range indices {
for _, idx := range cmsIndexes {
if strings.HasPrefix(k, idx) {
r := v.(map[string]interface{})
t := r["total"].(map[string]interface{})
s := t["store"].(map[string]interface{})
size := s["size_in_bytes"].(float64)
fmt.Printf("%s %d\n", k, int64(size))
rec := make(Record)
rec["name"] = k
rec["size"] = int64(size)
rec["type"] = "elasticsearch"
rec["location"] = ""
rec["group"] = groupESIndex(k)
out = append(out, rec)
}
}
}
return out
}
// helper function to deal with stats query
func getStats(statsParams Params) {
statsParams.URL = statsParams.ShortURL
short_term_data := run(&statsParams)
records := parseStats(short_term_data, statsParams.Verbose)
injectRecords(statsParams.Config, records, statsParams.Verbose, statsParams.Inject)
statsParams.URL = statsParams.LongURL
long_term_data := run(&statsParams)
records = parseStats(long_term_data, statsParams.Verbose)
injectRecords(statsParams.Config, records, statsParams.Verbose, statsParams.Inject)
}
// helper function to read given file with hdfs paths and dump their sizes
func hdfsDump(fname string, verbose int) []Record {
var out []Record
data, err := os.ReadFile(fname)
if err != nil {
log.Fatalf("Unable to read, file: %s, error: %v\n", fname, err)
}
var rec Record
err = json.Unmarshal(data, &rec)
if err != nil {
log.Printf("Unable to parse, data: %s, error: %v\n", string(data), err)
return out
}
for k, p := range rec {
path := p.(string)
size, err := hdfsSize(path, verbose)
if err == nil {
rec := make(Record)
rec["name"] = k
rec["size"] = int64(size)
rec["type"] = "hdfs"
rec["location"] = path
rec["group"] = ""
fmt.Printf("%s %d\n", path, int64(size))
out = append(out, rec)
}
}
return out
}
// helper function to print out total size of given HDFS path
func hdfsSize(path string, verbose int) (float64, error) {
out, err := exec.Command("hadoop", "fs", "-du", "-s", "-h", path).Output()
if err != nil {
log.Println("Fail to execute hadoop fs -du -s -h", path, err)
return -1, err
}
// hadoop fs -du -h -s /cms/wmarchive
// 3.0 T 9.1 T /cms/wmarchive
arr := strings.Split(string(out), " ")
size, err := strconv.ParseFloat(arr[0], 10)
if err != nil {
log.Printf("Fail to parse hadoop output, %s, %v\n", out, err)
return -1, err
}
metric := strings.Trim(arr[1], " ")
switch metric {
case "K":
size = size * 1024
case "M":
size = size * 1024 * 1024
case "G":
size = size * 1024 * 1024 * 1024
case "T":
size = size * 1024 * 1024 * 1024
case "P":
size = size * 1024 * 1024 * 1024 * 1024
case "E":
size = size * 1024 * 1024 * 1024 * 1024 * 1024
case "Z":
size = size * 1024 * 1024 * 1024 * 1024 * 1024 * 1024
case "Y":
size = size * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024
default:
if verbose > 0 {
log.Println("Unable to find proper size", out)
}
}
return size, nil
}
// helper function to parse comma separated tags string
func parseTags(itags string) []string {
var tags []string
for _, tag := range strings.Split(itags, ",") {
tags = append(tags, strings.Trim(tag, " "))
}
return tags
}
// helper function to parse given time-range separated by '-'
func parseTimes(trange string) []int64 {
var times []int64
for _, v := range strings.Split(trange, "-") {
v = strings.Trim(v, " ")
var t int64
if v == "now" {
t = time.Now().Unix()
} else if len(v) == 10 { // unix since epoch
value, err := strconv.Atoi(v)
if err != nil {
log.Fatalf("Unable to parse given time value: %v\n", v)
}
t = int64(value)
} else {
var value string
var offset int64
if strings.HasSuffix(v, "s") || strings.HasSuffix(v, "sec") {
value = strings.Split(v, "s")[0]
offset = 1
} else if strings.HasSuffix(v, "m") || strings.HasSuffix(v, "min") {
value = strings.Split(v, "m")[0]
offset = 60
} else if strings.HasSuffix(v, "h") || strings.HasSuffix(v, "hour") {
value = strings.Split(v, "h")[0]
offset = 60 * 60
} else if strings.HasSuffix(v, "d") || strings.HasSuffix(v, "day") || strings.HasSuffix(v, "days") {
value = strings.Split(v, "d")[0]
offset = 60 * 60 * 24
} else {
log.Fatalf("Unable to parse given time value: %v\n", v)
}
if v, e := strconv.Atoi(value); e == nil {
t = time.Now().Unix() + int64(v)*offset
}
}
if t == 0 {
log.Fatalf("Unable to parse given time value: %v\n", v)
}
times = append(times, t*1000) // times should be in milliseconds of Unix since epoch
}
return times
}
// helper function to find dashboard info
func findDashboard(base, token, itags string, verbose int) []map[string]interface{} {
tags := parseTags(itags)
var headers [][]string
bearer := fmt.Sprintf("Bearer %s", token)
h := []string{"Authorization", bearer}
headers = append(headers, h)
h = []string{"Accept", "application/json"}
headers = append(headers, h)
// example: /api/search?query=Production%20Overview&starred=true&tag=prod
v := url.Values{}
for _, tag := range tags {
v.Add("tag", strings.Trim(tag, " "))
}
rurl := fmt.Sprintf("%s/api/search?%s", base, v.Encode())
if verbose > 0 {
log.Println(rurl)
}
req, err := http.NewRequest("GET", rurl, nil)
if err != nil {
log.Fatalf("Unable to make request to %s, error: %s", rurl, err)
}
for _, v := range headers {
if len(v) == 2 {
req.Header.Add(v[0], v[1])
}
}
if verbose > 1 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", rurl, err)
}
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("response: ", string(dump))
}
}
defer resp.Body.Close()
var data []map[string]interface{}
// Deserialize the response into a map.
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
log.Fatalf("Error parsing the response body: %s", err)
}
return data
}
// helper function to add annotation
func addAnnotation(base, token string, data []byte, verbose int) {
var headers [][]string
bearer := fmt.Sprintf("Bearer %s", token)
h := []string{"Authorization", bearer}
headers = append(headers, h)
h = []string{"Content-Type", "application/json"}
headers = append(headers, h)
rurl := fmt.Sprintf("%s/api/annotations", base)
if verbose > 0 {
log.Println(rurl)
}
req, err := http.NewRequest("POST", rurl, bytes.NewBuffer(data))
if err != nil {
log.Fatalf("Unable to make request to %s, error: %s", rurl, err)
}
for _, v := range headers {
if len(v) == 2 {
req.Header.Add(v[0], v[1])
}
}
if verbose > 1 {
dump, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Println("request: ", string(dump))
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Unable to get response from %s, error: %s", rurl, err)
}
if verbose > 1 {
dump, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Println("response:", string(dump))
}
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Unable to read JSON Data POST API, error: %v\n", err)
}
defer resp.Body.Close()
log.Println("response Status:", resp.Status)
log.Println("response Headers:", resp.Header)
log.Println("response Body:", string(body))
}
func main() {
defaultUrl := "https://monit-grafana.cern.ch"
deafultDataSourcesUrl := "https://raw.githubusercontent.com/dmwm/CMSMonitoring/master/static/datasources.json"
var verbose int
flag.IntVar(&verbose, "verbose", 0, "verbosity level, 2 and above is for debug")
var url string
flag.StringVar(&url, "url", defaultUrl, "MONIT URL")
var dsurl string
flag.StringVar(&dsurl, "dsurl", deafultDataSourcesUrl, "DataSources URL")
var token string
flag.StringVar(&token, "token", "", "MONIT token or token file")
var dbid int
flag.IntVar(&dbid, "dbid", 0, "MONIT db identified")
var dbname string
flag.StringVar(&dbname, "dbname", "", "MONIT dbname")
var esapi string
flag.StringVar(&esapi, "esapi", "_msearch", "MONIT ES API end-point")
var annotation string
flag.StringVar(&annotation, "annotation", "", "annotation json file")
var tags string
flag.StringVar(&tags, "tags", "", "comma separated dashboard tags")
var trange string
flag.StringVar(&trange, "trange", "", "dash separated time range, supported formats: seconds since epoch, <YYYYMMDD>, <now>, or Xs, Xm, Xh, Xd (where X is a value and suffixes s,m,h,d refer to seconds, minute, hour, day)")
var query string
flag.StringVar(&query, "query", "", "query string or query json file")
var input string
flag.StringVar(&input, "input", "", "specify input file (should contain either single JSON dict or list of dicts)")
var inject bool
flag.BoolVar(&inject, "inject", false, "inject data to MONIT")
var creds string
flag.StringVar(&creds, "creds", "", "json document with MONIT credentials")
var hdfs string
flag.StringVar(&hdfs, "hdfs", "", "json document with HDFS paths, see doc/hdfs/hdfs.json")
var listDataSources bool
flag.BoolVar(&listDataSources, "datasources", false, "list MONIT datasources")
var writeDataSourcesTo string
flag.StringVar(&writeDataSourcesTo, "writedsto", "", "fetch MONIT datasources from Grafana and write to given file")
flag.Usage = func() {
fmt.Println("Usage: monit [options]")
flag.PrintDefaults()
fmt.Println("Examples:")
fmt.Println(" # read data from input file")
fmt.Println(" monit -input=doc.json -verbose 1")
fmt.Println("")
fmt.Println(" # inject data from given file into MONIT")
fmt.Println(" monit -input=doc.json -creds=creds.json -verbose 1")
fmt.Println("")
fmt.Println(" # look-up data from MONIT")
fmt.Println(" monit -token token -query=query.json -dbname=monit_prod_wmagent")
fmt.Println("")
fmt.Println(" # look-up data from ES MONIT using specific ES API end-point")
fmt.Println(" monit -token token -query=query.json -dbname=monit_prod_wmagent -esapi=_count")
fmt.Println("")
fmt.Println(" # provide stats for all cms ES indicies")
fmt.Println(" monit -token token -query=\"stats\"")
fmt.Println("")
fmt.Println(" # provide stats for all cms ES and hdfs data and inject them to MONIT")
fmt.Println(" monit -token token -query=\"stats\" -hdfs hdfs.json -creds=creds.json -inject")
fmt.Println("")
fmt.Println(" # look-up all available intervention in MONIT InfluxDB for last 2 hours")
fmt.Println(" monit -token token -query=\"select * from outages where time > now() - 2h limit 1\" -dbname=monit_production_ssb_otgs -dbid=9474")
fmt.Println("")
fmt.Println(" # provide annotation to MONIT")
fmt.Println(" monit -token admin.token -annotation=a.json")
fmt.Println(" monit -token admin.token -annotation=\"some message\" -tags=cmsweb,das -trange=now-10m")
fmt.Println("")
fmt.Println(" # find dashboard information for given tags")
fmt.Println(" monit -token token -tags=\"cmsweb,das\"")
fmt.Println("")
fmt.Println(" # look-up all available datasources in MONIT")
fmt.Println(" monit -datasources -token token")
fmt.Println("")
fmt.Println(" # write all datasources in MONIT to given file, requires admin token")
fmt.Println(" monit -token admin.token -writedsto datasources.json")
fmt.Println("")
fmt.Println(" # use different data sources url")
fmt.Println(" monit -token admin.token -dsurl \"http://...\" -query=\"stats\"")
}
flag.Parse()
if verbose > 0 {
log.SetFlags(log.LstdFlags | log.Lshortfile)
} else {
log.SetFlags(log.LstdFlags)
}
var e error
// Fetch data sources from Grafana and write to file. Requires admin token.
if token == "" {
log.Fatalf("Please provide valid token")
}
if writeDataSourcesTo != "" {
DataSources, e = datasources(defaultUrl, token, verbose)
if e == nil {
writeDS(writeDataSourcesTo)
fmt.Println("Data sources are written successfully into", writeDataSourcesTo)
} else {
log.Fatalf("Please provide admin token!")
}
os.Exit(0)
}
// If admin token provided, use function datasources, else readDS