-
Notifications
You must be signed in to change notification settings - Fork 447
/
utils.go
1443 lines (1295 loc) · 34.9 KB
/
utils.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 2015 Sorint.lab
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
// See the License for the specific language governing permissions and
// limitations under the License.
package integration
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"sync"
"testing"
"time"
"github.com/sorintlab/stolon/internal/cluster"
"github.com/sorintlab/stolon/internal/common"
pg "github.com/sorintlab/stolon/internal/postgresql"
"github.com/sorintlab/stolon/internal/store"
"github.com/sorintlab/stolon/internal/util"
"github.com/gofrs/uuid"
_ "github.com/lib/pq"
"github.com/sgotti/gexpect"
)
const (
sleepInterval = 500 * time.Millisecond
MinPort = 2048
MaxPort = 16384
)
var (
defaultPGParameters = cluster.PGParameters{"log_destination": "stderr", "logging_collector": "false"}
defaultStoreTimeout = 1 * time.Second
)
var curPort = MinPort
var portMutex = sync.Mutex{}
func pgParametersWithDefaults(p cluster.PGParameters) cluster.PGParameters {
pd := cluster.PGParameters{}
for k, v := range defaultPGParameters {
pd[k] = v
}
for k, v := range p {
pd[k] = v
}
return pd
}
type Querier interface {
Exec(query string, args ...interface{}) (sql.Result, error)
Query(query string, args ...interface{}) (*sql.Rows, error)
}
type ReplQuerier interface {
ReplQuery(query string, args ...interface{}) (*sql.Rows, error)
}
func GetPGParameters(q Querier) (common.Parameters, error) {
var pgParameters = common.Parameters{}
rows, err := q.Query("select name, setting, source from pg_settings")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var name, setting, source string
if err = rows.Scan(&name, &setting, &source); err != nil {
return nil, err
}
if source == "configuration file" {
pgParameters[name] = setting
}
}
return pgParameters, nil
}
func GetSystemData(q ReplQuerier) (*pg.SystemData, error) {
rows, err := q.ReplQuery("IDENTIFY_SYSTEM")
if err != nil {
return nil, err
}
defer rows.Close()
if rows.Next() {
var sd pg.SystemData
var xLogPosLsn string
var unused *string
if err = rows.Scan(&sd.SystemID, &sd.TimelineID, &xLogPosLsn, &unused); err != nil {
return nil, err
}
sd.XLogPos, err = pg.PGLsnToInt(xLogPosLsn)
if err != nil {
return nil, err
}
return &sd, nil
}
return nil, fmt.Errorf("query returned 0 rows")
}
func GetXLogPos(q ReplQuerier) (uint64, error) {
// get the current master XLogPos
systemData, err := GetSystemData(q)
if err != nil {
return 0, err
}
return systemData.XLogPos, nil
}
// getReplicatinSlots return existing replication slots (also temporary
// replication slots on PostgreSQL > 10)
func getReplicationSlots(q Querier) ([]string, error) {
replSlots := []string{}
rows, err := q.Query("select slot_name from pg_replication_slots")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var slotName string
if err := rows.Scan(&slotName); err != nil {
return nil, err
}
replSlots = append(replSlots, slotName)
}
return replSlots, nil
}
/*
// currently unused, keep for future needs
func waitReplicationSlots(q Querier, replSlots []string, timeout time.Duration) error {
sort.Strings(replSlots)
start := time.Now()
curReplSlots := []string{}
var err error
for time.Now().Add(-timeout).Before(start) {
curReplSlots, err := getReplicationSlots(q)
if err != nil {
goto end
}
sort.Strings(curReplSlots)
if reflect.DeepEqual(replSlots, curReplSlots) {
return nil
}
end:
time.Sleep(2 * time.Second)
}
return fmt.Errorf("timeout waiting for replSlots %v, got: %v, last err: %v", replSlots, curReplSlots, err)
}
*/
func waitStolonReplicationSlots(q Querier, replSlots []string, timeout time.Duration) error {
// prefix with stolon_
for i, slot := range replSlots {
replSlots[i] = common.StolonName(slot)
}
sort.Strings(replSlots)
start := time.Now()
var curReplSlots []string
var err error
for time.Now().Add(-timeout).Before(start) {
allReplSlots, err := getReplicationSlots(q)
if err != nil {
goto end
}
curReplSlots = []string{}
for _, s := range allReplSlots {
if common.IsStolonName(s) {
curReplSlots = append(curReplSlots, s)
}
}
sort.Strings(curReplSlots)
if reflect.DeepEqual(replSlots, curReplSlots) {
return nil
}
end:
time.Sleep(2 * time.Second)
}
return fmt.Errorf("timeout waiting for replSlots %v, got: %v, last err: %v", replSlots, curReplSlots, err)
}
func waitNotStolonReplicationSlots(q Querier, replSlots []string, timeout time.Duration) error {
sort.Strings(replSlots)
start := time.Now()
var curReplSlots []string
var err error
for time.Now().Add(-timeout).Before(start) {
allReplSlots, err := getReplicationSlots(q)
if err != nil {
goto end
}
curReplSlots = []string{}
for _, s := range allReplSlots {
if !common.IsStolonName(s) {
curReplSlots = append(curReplSlots, s)
}
}
sort.Strings(curReplSlots)
if reflect.DeepEqual(replSlots, curReplSlots) {
return nil
}
end:
time.Sleep(2 * time.Second)
}
return fmt.Errorf("timeout waiting for replSlots %v, got: %v, last err: %v", replSlots, curReplSlots, err)
}
type Process struct {
t *testing.T
uid string
name string
args []string
cmd *gexpect.ExpectSubprocess
bin string
}
func (p *Process) start() error {
if p.cmd != nil {
panic(fmt.Errorf("%s: cmd not cleanly stopped", p.uid))
}
cmd := exec.Command(p.bin, p.args...)
pr, pw, err := os.Pipe()
if err != nil {
return err
}
p.cmd = &gexpect.ExpectSubprocess{Cmd: cmd, Output: pw}
if err := p.cmd.Start(); err != nil {
return err
}
go func() {
scanner := bufio.NewScanner(pr)
for scanner.Scan() {
p.t.Logf("[%s %s]: %s", p.name, p.uid, scanner.Text())
}
}()
return nil
}
func (p *Process) Start() error {
if err := p.start(); err != nil {
return err
}
p.cmd.Continue()
return nil
}
func (p *Process) StartExpect() error {
return p.start()
}
func (p *Process) Signal(sig os.Signal) error {
p.t.Logf("signalling %s %s with %s", p.name, p.uid, sig)
if p.cmd == nil {
panic(fmt.Errorf("p: %s, cmd is empty", p.uid))
}
return p.cmd.Cmd.Process.Signal(sig)
}
func (p *Process) Kill() {
p.t.Logf("killing %s %s", p.name, p.uid)
if p.cmd == nil {
panic(fmt.Errorf("p: %s, cmd is empty", p.uid))
}
_ = p.cmd.Cmd.Process.Signal(os.Kill)
_ = p.cmd.Wait()
p.cmd = nil
}
func (p *Process) Stop() {
p.t.Logf("stopping %s %s", p.name, p.uid)
if p.cmd == nil {
panic(fmt.Errorf("p: %s, cmd is empty", p.uid))
}
p.cmd.Continue()
_ = p.cmd.Cmd.Process.Signal(os.Interrupt)
_ = p.cmd.Wait()
p.cmd = nil
}
func (p *Process) Wait(timeout time.Duration) error {
timeoutCh := time.NewTimer(timeout).C
endCh := make(chan error)
go func() {
err := p.cmd.Wait()
endCh <- err
}()
select {
case <-timeoutCh:
return fmt.Errorf("timeout waiting on process")
case <-endCh:
return nil
}
}
type TestKeeper struct {
t *testing.T
Process
dataDir string
pgListenAddress string
pgPort string
pgSUUsername string
pgSUPassword string
pgReplUsername string
pgReplPassword string
db *sql.DB
rdb *sql.DB
}
func NewTestKeeperWithID(t *testing.T, dir, uid, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestKeeper, error) {
args := []string{}
dataDir := filepath.Join(dir, fmt.Sprintf("st%s", uid))
pgListenAddress, pgPort, err := getFreePort(true, false)
if err != nil {
return nil, err
}
args = append(args, fmt.Sprintf("--uid=%s", uid))
args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
args = append(args, fmt.Sprintf("--pg-listen-address=%s", pgListenAddress))
args = append(args, fmt.Sprintf("--pg-port=%s", pgPort))
args = append(args, fmt.Sprintf("--data-dir=%s", dataDir))
args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
args = append(args, fmt.Sprintf("--pg-su-username=%s", pgSUUsername))
if pgSUPassword != "" {
args = append(args, fmt.Sprintf("--pg-su-password=%s", pgSUPassword))
}
args = append(args, fmt.Sprintf("--pg-repl-username=%s", pgReplUsername))
args = append(args, fmt.Sprintf("--pg-repl-password=%s", pgReplPassword))
if os.Getenv("DEBUG") != "" {
args = append(args, "--debug")
}
args = append(args, a...)
connParams := pg.ConnParams{
"user": pgSUUsername,
"password": pgSUPassword,
"host": pgListenAddress,
"port": pgPort,
"dbname": "postgres",
"sslmode": "disable",
}
replConnParams := pg.ConnParams{
"user": pgReplUsername,
"password": pgReplPassword,
"host": pgListenAddress,
"port": pgPort,
"dbname": "postgres",
"sslmode": "disable",
"replication": "1",
}
connString := connParams.ConnString()
db, err := sql.Open("postgres", connString)
if err != nil {
return nil, err
}
replConnString := replConnParams.ConnString()
rdb, err := sql.Open("postgres", replConnString)
if err != nil {
return nil, err
}
bin := os.Getenv("STKEEPER_BIN")
if bin == "" {
return nil, fmt.Errorf("missing STKEEPER_BIN env")
}
tk := &TestKeeper{
t: t,
Process: Process{
t: t,
uid: uid,
name: "keeper",
bin: bin,
args: args,
},
dataDir: dataDir,
pgListenAddress: pgListenAddress,
pgPort: pgPort,
pgSUUsername: pgSUUsername,
pgSUPassword: pgSUPassword,
pgReplUsername: pgReplUsername,
pgReplPassword: pgReplPassword,
db: db,
rdb: rdb,
}
return tk, nil
}
func NewTestKeeper(t *testing.T, dir, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestKeeper, error) {
u := uuid.Must(uuid.NewV4())
uid := fmt.Sprintf("%x", u[:4])
return NewTestKeeperWithID(t, dir, uid, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword, storeBackend, storeEndpoints, a...)
}
func (tk *TestKeeper) PGDataVersion() (int, int, error) {
fh, err := os.Open(filepath.Join(tk.dataDir, "postgres", "PG_VERSION"))
if err != nil {
return 0, 0, fmt.Errorf("failed to read PG_VERSION: %v", err)
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
scanner.Split(bufio.ScanLines)
scanner.Scan()
version := scanner.Text()
return pg.ParseVersion(version)
}
func (tk *TestKeeper) GetPrimaryConninfo() (pg.ConnParams, error) {
maj, _, err := tk.PGDataVersion()
if err != nil {
return nil, err
}
confFile := "recovery.conf"
if maj >= 12 {
confFile = "postgresql.conf"
}
regex := regexp.MustCompile(`\s*primary_conninfo\s*=\s*'(.*)'$`)
fh, err := os.Open(filepath.Join(tk.dataDir, "postgres", confFile))
if os.IsNotExist(err) {
return nil, nil
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
m := regex.FindStringSubmatch(scanner.Text())
if len(m) == 2 {
return pg.ParseConnString(m[1])
}
}
return nil, nil
}
func (tk *TestKeeper) Exec(query string, args ...interface{}) (sql.Result, error) {
res, err := tk.db.Exec(query, args...)
if err != nil {
return nil, err
}
return res, nil
}
func (tk *TestKeeper) Query(query string, args ...interface{}) (*sql.Rows, error) {
res, err := tk.db.Query(query, args...)
if err != nil {
return nil, err
}
return res, nil
}
func (tk *TestKeeper) ReplQuery(query string, args ...interface{}) (*sql.Rows, error) {
res, err := tk.rdb.Query(query, args...)
if err != nil {
return nil, err
}
return res, nil
}
func (tk *TestKeeper) SwitchWals(times int) error {
maj, _, err := tk.PGDataVersion()
if err != nil {
return err
}
var switchLogFunc string
if maj < 10 {
switchLogFunc = "select pg_switch_xlog()"
} else {
switchLogFunc = "select pg_switch_wal()"
}
_, _ = tk.Exec("DROP TABLE switchwal")
if _, err := tk.Exec("CREATE TABLE switchwal(ID INT PRIMARY KEY NOT NULL)"); err != nil {
return err
}
// if times > 1 we have to do some transactions or the wal won't switch
for i := 0; i < times; i++ {
if _, err := tk.Exec("INSERT INTO switchwal VALUES ($1)", i); err != nil {
return err
}
if _, err := tk.db.Exec(switchLogFunc); err != nil {
return err
}
}
_, _ = tk.Exec("DROP TABLE switchwal")
return nil
}
func (tk *TestKeeper) CheckPoint() error {
_, err := tk.Exec("CHECKPOINT")
return err
}
func (tk *TestKeeper) WaitDBUp(timeout time.Duration) error {
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
_, err := tk.Exec("select 1")
if err == nil {
return nil
}
tk.t.Logf("tk: %v, error: %v", tk.uid, err)
time.Sleep(sleepInterval)
}
return fmt.Errorf("timeout")
}
func (tk *TestKeeper) WaitDBDown(timeout time.Duration) error {
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
_, err := tk.Exec("select 1")
if err != nil {
return nil
}
time.Sleep(sleepInterval)
}
return fmt.Errorf("timeout")
}
func (tk *TestKeeper) GetPGProcess() (*os.Process, error) {
fh, err := os.Open(filepath.Join(tk.dataDir, "postgres/postmaster.pid"))
if err != nil {
return nil, err
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
scanner.Split(bufio.ScanLines)
if !scanner.Scan() {
return nil, fmt.Errorf("not enough lines in pid file")
}
pidStr := scanner.Text()
pid, err := strconv.Atoi(string(pidStr))
if err != nil {
return nil, err
}
return os.FindProcess(pid)
}
func (tk *TestKeeper) SignalPG(sig os.Signal) error {
p, err := tk.GetPGProcess()
if err != nil {
return err
}
return p.Signal(sig)
}
func (tk *TestKeeper) isInRecovery() (bool, error) {
rows, err := tk.Query("SELECT pg_is_in_recovery from pg_is_in_recovery()")
if err != nil {
return false, err
}
defer rows.Close()
if rows.Next() {
var isInRecovery bool
if err := rows.Scan(&isInRecovery); err != nil {
return false, err
}
if isInRecovery {
return true, nil
}
return false, nil
}
return false, fmt.Errorf("no rows returned")
}
func (tk *TestKeeper) WaitDBRole(r common.Role, ptk *TestKeeper, timeout time.Duration) error {
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
time.Sleep(sleepInterval)
// when the cluster is in standby mode also the master db is a standby
// so we cannot just check if the keeper is in recovery but have to
// check if the primary_conninfo points to the primary db or to the
// cluster master
if ptk == nil {
ok, err := tk.isInRecovery()
if err != nil {
continue
}
if !ok && r == common.RoleMaster {
return nil
}
if ok && r == common.RoleStandby {
return nil
}
} else {
ok, err := tk.isInRecovery()
if err != nil {
continue
}
if !ok {
continue
}
// TODO(sgotti) get this information from the running instance instead than from
// recovery.conf to be really sure it's applied
conninfo, err := tk.GetPrimaryConninfo()
if err != nil {
continue
}
if conninfo["host"] == ptk.pgListenAddress && conninfo["port"] == ptk.pgPort {
if r == common.RoleMaster {
return nil
}
} else {
if r == common.RoleStandby {
return nil
}
}
}
}
return fmt.Errorf("timeout")
}
func (tk *TestKeeper) WaitPGParameter(parameter, value string, timeout time.Duration) error {
latestValue := ""
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
pgParameters, err := GetPGParameters(tk)
if err != nil {
goto end
}
latestValue = pgParameters[parameter]
if latestValue == value {
return nil
}
end:
time.Sleep(sleepInterval)
}
return fmt.Errorf("timeout waiting for pgParamater %q (%q) to equal %q", parameter, latestValue, value)
}
func (tk *TestKeeper) GetPGParameters() (common.Parameters, error) {
return GetPGParameters(tk)
}
/*
// currently unused, keep for future needs
type CheckFunc func(time.Duration) error
func waitChecks(timeout time.Duration, fns ...CheckFunc) error {
end := make(chan error)
fnc := len(fns)
for _, fn := range fns {
go func(fn CheckFunc, end chan error) {
end <- fn(timeout)
}(fn, end)
}
c := 0
for c < fnc {
err := <-end
if err != nil {
return err
}
c++
}
return nil
}
*/
type TestSentinel struct {
t *testing.T
Process
}
func NewTestSentinel(t *testing.T, dir string, clusterName string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestSentinel, error) {
u := uuid.Must(uuid.NewV4())
uid := fmt.Sprintf("%x", u[:4])
args := []string{}
args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
if os.Getenv("DEBUG") != "" {
args = append(args, "--debug")
}
args = append(args, a...)
bin := os.Getenv("STSENTINEL_BIN")
if bin == "" {
return nil, fmt.Errorf("missing STSENTINEL_BIN env")
}
ts := &TestSentinel{
t: t,
Process: Process{
t: t,
uid: uid,
name: "sentinel",
bin: bin,
args: args,
},
}
return ts, nil
}
type TestProxy struct {
t *testing.T
Process
listenAddress string
port string
db *sql.DB
rdb *sql.DB
}
func NewTestProxy(t *testing.T, dir string, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestProxy, error) {
u := uuid.Must(uuid.NewV4())
uid := fmt.Sprintf("%x", u[:4])
listenAddress, port, err := getFreePort(true, false)
if err != nil {
return nil, err
}
args := []string{}
args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
args = append(args, fmt.Sprintf("--listen-address=%s", listenAddress))
args = append(args, fmt.Sprintf("--port=%s", port))
args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
if os.Getenv("DEBUG") != "" {
args = append(args, "--debug")
}
args = append(args, a...)
connParams := pg.ConnParams{
"user": pgSUUsername,
"password": pgSUPassword,
"host": listenAddress,
"port": port,
"dbname": "postgres",
"sslmode": "disable",
}
replConnParams := pg.ConnParams{
"user": pgReplUsername,
"password": pgReplPassword,
"host": listenAddress,
"port": port,
"dbname": "postgres",
"sslmode": "disable",
"replication": "1",
}
connString := connParams.ConnString()
db, err := sql.Open("postgres", connString)
if err != nil {
return nil, err
}
replConnString := replConnParams.ConnString()
rdb, err := sql.Open("postgres", replConnString)
if err != nil {
return nil, err
}
bin := os.Getenv("STPROXY_BIN")
if bin == "" {
return nil, fmt.Errorf("missing STPROXY_BIN env")
}
tp := &TestProxy{
t: t,
Process: Process{
t: t,
uid: uid,
name: "proxy",
bin: bin,
args: args,
},
listenAddress: listenAddress,
port: port,
db: db,
rdb: rdb,
}
return tp, nil
}
func (tp *TestProxy) WaitListening(timeout time.Duration) error {
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
_, err := net.DialTimeout("tcp", net.JoinHostPort(tp.listenAddress, tp.port), timeout-time.Since(start))
if err == nil {
return nil
}
time.Sleep(sleepInterval)
}
return fmt.Errorf("timeout")
}
func (tp *TestProxy) CheckListening() bool {
_, err := net.Dial("tcp", net.JoinHostPort(tp.listenAddress, tp.port))
return err == nil
}
func (tp *TestProxy) WaitNotListening(timeout time.Duration) error {
start := time.Now()
for time.Now().Add(-timeout).Before(start) {
_, err := net.DialTimeout("tcp", net.JoinHostPort(tp.listenAddress, tp.port), timeout-time.Since(start))
if err != nil {
return nil
}
time.Sleep(sleepInterval)
}
return fmt.Errorf("timeout")
}
func (tp *TestProxy) Exec(query string, args ...interface{}) (sql.Result, error) {
res, err := tp.db.Exec(query, args...)
if err != nil {
return nil, err
}
return res, nil
}
func (tp *TestProxy) Query(query string, args ...interface{}) (*sql.Rows, error) {
res, err := tp.db.Query(query, args...)
if err != nil {
return nil, err
}
return res, nil
}
func (tp *TestProxy) ReplQuery(query string, args ...interface{}) (*sql.Rows, error) {
res, err := tp.rdb.Query(query, args...)
if err != nil {
return nil, err
}
return res, nil
}
func (tp *TestProxy) GetPGParameters() (common.Parameters, error) {
return GetPGParameters(tp)
}
func (tp *TestProxy) WaitRightMaster(tk *TestKeeper, timeout time.Duration) error {
return tk.WaitPGParameter("port", tk.pgPort, timeout)
}
func StolonCtl(t *testing.T, clusterName string, storeBackend store.Backend, storeEndpoints string, a ...string) error {
args := []string{}
args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
args = append(args, a...)
t.Logf("executing stolonctl, args: %s", args)
bin := os.Getenv("STCTL_BIN")
if bin == "" {
return fmt.Errorf("missing STCTL_BIN env")
}
cmd := exec.Command(bin, args...)
pr, pw, err := os.Pipe()
if err != nil {
return err
}
cmd.Stdout = pw
cmd.Stderr = pw
go func() {
scanner := bufio.NewScanner(pr)
for scanner.Scan() {
t.Logf("[%s]: %s", "stolonctl", scanner.Text())
}
}()
return cmd.Run()
}
type TestStore struct {
t *testing.T
Process
listenAddress string
port string
store store.KVStore
storeBackend store.Backend
}
func NewTestStore(t *testing.T, dir string, a ...string) (*TestStore, error) {
storeBackend := store.Backend(os.Getenv("STOLON_TEST_STORE_BACKEND"))
switch storeBackend {
case "consul":
return NewTestConsul(t, dir, a...)
case "etcd":
storeBackend = "etcdv2"
fallthrough
case "etcdv2", "etcdv3":
return NewTestEtcd(t, dir, storeBackend, a...)
}
return nil, fmt.Errorf("wrong store backend")
}
func NewTestEtcd(t *testing.T, dir string, backend store.Backend, a ...string) (*TestStore, error) {
u := uuid.Must(uuid.NewV4())
uid := fmt.Sprintf("%x", u[:4])
dataDir := filepath.Join(dir, fmt.Sprintf("etcd%s", uid))
listenAddress, port, err := getFreePort(true, false)
if err != nil {
return nil, err
}
listenAddress2, port2, err := getFreePort(true, false)
if err != nil {
return nil, err
}
args := []string{}
args = append(args, fmt.Sprintf("--name=%s", uid))
args = append(args, fmt.Sprintf("--data-dir=%s", dataDir))
args = append(args, fmt.Sprintf("--listen-client-urls=http://%s:%s", listenAddress, port))
args = append(args, fmt.Sprintf("--advertise-client-urls=http://%s:%s", listenAddress, port))
args = append(args, fmt.Sprintf("--listen-peer-urls=http://%s:%s", listenAddress2, port2))
args = append(args, fmt.Sprintf("--initial-advertise-peer-urls=http://%s:%s", listenAddress2, port2))
args = append(args, fmt.Sprintf("--initial-cluster=%s=http://%s:%s", uid, listenAddress2, port2))
args = append(args, a...)
storeEndpoints := fmt.Sprintf("%s:%s", listenAddress, port)
storeConfig := store.Config{
Backend: store.Backend(backend),
Endpoints: storeEndpoints,
Timeout: defaultStoreTimeout,
}
kvstore, err := store.NewKVStore(storeConfig)
if err != nil {
return nil, fmt.Errorf("cannot create store: %v", err)
}
bin := os.Getenv("ETCD_BIN")
if bin == "" {
return nil, fmt.Errorf("missing ETCD_BIN env")
}
tstore := &TestStore{
t: t,
Process: Process{
t: t,
uid: uid,
name: "etcd",
bin: bin,
args: args,
},
listenAddress: listenAddress,
port: port,
store: kvstore,
storeBackend: backend,
}
return tstore, nil
}
func NewTestConsul(t *testing.T, dir string, a ...string) (*TestStore, error) {
u := uuid.Must(uuid.NewV4())
uid := fmt.Sprintf("%x", u[:4])