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
/
pmm-admin_test.go
2546 lines (2275 loc) · 64.1 KB
/
pmm-admin_test.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 (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"github.com/hashicorp/consul/api"
"github.com/percona/pmm-client/pmm"
"github.com/percona/pmm-client/tests/fakeapi"
"github.com/percona/pmm/proto"
pc "github.com/percona/pmm/proto/config"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
type pmmAdminData struct {
bin string
rootDir string
}
func TestPmmAdmin(t *testing.T) {
var err error
// We can't/shouldn't use /usr/local/percona/ (the default basedir), so use
// a tmpdir instead with roughly the same structure.
rootDir, err := ioutil.TempDir("/tmp", "pmm-client-test-rootdir-")
assert.Nil(t, err)
defer func() {
err := os.RemoveAll(rootDir)
assert.Nil(t, err)
}()
binDir, err := ioutil.TempDir("/tmp", "pmm-client-test-bindir-")
assert.Nil(t, err)
defer func() {
err := os.RemoveAll(binDir)
assert.Nil(t, err)
}()
bin := binDir + "/pmm-admin"
xVariables := map[string]string{
"github.com/percona/pmm-client/pmm.Version": "gotest",
"github.com/percona/pmm-client/pmm.RootDir": rootDir,
}
var ldflags []string
for x, value := range xVariables {
ldflags = append(ldflags, fmt.Sprintf("-X %s=%s", x, value))
}
cmd := exec.Command(
"go",
"build",
"-o",
bin,
"-ldflags",
strings.Join(ldflags, " "),
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
assert.Nil(t, err, "Failed to build: %s", err)
data := pmmAdminData{
bin: bin,
rootDir: rootDir,
}
tests := []func(*testing.T, pmmAdminData){
testAddMongoDB,
testAddMongoDBAdditionalParamsErr,
testAddMongoDBMetrics,
testAddMongoDBMetricsErr,
testAddMongoDBQueries,
testAddMongoDBQueriesWithAdditionalParamsErr,
testAddPostgreSQL,
testAddPostgreSQLMetrics,
testAddPostgreSQLMetricsErr,
testAddPostgreSQLWithCreateUser,
testAddMySQL,
testAddMySQLAdditionalParamsErr,
testAddMySQLMetrics,
testAddMySQLQueryWithAdditionalParamsErr,
testAddMySQLMetricsErr,
testAddMySQLWithCreateUser,
testAddMySQLWithDisableSlowLogsRotation,
testAddMySQLWithRetainSlowLogs,
testAddLinuxMetricsWithAdditionalArgsOk,
testAddLinuxMetricsWithAdditionalArgsFail,
testCheckNetwork,
testConfig,
testConfigVerbose,
testConfigVerboseServerNotAvailable,
testConfigServerHideCredentials,
testHelp,
testHelpAddPostgreSQL,
testListEmpty,
testListNonEmpty,
testStartStopRestart,
testStartStopRestartAllWithNoServices,
testStartStopRestartAllWithServices,
testStartStopRestartNoServiceFound,
testVersion,
}
t.Run("pmm-admin", func(t *testing.T) {
for _, f := range tests {
f := f // capture range variable
fName := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
t.Run(fName, func(t *testing.T) {
// t.Parallel()
f(t, data)
})
}
})
}
func testVersion(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
cmd := exec.Command(
data.bin,
"--version",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
// sanity check that version number was changed with ldflag for this test build
assert.Equal(t, "1.17.5", pmm.Version)
expected := `gotest`
assertRegexpLines(t, expected, string(output))
}
func testHelp(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
expected := `Usage:
pmm-admin \[flags\]
pmm-admin \[command\]
Available Commands:
config Configure PMM Client.
add Add service to monitoring.
annotate Annotate application events.
remove Remove service from monitoring.
list List monitoring services for this system.
info Display PMM Client information \(works offline\).
check-network Check network connectivity between client and server.
ping Check if PMM server is alive.
start Start monitoring service.
stop Stop monitoring service.
restart Restart monitoring service.
show-passwords Show PMM Client password information \(works offline\).
purge Purge metrics data on PMM server.
repair Repair installation.
uninstall Removes all monitoring services with the best effort.
summary Fetch system data for diagnostics.
help Help about any command
Flags:
-c, --config-file string PMM config file \(default ".*"\)
-h, --help help for pmm-admin
--skip-root skip UID check \(experimental\)
--timeout duration timeout \(default 5s\)
--verbose verbose output
-v, --version show version
Use "pmm-admin \[command\] --help" for more information about a command.
`
t.Run("command", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"help",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
actual := string(output)
assertRegexpLines(t, expected, actual)
})
t.Run("flag", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"--help",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
actual := string(output)
assertRegexpLines(t, expected, actual)
})
}
func testHelpAddPostgreSQL(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
expected := `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.
Usage:
pmm-admin add postgresql \[flags\] \[name\]
Examples:
pmm-admin add postgresql --password abc123
pmm-admin add postgresql --password abc123 --create-user
pmm-admin add postgresql --password abc123 --port 3307 instance3307
Flags:
--create-user create a new PostgreSQL user
--create-user-password string optional password for a new PostgreSQL user
--disable-ssl disable ssl mode on exporter
--force force to create/update PostgreSQL user
-h, --help help for postgresql
--host string PostgreSQL host
--password string PostgreSQL password
--port string PostgreSQL port
--sslmode string PostgreSQL SSL Mode: disable, require, verify-full or verify-ca \(default "disable"\)
--user string PostgreSQL username
Global Flags:
-c, --config-file string PMM config file \(default ".*"\)
--service-port int service port
--skip-root skip UID check \(experimental\)
--timeout duration timeout \(default 5s\)
--verbose verbose output
`
t.Run("command", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"add", "postgresql",
"--help",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
actual := string(output)
assertRegexpLines(t, expected, actual)
})
}
func testConfig(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
os.MkdirAll(data.rootDir+pmm.PMMBaseDir, 0777)
// Create fake api server
fapi := fakeapi.New()
fapi.AppendRoot()
fapi.AppendQanAPIPing()
fapi.AppendConsulV1StatusLeader()
node := api.CatalogNode{
Node: &api.Node{},
}
clientName, _ := os.Hostname()
fapi.AppendConsulV1CatalogNode(clientName, node)
url, host, port := fapi.Start()
defer fapi.Close()
cmd := exec.Command(
data.bin,
"config",
"--server",
fmt.Sprintf("%s:%s", host, port),
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `OK, PMM server is alive.
` + fmt.Sprintf("%-15s | %s ", "PMM Server", host) + `
` + fmt.Sprintf("%-15s | %s", "Client Name", url) + `
` + fmt.Sprintf("%-15s | %s ", "Client Address", port) + `
`
assertRegexpLines(t, expected, string(output))
}
func testConfigVerbose(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
os.MkdirAll(data.rootDir+pmm.PMMBaseDir, 0777)
// Create fake api server
fapi := fakeapi.New()
clientName, _ := os.Hostname()
fapi.AppendRoot()
fapi.AppendQanAPIPing()
fapi.AppendConsulV1StatusLeader()
node := api.CatalogNode{
Node: &api.Node{},
}
fapi.AppendConsulV1CatalogNode(clientName, node)
_, host, port := fapi.Start()
hostPort := fmt.Sprintf("%s:%s", host, port)
defer fapi.Close()
cmd := exec.Command(
data.bin,
"config",
"--verbose",
"--server",
hostPort,
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
// with --verbose flag we should have bunch of http requests to server
expected := `.+ request:
> GET /qan-api/ping HTTP/1.1
> Host: ` + hostPort + `
> User-Agent: Go-http-client/1.1
> Accept-Encoding: gzip
>\s*
>\s*
.+ response:
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Date: .*
< X-Percona-Qan-Api-Version: gotest
< Content-Length: 0
<\s*
<\s*
.+ request:
> GET /v1/status/leader HTTP/1.1
> Host: ` + hostPort + `
> User-Agent: Go-http-client/1.1
> Accept-Encoding: gzip
>\s*
>\s*
.+ response:
< HTTP/1.1 200 OK
< Content-Length: 16
< Content-Type: text/plain; charset=utf-8
< Date: .*
< X-Remote-Ip: 127.0.0.1
< X-Server-Time: .*
<\s*
< "127.0.0.1:8300"
.+ request:
> GET /v1/catalog/node/` + clientName + ` HTTP/1.1
> Host: ` + hostPort + `
> User-Agent: Go-http-client/1.1
> Accept-Encoding: gzip
>\s*
>\s*
.+ response:
< HTTP/1.1 200 OK
< Content-Length: 140
< Content-Type: text/plain; charset=utf-8
< Date: .*
<\s*
< {"Node":{"ID":"","Node":"","Address":"","Datacenter":"","TaggedAddresses":null,"Meta":null,"CreateIndex":0,"ModifyIndex":0},"Services":null}
.+ request:
> GET /v1/status/leader HTTP/1.1
> Host: ` + hostPort + `
> User-Agent: Go-http-client/1.1
> Accept-Encoding: gzip
>\s*
>\s*
.+ response:
< HTTP/1.1 200 OK
< Content-Length: 16
< Content-Type: text/plain; charset=utf-8
< Date: .*
< X-Remote-Ip: 127.0.0.1
< X-Server-Time: .*
<\s*
< "127.0.0.1:8300"
OK, PMM server is alive.
PMM Server | ` + host + `
Client Name | ` + clientName + `
Client Address | ` + hostPort + `
`
assertRegexpLines(t, expected, string(output))
}
func testConfigVerboseServerNotAvailable(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
os.MkdirAll(data.rootDir+pmm.PMMBaseDir, 0777)
cmd := exec.Command(
data.bin,
"config",
"--verbose",
"--server",
"xyz",
)
output, err := cmd.CombinedOutput()
assert.Error(t, err)
// with --verbose flag we should have bunch of http requests to server
// however api is unavailable, so `--verbose` prints only request...
expected := `.* request:
> GET /qan-api/ping HTTP/1.1
> Host: xyz
> User-Agent: Go-http-client/1.1
> Accept-Encoding: gzip
>\s*
>\s*
Unable to connect to PMM server by address: xyz
Get http://xyz/qan-api/ping: dial tcp: lookup xyz.*: no such host
* Check if the configured address is correct.
* If server is running on non-default port, ensure it was specified along with the address.
* If server is enabled for SSL or self-signed SSL, enable the corresponding option.
* You may also check the firewall settings.
`
assertRegexpLines(t, expected, string(output))
}
func testConfigServerHideCredentials(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.NoError(t, err)
}()
err := os.MkdirAll(data.rootDir+pmm.PMMBaseDir, 0777)
assert.NoError(t, err)
cmd := exec.Command(
data.bin,
"config",
"--server",
fmt.Sprintf("%s:%s", "172.0.0.1", "8080"),
"--server-user",
"test",
"--server-password",
"123",
)
output, err := cmd.CombinedOutput()
assert.IsType(t, &exec.ExitError{}, err)
expected := `Unable to connect to PMM server by address: 172.0.0.1:8080
Get http://172.0.0.1:8080/qan-api/ping: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
* Check if the configured address is correct.
* If server is running on non-default port, ensure it was specified along with the address.
* If server is enabled for SSL or self-signed SSL, enable the corresponding option.
* You may also check the firewall settings.
`
assert.Equal(t, expected, string(output))
}
func testStartStopRestartAllWithNoServices(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
createFakeENV(t, data)
pmmConfig := pmm.Config{
ServerAddress: "just",
ClientName: "non",
ClientAddress: "empty",
BindAddress: "data",
}
bytes, _ := yaml.Marshal(pmmConfig)
ioutil.WriteFile(data.rootDir+pmm.PMMBaseDir+"/pmm.yml", bytes, 0600)
services := []string{
"start",
"stop",
"restart",
}
t.Run("service", func(t *testing.T) {
for _, service := range services {
service := service // capture range variable
t.Run(service, func(t *testing.T) {
t.Parallel()
cmd := exec.Command(
data.bin,
service,
"--all",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `OK, no services found.`
assertRegexpLines(t, expected, string(output))
})
}
})
}
func testListEmpty(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
createFakeENV(t, data)
// Create fake api server
fapi := fakeapi.New()
clientName := "test-client-name"
fapi.AppendRoot()
fapi.AppendQanAPIPing()
fapi.AppendConsulV1StatusLeader()
node := api.CatalogNode{
Node: &api.Node{},
}
fapi.AppendConsulV1CatalogNode(clientName, node)
fapi.AppendConsulV1KV()
fapi.AppendManaged()
_, host, port := fapi.Start()
defer fapi.Close()
pmmConfig := pmm.Config{
ServerAddress: fmt.Sprintf("%s:%s", host, port),
ClientName: clientName,
ClientAddress: "empty",
BindAddress: "data",
}
bytes, _ := yaml.Marshal(pmmConfig)
ioutil.WriteFile(data.rootDir+pmm.PMMBaseDir+"/pmm.yml", bytes, 0600)
// Test empty list
t.Run("list (empty)", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"list",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `pmm-admin gotest
PMM Server \| .*
Client Name \| test-client-name
Client Address \| .*
Service Manager \| .*
No services under monitoring.
`
assertRegexpLines(t, expected, string(output))
})
}
func testListNonEmpty(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
createFakeENV(t, data)
// Create fake api server
fapi := fakeapi.New()
clientName := "test-client-name"
fapi.AppendRoot()
fapi.AppendQanAPIPing()
fapi.AppendConsulV1StatusLeader()
node := api.CatalogNode{
Node: &api.Node{},
}
node.Services = map[string]*api.AgentService{
"a": {
ID: "id",
Service: "mysql:queries",
Port: 0,
Tags: []string{
fmt.Sprintf("alias_%s", clientName),
},
},
"b": {
ID: "id",
Service: "mongodb:queries",
Port: 0,
Tags: []string{
fmt.Sprintf("alias_%s", clientName),
},
},
}
fapi.AppendConsulV1CatalogNode(clientName, node)
fapi.AppendConsulV1KV()
fapi.AppendManaged()
_, host, port := fapi.Start()
defer fapi.Close()
pmmConfig := pmm.Config{
ServerAddress: fmt.Sprintf("%s:%s", host, port),
ClientName: clientName,
ClientAddress: "empty",
BindAddress: "data",
}
bytes, _ := yaml.Marshal(pmmConfig)
ioutil.WriteFile(data.rootDir+pmm.PMMBaseDir+"/pmm.yml", bytes, 0600)
// create fake system service
{
dir, extension := pmm.GetServiceDirAndExtension()
os.MkdirAll(data.rootDir+dir, 0777)
name := fmt.Sprintf("pmm-mysql-queries-0%s", extension)
os.Create(data.rootDir + dir + "/" + name)
}
{
dir, extension := pmm.GetServiceDirAndExtension()
os.MkdirAll(data.rootDir+dir, 0777)
name := fmt.Sprintf("pmm-mongodb-queries-0%s", extension)
os.Create(data.rootDir + dir + "/" + name)
}
// Test --help output
t.Run("list --help", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"list",
"--help",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `This command displays the list of monitoring services and their details.
Usage:
pmm-admin list \[flags\]
Aliases:
list, ls
Flags:
--format string print result using a Go template
-h, --help help for list
--json print result as json
Global Flags:
-c, --config-file string PMM config file \(default ".*?"\)
--skip-root skip UID check \(experimental\)
--timeout duration timeout \(default 5s\)
--verbose verbose output
`
assertRegexpLines(t, expected, string(output))
})
// Test text output
t.Run("list", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"list",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `pmm-admin gotest
PMM Server \| .*
Client Name \| test-client-name
Client Address \| .*
Service Manager \| .*
---------------- ----------------- ----------- -------- ------------ --------
SERVICE TYPE NAME LOCAL PORT RUNNING DATA SOURCE OPTIONS\s*
---------------- ----------------- ----------- -------- ------------ --------
mongodb:queries test-client-name - YES - \s*
mysql:queries test-client-name - YES - \s*
`
assertRegexpLines(t, expected, string(output))
})
// Test json output
t.Run("list --json", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"list",
"--json",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := pmm.List{
Version: "gotest",
ServerInfo: pmm.ServerInfo{
ClientName: "test-client-name",
ClientAddress: "empty",
ClientBindAddress: "(data)",
},
Services: []pmm.ServiceStatus{
{
Type: "mongodb:queries",
Name: "test-client-name",
Port: "-",
DSN: "-",
Running: true,
},
{
Type: "mysql:queries",
Name: "test-client-name",
Port: "-",
DSN: "-",
Running: true,
},
},
ExternalServices: []pmm.ExternalMetrics{},
}
got := pmm.List{}
err = json.Unmarshal(output, &got)
// we can't really test this data
got.Platform = ""
got.ServerAddress = ""
assert.Nil(t, err)
assert.Equal(t, expected, got)
})
// Test custom text template with table data ()
t.Run("list --format <table data>", func(t *testing.T) {
format := `SERVICE TYPE NAME LOCAL PORT RUNNING DATA SOURCE OPTIONS
{{range .Services}}{{.Type}} {{.Name}} {{.Port}} {{if .Running}}YES{{else}}NO{{end}} {{.DSN}} {{.Options}}
{{end}}`
cmd := exec.Command(
data.bin,
"list",
"--format", format,
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `SERVICE TYPE NAME LOCAL PORT RUNNING DATA SOURCE OPTIONS\s*
mongodb:queries test-client-name - YES -\s*
mysql:queries test-client-name - YES -\s*
`
assertRegexpLines(t, expected, string(output))
})
// Test custom format that produces just json list
t.Run("list --format '{{json .Services'}}", func(t *testing.T) {
format := `{{json .Services}}`
cmd := exec.Command(
data.bin,
"list",
"--format", format,
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `[{"Type":"mongodb:queries","Name":"test-client-name","Port":"-","Running":true,"DSN":"-","Options":"","SSL":"","Password":""},{"Type":"mysql:queries","Name":"test-client-name","Port":"-","Running":true,"DSN":"-","Options":"","SSL":"","Password":""}]`
assert.JSONEq(t, expected, string(output))
})
}
func testStartStopRestart(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
createFakeENV(t, data)
svcName := "mysql:queries"
// Create fake api server
fapi := fakeapi.New()
clientName := "test-client-name"
fapi.AppendRoot()
fapi.AppendQanAPIPing()
fapi.AppendConsulV1StatusLeader()
node := api.CatalogNode{
Node: &api.Node{},
Services: map[string]*api.AgentService{
"a": {
ID: "id",
Service: svcName,
Port: 0,
Tags: []string{
fmt.Sprintf("alias_%s", clientName),
},
},
},
}
fapi.AppendConsulV1CatalogNode(clientName, node)
_, host, port := fapi.Start()
defer fapi.Close()
pmmConfig := pmm.Config{
ServerAddress: fmt.Sprintf("%s:%s", host, port),
ClientName: clientName,
ClientAddress: "empty",
BindAddress: "data",
}
bytes, _ := yaml.Marshal(pmmConfig)
ioutil.WriteFile(data.rootDir+pmm.PMMBaseDir+"/pmm.yml", bytes, 0600)
// create fake system service
{
dir, extension := pmm.GetServiceDirAndExtension()
os.MkdirAll(data.rootDir+dir, 0777)
name := fmt.Sprintf("pmm-mysql-queries-0%s", extension)
os.Create(data.rootDir + dir + "/" + name)
}
t.Run("start", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"start",
svcName,
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := fmt.Sprintf("OK, service %s already %s for %s.", svcName, "started", clientName)
assertRegexpLines(t, expected, string(output))
})
t.Run("stop", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"stop",
svcName,
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := fmt.Sprintf("OK, %s %s service for %s.", "stopped", svcName, clientName)
assertRegexpLines(t, expected, string(output))
})
t.Run("restart", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"restart",
svcName,
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := fmt.Sprintf("OK, %s %s service for %s.", "restarted", svcName, clientName)
assertRegexpLines(t, expected, string(output))
})
}
func testStartStopRestartAllWithServices(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
createFakeENV(t, data)
pmmConfig := pmm.Config{
ServerAddress: "just",
ClientName: "non",
ClientAddress: "empty",
BindAddress: "data",
}
bytes, _ := yaml.Marshal(pmmConfig)
ioutil.WriteFile(data.rootDir+pmm.PMMBaseDir+"/pmm.yml", bytes, 0600)
// create fake system services
numOfServices := 3
{
dir, extension := pmm.GetServiceDirAndExtension()
os.MkdirAll(data.rootDir+dir, 0777)
for i := 0; i < numOfServices; i++ {
name := fmt.Sprintf("pmm-service-%d%s", i, extension)
os.Create(data.rootDir + dir + "/" + name)
}
}
t.Run("start", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"start",
"--all",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `OK, all services already started. Run 'pmm-admin list' to see monitoring services.
Unable to connect to PMM server by address: just
Get http://just/qan-api/ping: dial tcp: lookup just.*: no such host
* Check if the configured address is correct.
* If server is running on non-default port, ensure it was specified along with the address.
* If server is enabled for SSL or self-signed SSL, enable the corresponding option.
* You may also check the firewall settings.
`
assertRegexpLines(t, expected, string(output))
})
t.Run("stop", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"stop",
"--all",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := fmt.Sprintf("OK, %s %d services.\n", "stopped", numOfServices)
assertRegexpLines(t, expected, string(output))
})
t.Run("restart", func(t *testing.T) {
cmd := exec.Command(
data.bin,
"restart",
"--all",
)
output, err := cmd.CombinedOutput()
assert.Nil(t, err)
expected := `OK, restarted ` + fmt.Sprintf("%d", numOfServices) + ` services.
Unable to connect to PMM server by address: just
Get http://just/qan-api/ping: dial tcp: lookup just.*: no such host
* Check if the configured address is correct.
* If server is running on non-default port, ensure it was specified along with the address.
* If server is enabled for SSL or self-signed SSL, enable the corresponding option.
* You may also check the firewall settings.
`
assertRegexpLines(t, expected, string(output))
})
}
func testStartStopRestartNoServiceFound(t *testing.T, data pmmAdminData) {
defer func() {
err := os.RemoveAll(data.rootDir)
assert.Nil(t, err)
}()
createFakeENV(t, data)
// Create fake api server
fapi := fakeapi.New()
fapi.AppendRoot()
fapi.AppendQanAPIPing()
fapi.AppendConsulV1StatusLeader()
clientName, _ := os.Hostname()
node := api.CatalogNode{
Node: &api.Node{},
}
fapi.AppendConsulV1CatalogNode(clientName, node)
_, host, port := fapi.Start()
defer fapi.Close()
pmmConfig := pmm.Config{
ServerAddress: fmt.Sprintf("%s:%s", host, port),
ClientName: clientName,