This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathpmm-admin.go
1646 lines (1504 loc) · 66.2 KB
/
pmm-admin.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
/*
Copyright (c) 2016, Percona LLC and/or its affiliates. All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package main
import (
"context"
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/percona/pmm-client/pmm"
"github.com/percona/pmm-client/pmm/plugin"
linuxMetrics "github.com/percona/pmm-client/pmm/plugin/linux/metrics"
mongodbMetrics "github.com/percona/pmm-client/pmm/plugin/mongodb/metrics"
mongodbQueries "github.com/percona/pmm-client/pmm/plugin/mongodb/queries"
"github.com/percona/pmm-client/pmm/plugin/mysql"
mysqlMetrics "github.com/percona/pmm-client/pmm/plugin/mysql/metrics"
mysqlQueries "github.com/percona/pmm-client/pmm/plugin/mysql/queries"
"github.com/percona/pmm-client/pmm/plugin/postgresql"
postgresqlMetrics "github.com/percona/pmm-client/pmm/plugin/postgresql/metrics"
proxysqlMetrics "github.com/percona/pmm-client/pmm/plugin/proxysql/metrics"
"github.com/percona/pmm-client/pmm/utils"
"github.com/spf13/cobra"
)
// Context used to cancel pmm-admin command if it runs for too long.
// Cobra library doesn't help with passing context: https://github.com/spf13/cobra/issues/563
var (
ctx context.Context
cancel context.CancelFunc
)
var (
admin pmm.Admin
rootCmd = &cobra.Command{
Use: "pmm-admin",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
ctx, cancel = context.WithTimeout(context.Background(), flagTimeout)
if !admin.SkipAdmin && os.Getuid() != 0 {
// skip root check if binary was build in tests
if pmm.Version != "gotest" {
fmt.Println("pmm-admin requires superuser privileges to manage system services.")
os.Exit(1)
}
}
switch cmd.Name() {
case "help":
// Skip pre-run for "help" command.
// You should always be able to get help even if pmm is not configured yet.
return
case "uninstall":
return
case "summary":
return
case "config":
// Skip pre-run as we do not require config file to exist here.
// If the config does not exist, we will init an empty and write on Run.
if err := admin.LoadConfig(); err != nil {
fmt.Printf("Cannot read config file %s: %s\n", pmm.ConfigFile, err)
os.Exit(1)
}
return
}
// The version flag will not run anywhere else than on rootCmd as this flag is not persistent
// and we want it only here without any additional checks.
if flagVersion {
fmt.Println(pmm.Version)
os.Exit(0)
}
if flagFormat != "" {
admin.Format = flagFormat
}
if flagJSON {
admin.Format = "{{ json . }}"
}
if path := pmm.CheckBinaries(); path != "" {
fmt.Println("Installation problem, one of the binaries is missing:", path)
os.Exit(1)
}
// Read config file.
if !pmm.FileExists(pmm.ConfigFile) {
fmt.Println("PMM client is not configured, missing config file. Please make sure you have run 'pmm-admin config'.")
os.Exit(1)
}
if err := admin.LoadConfig(); err != nil {
fmt.Printf("Error reading config file %s: %s\n", pmm.ConfigFile, err)
os.Exit(1)
}
// Check for required settings in config file
// optional settings are marked with "omitempty"
if admin.Config.ServerAddress == "" || admin.Config.ClientName == "" || admin.Config.ClientAddress == "" || admin.Config.BindAddress == "" {
fmt.Println("PMM client is not configured properly. Please make sure you have run 'pmm-admin config'.")
os.Exit(1)
}
switch cmd.Name() {
case
"info",
"show-passwords":
// above cmds should work w/o connectivity, so we return before admin.SetAPI()
return
case
"start",
"stop",
"restart":
if flagAll {
// above cmds should work w/o connectivity if flagAll is set
return
}
}
// Set APIs and check if server is alive.
if err := admin.SetAPI(); err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}
// Proceed to "pmm-admin repair" if requested.
if cmd.Name() == "repair" {
return
}
if pmm.Version != "gotest" {
// Check PMM-Server and PMM-Client versions
if fatal, err := admin.CheckVersion(ctx); err != nil {
fmt.Printf("%s\n", err)
if fatal {
os.Exit(1)
}
}
}
// Check for broken installation.
orphanedServices, missingServices := admin.CheckInstallation()
if len(orphanedServices) > 0 {
fmt.Printf(`We have found system services disconnected from PMM server.
Usually, this happens when data container is wiped before all monitoring services are removed or client is uninstalled.
Orphaned local services: %s
To continue, run 'pmm-admin repair' to remove orphaned services.
`, strings.Join(orphanedServices, ", "))
os.Exit(1)
}
if len(missingServices) > 0 {
fmt.Printf(`PMM server reports services that are missing locally.
Usually, this happens when the system is completely reinstalled.
Orphaned remote services: %s
Beware, if another system with the same client name created those services, repairing the installation will remove remote services
and the other system will be left with orphaned local services. If you are sure there is no other system with the same name,
run 'pmm-admin repair' to remove orphaned services. Otherwise, please reinstall this client.
`, strings.Join(missingServices, ", "))
os.Exit(1)
}
},
Run: func(cmd *cobra.Command, args []string) {
cmd.Usage()
os.Exit(1)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
cancel()
},
}
cmdSummary = &cobra.Command{
Use: "summary",
Short: "Fetch system data for diagnostics.",
Long: "Collect data for Support Engineers to review when troubleshooting pmm-client cases",
Example: ` pmm-admin summary `,
Run: func(cmd *cobra.Command, args []string) {
if err := admin.CollectSummary(); err != nil {
fmt.Println("Error requesting summary. Error message is: ", err)
os.Exit(1)
}
},
}
cmdAdd = &cobra.Command{
Use: "add",
Short: "Add service to monitoring.",
Long: "This command is used to add a monitoring service.",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Root().PersistentPreRun(cmd.Root(), args)
admin.ServiceName = admin.Config.ClientName
admin.ServicePort = flagServicePort
// Check if we have double dash "--"
i := cmd.ArgsLenAtDash()
if i == -1 {
// If "--" is not present then first argument is Service Name and rest we pass through
if len(args) >= 1 {
admin.ServiceName, admin.Args = args[0], args[1:]
}
} else {
// If "--" is present then we split arguments into command and exporter arguments
// exporter arguments
admin.Args = args[i:]
// cmd arguments
args = args[:i]
if len(args) > 1 {
fmt.Printf("Too many parameters. Only service name is allowed but got: %s.\n", strings.Join(args, ", "))
os.Exit(1)
}
if len(args) == 1 {
admin.ServiceName = args[0]
}
}
if match, _ := regexp.MatchString(pmm.NameRegex, admin.ServiceName); !match {
fmt.Println("Service name must be 2 to 60 characters long, contain only letters, numbers and symbols _ - . :")
os.Exit(1)
}
},
}
cmdAnnotate = &cobra.Command{
Use: "annotate TEXT",
Short: "Annotate application events.",
Long: "Publish Application Events as Annotations to PMM Server.",
Example: ` pmm-admin annotate "Application deploy v1.2" --tags "UI, v1.2"`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 {
fmt.Println("Description of annotation is required")
os.Exit(1)
}
if err := admin.AddAnnotation(context.TODO(), strings.Join(args, " "), flagATags); err != nil {
fmt.Println("Your annotation could not be posted. Error message we received was:\n", err)
os.Exit(1)
}
fmt.Println("Your annotation was successfully posted.")
},
}
cmdAddLinuxMetrics = &cobra.Command{
Use: "linux:metrics [flags] [name] [-- [exporter_args]]",
Short: "Add this system to metrics monitoring.",
Long: `This command adds this system to linux metrics monitoring.
You cannot monitor linux metrics from remote machines because the metric exporter requires an access to the local filesystem.
It is supposed there could be only one instance of linux metrics being monitored for this system.
However, you can add another one with the different name just for testing purposes using --force flag.
[name] is an optional argument, by default it is set to the client name of this PMM client.
[exporter_args] are the command line options to be passed directly to Prometheus Exporter.
`,
Run: func(cmd *cobra.Command, args []string) {
linuxMetrics := linuxMetrics.New()
if _, err := admin.AddMetrics(ctx, linuxMetrics, flagForce, flagDisableSSL); err != nil {
fmt.Println("Error adding linux metrics:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring this system.")
},
}
cmdAddMySQL = &cobra.Command{
Use: "mysql [flags] [name]",
Short: "Add complete monitoring for MySQL instance (linux and mysql metrics, queries).",
Long: `This command adds the given MySQL instance to system, metrics and queries monitoring.
When adding a MySQL instance, this tool tries to auto-detect the DSN and credentials.
If you want to create a new user to be used for metrics collecting, provide --create-user option. pmm-admin will create
a new user 'pmm@' automatically using the given (auto-detected) MySQL credentials for granting purpose.
Table statistics is automatically disabled when there are more than 10000 tables on MySQL.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: ` pmm-admin add mysql --password abc123
pmm-admin add mysql --password abc123 --create-user
pmm-admin add mysql --password abc123 --port 3307 instance3307`,
Run: func(cmd *cobra.Command, args []string) {
// Passing additional arguments doesn't make sense because this command enables multiple exporters.
if len(admin.Args) > 0 {
fmt.Printf("We can't determine which exporter should receive additional flags: %s.\n", strings.Join(admin.Args, ", "))
fmt.Println("To pass additional arguments to specific exporter you need to add it separately e.g.:")
fmt.Println("pmm-admin add linux:metrics -- ", strings.Join(admin.Args, " "))
fmt.Println("or")
fmt.Println("pmm-admin add mysql:metrics -- ", strings.Join(admin.Args, " "))
os.Exit(1)
}
// Check --query-source flag.
if flagMySQLQueries.QuerySource != "auto" && flagMySQLQueries.QuerySource != "slowlog" && flagMySQLQueries.QuerySource != "perfschema" {
fmt.Println("Flag --query-source can take the following values: auto, slowlog, perfschema.")
os.Exit(1)
}
linuxMetrics := linuxMetrics.New()
_, err := admin.AddMetrics(ctx, linuxMetrics, flagForce, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[linux:metrics] OK, already monitoring this system.")
} else if err != nil {
fmt.Println("[linux:metrics] Error adding linux metrics:", err)
os.Exit(1)
} else {
fmt.Println("[linux:metrics] OK, now monitoring this system.")
}
mysqlMetrics := mysqlMetrics.New(flagMySQLMetrics, flagMySQL)
info, err := admin.AddMetrics(ctx, mysqlMetrics, false, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[mysql:metrics] OK, already monitoring MySQL metrics.")
} else if err != nil {
fmt.Println("[mysql:metrics] Error adding MySQL metrics:", err)
os.Exit(1)
} else {
fmt.Println("[mysql:metrics] OK, now monitoring MySQL metrics using DSN", utils.SanitizeDSN(info.DSN))
}
mysqlQueries := mysqlQueries.New(flagQueries, flagMySQLQueries, flagMySQL)
info, err = admin.AddQueries(ctx, mysqlQueries)
if err == pmm.ErrDuplicate {
fmt.Println("[mysql:queries] OK, already monitoring MySQL queries.")
} else if err != nil {
fmt.Println("[mysql:queries] Error adding MySQL queries:", err)
os.Exit(1)
} else {
fmt.Println("[mysql:queries] OK, now monitoring MySQL queries from", info.QuerySource,
"using DSN", utils.SanitizeDSN(info.DSN))
}
},
}
cmdAddMySQLMetrics = &cobra.Command{
Use: "mysql:metrics [flags] [name] [-- [exporter_args]]",
Short: "Add MySQL instance to metrics monitoring.",
Long: `This command adds the given MySQL instance to metrics monitoring.
When adding a MySQL instance, this tool tries to auto-detect the DSN and credentials.
If you want to create a new user to be used for metrics collecting, provide --create-user option. pmm-admin will create
a new user 'pmm@' automatically using the given (auto-detected) MySQL credentials for granting purpose.
Table statistics is automatically disabled when there are more than 10000 tables on MySQL.
[name] is an optional argument, by default it is set to the client name of this PMM client.
[exporter_args] are the command line options to be passed directly to Prometheus Exporter.
`,
Example: ` pmm-admin add mysql:metrics --password abc123
pmm-admin add mysql:metrics --password abc123 --create-user
pmm-admin add mysql:metrics --password abc123 --port 3307 instance3307
pmm-admin add mysql:metrics --user rdsuser --password abc123 --host my-rds.1234567890.us-east-1.rds.amazonaws.com my-rds
pmm-admin add mysql:metrics -- --collect.perf_schema.eventsstatements
pmm-admin add mysql:metrics -- --collect.perf_schema.eventswaits=false`,
Run: func(cmd *cobra.Command, args []string) {
mysqlMetrics := mysqlMetrics.New(flagMySQLMetrics, flagMySQL)
info, err := admin.AddMetrics(ctx, mysqlMetrics, false, flagDisableSSL)
if err != nil {
fmt.Println("Error adding MySQL metrics:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring MySQL metrics using DSN", utils.SanitizeDSN(info.DSN))
},
}
cmdAddMySQLQueries = &cobra.Command{
Use: "mysql:queries [flags] [name]",
Short: "Add MySQL instance to Query Analytics.",
Long: `This command adds the given MySQL instance to Query Analytics.
When adding a MySQL instance, this tool tries to auto-detect the DSN and credentials.
If you want to create a new user to be used for query collecting, provide --create-user option. pmm-admin will create
a new user 'pmm@' automatically using the given (auto-detected) MySQL credentials for granting purpose.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: ` pmm-admin add mysql:queries --password abc123
pmm-admin add mysql:queries --password abc123 --create-user
pmm-admin add mysql:metrics --password abc123 --port 3307 instance3307
pmm-admin add mysql:queries --user rdsuser --password abc123 --host my-rds.1234567890.us-east-1.rds.amazonaws.com my-rds`,
Run: func(cmd *cobra.Command, args []string) {
// Agent does not accept additional arguments, we start it through qan-api.
if len(admin.Args) > 0 {
msg := `Command pmm-admin add mysql:queries does not accept additional flags: %s.
Type pmm-admin add mysql:queries --help to see all acceptable flags.
`
fmt.Printf(msg, strings.Join(admin.Args, ", "))
os.Exit(1)
}
// Check --query-source flag.
if flagMySQLQueries.QuerySource != "auto" && flagMySQLQueries.QuerySource != "slowlog" && flagMySQLQueries.QuerySource != "perfschema" {
fmt.Println("Flag --query-source can take the following values: auto, slowlog, perfschema.")
os.Exit(1)
}
mysqlQueries := mysqlQueries.New(flagQueries, flagMySQLQueries, flagMySQL)
info, err := admin.AddQueries(ctx, mysqlQueries)
if err != nil {
fmt.Println("Error adding MySQL queries:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring MySQL queries from", info.QuerySource,
"using DSN", utils.SanitizeDSN(info.DSN))
},
}
cmdAddPostgreSQL = &cobra.Command{
Use: "postgresql [flags] [name]",
Short: "Add complete monitoring for PostgreSQL instance (linux and postgresql metrics).",
Long: `This command adds the given PostgreSQL instance to system and metrics monitoring.
When adding a PostgreSQL instance, this tool tries to auto-detect the DSN and credentials.
If you want to create a new user to be used for metrics collecting, provide --create-user option. pmm-admin will create
a new user 'pmm' automatically using the given (auto-detected) PostgreSQL credentials for granting purpose.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: ` pmm-admin add postgresql --password abc123
pmm-admin add postgresql --password abc123 --create-user
pmm-admin add postgresql --password abc123 --port 3307 instance3307`,
Run: func(cmd *cobra.Command, args []string) {
// Passing additional arguments doesn't make sense because this command enables multiple exporters.
if len(admin.Args) > 0 {
fmt.Printf("We can't determine which exporter should receive additional flags: %s.\n", strings.Join(admin.Args, ", "))
fmt.Println("To pass additional arguments to specific exporter you need to add it separately e.g.:")
fmt.Println("pmm-admin add linux:metrics -- ", strings.Join(admin.Args, " "))
fmt.Println("or")
fmt.Println("pmm-admin add postgresql:metrics -- ", strings.Join(admin.Args, " "))
os.Exit(1)
}
linuxMetrics := linuxMetrics.New()
_, err := admin.AddMetrics(ctx, linuxMetrics, flagForce, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[linux:metrics] OK, already monitoring this system.")
} else if err != nil {
fmt.Println("[linux:metrics] Error adding linux metrics:", err)
os.Exit(1)
} else {
fmt.Println("[linux:metrics] OK, now monitoring this system.")
}
postgresqlMetrics := postgresqlMetrics.New(flagPostgreSQL)
info, err := admin.AddMetrics(ctx, postgresqlMetrics, false, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[postgresql:metrics] OK, already monitoring PostgreSQL metrics.")
} else if err != nil {
fmt.Println("[postgresql:metrics] Error adding PostgreSQL metrics:", err)
os.Exit(1)
} else {
fmt.Println("[postgresql:metrics] OK, now monitoring PostgreSQL metrics using DSN", utils.SanitizeDSN(info.DSN))
}
},
}
cmdAddPostgreSQLMetrics = &cobra.Command{
Use: "postgresql:metrics [flags] [name] [-- [exporter_args]]",
Short: "Add PostgreSQL instance to metrics monitoring.",
Long: `This command adds the given PostgreSQL instance to metrics monitoring.
When adding a PostgreSQL instance, this tool tries to auto-detect the DSN and credentials.
If you want to create a new user to be used for metrics collecting, provide --create-user option. pmm-admin will create
a new user 'pmm' automatically using the given (auto-detected) PostgreSQL credentials for granting purpose.
[name] is an optional argument, by default it is set to the client name of this PMM client.
[exporter_args] are the command line options to be passed directly to Prometheus Exporter.
`,
Example: ` pmm-admin add postgresql:metrics --password abc123
pmm-admin add postgresql:metrics --password abc123 --create-user
pmm-admin add postgresql:metrics --password abc123 --port 3307 instance3307
pmm-admin add postgresql:metrics --user rdsuser --password abc123 --host my-rds.1234567890.us-east-1.rds.amazonaws.com my-rds
pmm-admin add postgresql:metrics -- --extend.query-path /path/to/queries.yaml`,
Run: func(cmd *cobra.Command, args []string) {
postgresqlMetrics := postgresqlMetrics.New(flagPostgreSQL)
info, err := admin.AddMetrics(ctx, postgresqlMetrics, false, flagDisableSSL)
if err != nil {
fmt.Println("Error adding PostgreSQL metrics:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring PostgreSQL metrics using DSN", utils.SanitizeDSN(info.DSN))
},
}
cmdAddMongoDB = &cobra.Command{
Use: "mongodb [flags] [name]",
Short: "Add complete monitoring for MongoDB instance (linux and mongodb metrics, queries).",
Long: `This command adds the given MongoDB instance to system, metrics and queries monitoring.
When adding a MongoDB instance, you may provide --uri if the default one does not work for you.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: ` pmm-admin add mongodb
pmm-admin add mongodb --cluster bare-metal`,
Run: func(cmd *cobra.Command, args []string) {
// Passing additional arguments doesn't make sense because this command enables multiple exporters.
if len(admin.Args) > 0 {
fmt.Printf("We can't determine which exporter should receive additional flags: %s.\n", strings.Join(admin.Args, ", "))
fmt.Println("To pass additional arguments to specific exporter you need to add it separately e.g.:")
fmt.Println("pmm-admin add linux:metrics -- ", strings.Join(admin.Args, " "))
fmt.Println("or")
fmt.Println("pmm-admin add mongodb:metrics -- ", strings.Join(admin.Args, " "))
os.Exit(1)
}
linuxMetrics := linuxMetrics.New()
_, err := admin.AddMetrics(ctx, linuxMetrics, flagForce, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[linux:metrics] OK, already monitoring this system.")
} else if err != nil {
fmt.Println("[linux:metrics] Error adding linux metrics:", err)
os.Exit(1)
} else {
fmt.Println("[linux:metrics] OK, now monitoring this system.")
}
mongodbMetrics := mongodbMetrics.New(flagMongoURI, admin.Args, flagCluster, pmm.PMMBaseDir)
info, err := admin.AddMetrics(ctx, mongodbMetrics, false, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[mongodb:metrics] OK, already monitoring MongoDB metrics.")
} else if err != nil {
fmt.Println("[mongodb:metrics] Error adding MongoDB metrics:", err)
os.Exit(1)
} else {
fmt.Println("[mongodb:metrics] OK, now monitoring MongoDB metrics using URI", utils.SanitizeDSN(info.DSN))
}
mongodbQueries := mongodbQueries.New(flagQueries, flagMongoURI, admin.Args, pmm.PMMBaseDir)
info, err = admin.AddQueries(ctx, mongodbQueries)
if err == pmm.ErrDuplicate {
fmt.Println("[mongodb:queries] OK, already monitoring MongoDB queries.")
} else if err != nil {
fmt.Println("[mongodb:queries] Error adding MongoDB queries:", err)
os.Exit(1)
} else {
fmt.Println("[mongodb:queries] OK, now monitoring MongoDB queries using URI", utils.SanitizeDSN(info.DSN))
fmt.Println("[mongodb:queries] It is required for correct operation that profiling of monitored MongoDB databases be enabled.")
fmt.Println("[mongodb:queries] Note that profiling is not enabled by default because it may reduce the performance of your MongoDB server.")
fmt.Println("[mongodb:queries] For more information read PMM documentation (https://www.percona.com/doc/percona-monitoring-and-management/conf-mongodb.html).")
}
},
}
cmdAddMongoDBMetrics = &cobra.Command{
Use: "mongodb:metrics [flags] [name] [-- [exporter_args]]",
Short: "Add MongoDB instance to metrics monitoring.",
Long: `This command adds the given MongoDB instance to metrics monitoring.
When adding a MongoDB instance, you may provide --uri if the default one does not work for you.
[name] is an optional argument, by default it is set to the client name of this PMM client.
[exporter_args] are the command line options to be passed directly to Prometheus Exporter.
`,
Example: ` pmm-admin add mongodb:metrics
pmm-admin add mongodb:metrics --cluster bare-metal
pmm-admin add mongodb:metrics -- --mongodb.tls`,
Run: func(cmd *cobra.Command, args []string) {
mongodbMetrics := mongodbMetrics.New(flagMongoURI, admin.Args, flagCluster, pmm.PMMBaseDir)
info, err := admin.AddMetrics(ctx, mongodbMetrics, false, flagDisableSSL)
if err != nil {
fmt.Println("Error adding MongoDB metrics:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring MongoDB metrics using URI", utils.SanitizeDSN(info.DSN))
},
}
cmdAddMongoDBQueries = &cobra.Command{
Use: "mongodb:queries [flags] [name]",
Short: "Add MongoDB instance to Query Analytics.",
Long: `This command adds the given MongoDB instance to Query Analytics.
When adding a MongoDB instance, you may provide --uri if the default one does not work for you.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: ` pmm-admin add mongodb:queries
pmm-admin add mongodb:queries`,
Run: func(cmd *cobra.Command, args []string) {
// Agent does not accept additional arguments, we start it through qan-api.
if len(admin.Args) > 0 {
msg := `Command pmm-admin add mongodb:queries does not accept additional flags: %s.
Type pmm-admin add mongodb:queries --help to see all acceptable flags.
`
fmt.Printf(msg, strings.Join(admin.Args, ", "))
os.Exit(1)
}
mongodbQueries := mongodbQueries.New(flagQueries, flagMongoURI, admin.Args, pmm.PMMBaseDir)
info, err := admin.AddQueries(ctx, mongodbQueries)
if err == pmm.ErrDuplicate {
fmt.Println("Error adding MongoDB queries:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring MongoDB queries using URI", utils.SanitizeDSN(info.DSN))
fmt.Println("It is required for correct operation that profiling of monitored MongoDB databases be enabled.")
fmt.Println("Note that profiling is not enabled by default because it may reduce the performance of your MongoDB server.")
fmt.Println("For more information read PMM documentation (https://www.percona.com/doc/percona-monitoring-and-management/conf-mongodb.html).")
},
}
cmdAddProxySQL = &cobra.Command{
Use: "proxysql [flags] [name]",
Short: "Add complete monitoring for ProxySQL instance (linux and proxysql metrics).",
Long: `This command adds the given ProxySQL instance to system and metrics monitoring.
When adding a ProxySQL instance, you may provide --dsn if the default one does not work for you.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: ` pmm-admin add proxysql --dsn "stats:stats@tcp(localhost:6032)/"`,
Run: func(cmd *cobra.Command, args []string) {
// Passing additional arguments doesn't make sense because this command enables multiple exporters.
if len(admin.Args) > 0 {
fmt.Printf("We can't determine which exporter should receive additional flags: %s.\n", strings.Join(admin.Args, ", "))
fmt.Println("To pass additional arguments to specific exporter you need to add it separately e.g.:")
fmt.Println("pmm-admin add linux:metrics -- ", strings.Join(admin.Args, " "))
fmt.Println("or")
fmt.Println("pmm-admin add proxysql:metrics -- ", strings.Join(admin.Args, " "))
os.Exit(1)
}
linuxMetrics := linuxMetrics.New()
_, err := admin.AddMetrics(ctx, linuxMetrics, flagForce, flagDisableSSL)
if err == pmm.ErrDuplicate {
fmt.Println("[linux:metrics] OK, already monitoring this system.")
} else if err != nil {
fmt.Println("[linux:metrics] Error adding linux metrics:", err)
os.Exit(1)
} else {
fmt.Println("[linux:metrics] OK, now monitoring this system.")
}
proxysqlMetrics := proxysqlMetrics.New(flagDSN)
info, err := admin.AddMetrics(ctx, proxysqlMetrics, false, flagDisableSSL)
if err != nil {
fmt.Println("Error adding proxysql metrics:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring ProxySQL metrics using DSN", utils.SanitizeDSN(info.DSN))
},
}
cmdAddProxySQLMetrics = &cobra.Command{
Use: "proxysql:metrics [flags] [name] [-- [exporter_args]]",
Short: "Add ProxySQL instance to metrics monitoring.",
Long: `This command adds the given ProxySQL instance to metrics monitoring.
[name] is an optional argument, by default it is set to the client name of this PMM client.
[exporter_args] are the command line options to be passed directly to Prometheus Exporter.
`,
Run: func(cmd *cobra.Command, args []string) {
proxysqlMetrics := proxysqlMetrics.New(flagDSN)
info, err := admin.AddMetrics(ctx, proxysqlMetrics, false, flagDisableSSL)
if err != nil {
fmt.Println("Error adding proxysql metrics:", err)
os.Exit(1)
}
fmt.Println("OK, now monitoring ProxySQL metrics using DSN", utils.SanitizeDSN(info.DSN))
},
}
cmdAddExternalService = &cobra.Command{
Use: "external:service job_name [instance] --service-port=port",
Short: "Add external Prometheus exporter running on this host to new or existing scrape job for metrics monitoring.",
Long: `Add external Prometheus exporter running on this host to new or existing scrape job for metrics monitoring.
[instance] is an optional argument, by default it is set to the client name of this PMM client.
`,
Example: "pmm-admin add external:service postgresql --service-port=9187 --timeout=10s",
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
if flagServicePort == 0 {
fmt.Println("--service-port flag is required.")
os.Exit(1)
}
target := net.JoinHostPort(admin.Config.BindAddress, strconv.Itoa(flagServicePort))
instance := admin.Config.ClientName
if len(args) > 1 { // zeroth arg is admin.ServiceName
instance = args[1]
}
exp := &pmm.ExternalMetrics{
JobName: admin.ServiceName,
ScrapeInterval: flagExtInterval,
ScrapeTimeout: flagExtTimeout,
MetricsPath: flagExtPath,
Scheme: flagExtScheme,
Targets: []pmm.ExternalTarget{{
Target: target,
Labels: []pmm.ExternalLabelPair{{
Name: "instance",
Value: instance,
}},
}},
}
if err := admin.AddExternalService(context.TODO(), exp, flagForce); err != nil {
fmt.Println("Error adding external service:", err)
os.Exit(1)
}
fmt.Println("External service added.")
},
}
cmdAddExternalMetrics = &cobra.Command{
Use: "external:metrics job_name [host1:port1[=instance1]] [host2:port2[=instance2]] ...",
Short: "Add external Prometheus exporters job to metrics monitoring.",
Long: `This command adds external Prometheus exporters job with given name to metrics monitoring.
An optional list of instances (scrape targets) can be provided.
`,
Example: "pmm-admin add external:service postgresql --service-port=9187 --timeout=10s",
Args: cobra.MinimumNArgs(2),
Run: func(cmd *cobra.Command, args []string) {
if flagServicePort != 0 {
fmt.Println("--service-port should not be used with this command.")
os.Exit(1)
}
var targets []pmm.ExternalTarget
for _, arg := range args[1:] { // zeroth arg is admin.ServiceName
parts := strings.Split(arg, "=")
if len(parts) > 2 {
fmt.Printf("Unexpected syntax for %q.\n", arg)
os.Exit(1)
}
target := parts[0]
if _, _, err := net.SplitHostPort(target); err != nil {
fmt.Printf("Unexpected syntax for %q: %s. \n", arg, err)
os.Exit(1)
}
t := pmm.ExternalTarget{
Target: target,
}
if len(parts) == 2 {
// so both 1.2.3.4:9000=host1 and 1.2.3.4:9000="host1" work
instance, _ := strconv.Unquote(parts[1])
if instance == "" {
instance = parts[1]
}
t.Labels = []pmm.ExternalLabelPair{{
Name: "instance",
Value: instance,
}}
}
targets = append(targets, t)
}
exp := &pmm.ExternalMetrics{
JobName: admin.ServiceName, // zeroth arg
ScrapeInterval: flagExtInterval,
ScrapeTimeout: flagExtTimeout,
MetricsPath: flagExtPath,
Scheme: flagExtScheme,
Targets: targets,
}
if err := admin.AddExternalMetrics(context.TODO(), exp, !flagForce); err != nil {
fmt.Println("Error adding external metrics:", err)
os.Exit(1)
}
fmt.Println("External metrics added.")
},
}
cmdAddExternalInstances = &cobra.Command{
Use: "external:instances job_name [host1:port1[=instance1]] [host2:port2[=instance2]] ...",
Short: "Add external Prometheus exporters instances to existing metrics monitoring job.",
Long: `This command adds external Prometheus exporters instances (scrape targets) to existing metrics monitoring job.
`,
Args: cobra.MinimumNArgs(2),
Run: func(cmd *cobra.Command, args []string) {
if flagServicePort != 0 {
fmt.Println("--service-port should not be used with this command.")
os.Exit(1)
}
var targets []pmm.ExternalTarget
for _, arg := range args[1:] { // zeroth arg is admin.ServiceName
parts := strings.Split(arg, "=")
if len(parts) > 2 {
fmt.Printf("Unexpected syntax for %q.\n", arg)
os.Exit(1)
}
target := parts[0]
if _, _, err := net.SplitHostPort(target); err != nil {
fmt.Printf("Unexpected syntax for %q: %s. \n", arg, err)
os.Exit(1)
}
t := pmm.ExternalTarget{
Target: target,
}
if len(parts) == 2 {
// so both 1.2.3.4:9000=host1 and 1.2.3.4:9000="host1" work
instance, _ := strconv.Unquote(parts[1])
if instance == "" {
instance = parts[1]
}
t.Labels = []pmm.ExternalLabelPair{{
Name: "instance",
Value: instance,
}}
}
targets = append(targets, t)
}
if err := admin.AddExternalInstances(context.TODO(), admin.ServiceName, targets, !flagForce); err != nil {
fmt.Println("Error adding external instances:", err)
os.Exit(1)
}
fmt.Println("External instances added.")
},
}
cmdRemove = &cobra.Command{
Use: "remove",
Aliases: []string{"rm"},
Short: "Remove service from monitoring.",
Long: "This command is used to remove one monitoring service or all.",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cmd.Root().PersistentPreRun(cmd.Root(), args)
admin.ServiceName = admin.Config.ClientName
if len(args) > 0 {
admin.ServiceName = args[0]
}
},
Run: func(cmd *cobra.Command, args []string) {
if flagAll {
count, err := admin.RemoveAllMonitoring(false)
if err != nil {
fmt.Printf("Error removing one of the services: %s\n", err)
os.Exit(1)
}
if count == 0 {
fmt.Println("OK, no services found.")
} else {
fmt.Printf("OK, %d services were removed.\n", count)
}
os.Exit(0)
}
cmd.Usage()
os.Exit(1)
},
}
cmdRemoveMySQL = &cobra.Command{
Use: "mysql [flags] [name]",
Short: "Remove all monitoring for MySQL instance (linux and mysql metrics, queries).",
Long: `This command removes all monitoring for MySQL instance (linux and mysql metrics, queries).
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
err := admin.RemoveMetrics("linux")
if err == pmm.ErrNoService {
fmt.Printf("[linux:metrics] OK, no system %s under monitoring.\n", admin.ServiceName)
} else if err != nil {
fmt.Printf("[linux:metrics] Error removing linux metrics %s: %s\n", admin.ServiceName, err)
} else {
fmt.Printf("[linux:metrics] OK, removed system %s from monitoring.\n", admin.ServiceName)
}
err = admin.RemoveMetrics("mysql")
if err == pmm.ErrNoService {
fmt.Printf("[mysql:metrics] OK, no MySQL metrics %s under monitoring.\n", admin.ServiceName)
} else if err != nil {
fmt.Printf("[mysql:metrics] Error removing MySQL metrics %s: %s\n", admin.ServiceName, err)
} else {
fmt.Printf("[mysql:metrics] OK, removed MySQL metrics %s from monitoring.\n", admin.ServiceName)
}
err = admin.RemoveQueries("mysql")
if err == pmm.ErrNoService {
fmt.Printf("[mysql:queries] OK, no MySQL queries %s under monitoring.\n", admin.ServiceName)
} else if err != nil {
fmt.Printf("[mysql:queries] Error removing MySQL queries %s: %s\n", admin.ServiceName, err)
} else {
fmt.Printf("[mysql:queries] OK, removed MySQL queries %s from monitoring.\n", admin.ServiceName)
}
},
}
cmdRemoveLinuxMetrics = &cobra.Command{
Use: "linux:metrics [flags] [name]",
Short: "Remove this system from metrics monitoring.",
Long: `This command removes this system from linux metrics monitoring.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
if err := admin.RemoveMetrics("linux"); err != nil {
fmt.Printf("Error removing linux metrics %s: %s\n", admin.ServiceName, err)
os.Exit(1)
}
fmt.Printf("OK, removed system %s from monitoring.\n", admin.ServiceName)
},
}
cmdRemoveMySQLMetrics = &cobra.Command{
Use: "mysql:metrics [flags] [name]",
Short: "Remove MySQL instance from metrics monitoring.",
Long: `This command removes MySQL instance from metrics monitoring.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
if err := admin.RemoveMetrics("mysql"); err != nil {
fmt.Printf("Error removing MySQL metrics %s: %s\n", admin.ServiceName, err)
os.Exit(1)
}
fmt.Printf("OK, removed MySQL metrics %s from monitoring.\n", admin.ServiceName)
},
}
cmdRemoveMySQLQueries = &cobra.Command{
Use: "mysql:queries [flags] [name]",
Short: "Remove MySQL instance from Query Analytics.",
Long: `This command removes MySQL instance from Query Analytics.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
if err := admin.RemoveQueries("mysql"); err != nil {
fmt.Printf("Error removing MySQL queries %s: %s\n", admin.ServiceName, err)
os.Exit(1)
}
fmt.Printf("OK, removed MySQL queries %s from monitoring.\n", admin.ServiceName)
},
}
cmdRemoveMongoDB = &cobra.Command{
Use: "mongodb [flags] [name]",
Short: "Remove all monitoring for MongoDB instance (linux and mongodb metrics).",
Long: `This command removes all monitoring for MongoDB instance (linux and mongodb metrics).
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
err := admin.RemoveMetrics("linux")
if err == pmm.ErrNoService {
fmt.Printf("[linux:metrics] OK, no system %s under monitoring.\n", admin.ServiceName)
} else if err != nil {
fmt.Printf("[linux:metrics] Error removing linux metrics %s: %s\n", admin.ServiceName, err)
} else {
fmt.Printf("[linux:metrics] OK, removed system %s from monitoring.\n", admin.ServiceName)
}
err = admin.RemoveMetrics("mongodb")
if err == pmm.ErrNoService {
fmt.Printf("[mongodb:metrics] OK, no MongoDB metrics %s under monitoring.\n", admin.ServiceName)
} else if err != nil {
fmt.Printf("[mongodb:metrics] Error removing MongoDB metrics %s: %s\n", admin.ServiceName, err)
} else {
fmt.Printf("[mongodb:metrics] OK, removed MongoDB metrics %s from monitoring.\n", admin.ServiceName)
}
err = admin.RemoveQueries("mongodb")
if err == pmm.ErrNoService {
fmt.Printf("[mongodb:queries] OK, no MongoDB queries %s under monitoring.\n", admin.ServiceName)
} else if err != nil {
fmt.Printf("[mongodb:queries] Error removing MongoDB queries %s: %s\n", admin.ServiceName, err)
} else {
fmt.Printf("[mongodb:queries] OK, removed MongoDB queries %s from monitoring.\n", admin.ServiceName)
}
},
}
cmdRemoveMongoDBMetrics = &cobra.Command{
Use: "mongodb:metrics [flags] [name]",
Short: "Remove MongoDB instance from metrics monitoring.",
Long: `This command removes MongoDB instance from metrics monitoring.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
if err := admin.RemoveMetrics("mongodb"); err != nil {
fmt.Printf("Error removing MongoDB metrics %s: %s\n", admin.ServiceName, err)
os.Exit(1)
}
fmt.Printf("OK, removed MongoDB metrics %s from monitoring.\n", admin.ServiceName)
},
}
cmdRemoveMongoDBQueries = &cobra.Command{
Use: "mongodb:queries [flags] [name]",
Short: "Remove MongoDB instance from Query Analytics.",
Long: `This command removes MongoDB instance from Query Analytics.
[name] is an optional argument, by default it is set to the client name of this PMM client.
`,
Run: func(cmd *cobra.Command, args []string) {
if err := admin.RemoveQueries("mongodb"); err != nil {
fmt.Printf("Error removing MongoDB queries %s: %s\n", admin.ServiceName, err)
os.Exit(1)
}
fmt.Printf("OK, removed MongoDB queries %s from monitoring.\n", admin.ServiceName)
},
}
cmdRemovePostgreSQL = &cobra.Command{
Use: "postgresql [flags] [name]",
Short: "Remove all monitoring for PostgreSQL instance (linux and postgresql metrics).",
Long: `This command removes all monitoring for PostgreSQL instance (linux and mysql metrics).