-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathlocal_cluster.go
More file actions
1553 lines (1363 loc) · 42.7 KB
/
local_cluster.go
File metadata and controls
1553 lines (1363 loc) · 42.7 KB
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
/*
* SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
package dgraphtest
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
stderrors "errors"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
cerrdefs "github.com/containerd/errdefs"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/volume"
docker "github.com/docker/docker/client"
"github.com/golang-jwt/jwt/v5"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/dgraph-io/dgo/v250"
"github.com/dgraph-io/dgo/v250/protos/api"
"github.com/dgraph-io/dgraph/v25/dgraphapi"
"github.com/dgraph-io/dgraph/v25/x"
)
// cluster's network struct
type cnet struct {
id string
name string
}
// LocalCluster is a local dgraph cluster
type LocalCluster struct {
conf ClusterConfig
tempBinDir string
tempSecretsDir string
encKeyPath string
lowerThanV21 bool
customTokenizers string
// resources
dcli *docker.Client
net cnet
netMutex sync.Mutex // protects network recreation
zeros []*zero
alphas []*alpha
}
// UpgradeStrategy is an Enum that defines various upgrade strategies
type UpgradeStrategy int
const (
BackupRestore UpgradeStrategy = iota
ExportImport
InPlace
)
func (u UpgradeStrategy) String() string {
switch u {
case BackupRestore:
return "backup-restore"
case InPlace:
return "in-place"
case ExportImport:
return "export-import"
default:
panic("unknown upgrade strategy")
}
}
// NewLocalCluster creates a new local dgraph cluster with given configuration
func NewLocalCluster(conf ClusterConfig) (*LocalCluster, error) {
c := &LocalCluster{conf: conf}
if err := c.init(); err != nil {
c.Cleanup(true)
return nil, err
}
return c, nil
}
// init performs the one time setup and sets up the cluster.
func (c *LocalCluster) init() error {
var err error
c.dcli, err = docker.NewClientWithOpts(docker.FromEnv, docker.WithAPIVersionNegotiation())
if err != nil {
return errors.Wrap(err, "error setting up docker client")
}
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
if _, err := c.dcli.Ping(ctx); err != nil {
return errors.Wrap(err, "unable to talk to docker daemon")
}
if err := c.createNetwork(); err != nil {
return err
}
c.tempBinDir, err = os.MkdirTemp("", c.conf.prefix)
if err != nil {
return errors.Wrap(err, "error while creating tempBinDir")
}
log.Printf("[INFO] tempBinDir: %v", c.tempBinDir)
c.tempSecretsDir, err = os.MkdirTemp("", c.conf.prefix)
if err != nil {
return errors.Wrap(err, "error while creating tempSecretsDir")
}
log.Printf("[INFO] tempSecretsDir: %v", c.tempSecretsDir)
if err := os.Mkdir(binariesPath, os.ModePerm); err != nil && !os.IsExist(err) {
return errors.Wrap(err, "error while making binariesPath")
}
if err := os.Mkdir(datasetFilesPath, os.ModePerm); err != nil && !os.IsExist(err) {
return errors.Wrap(err, "error while making datafiles path")
}
for _, vol := range c.conf.volumes {
if err := c.createVolume(vol); err != nil {
return err
}
}
c.zeros = c.zeros[:0]
for i := range c.conf.numZeros {
zo := &zero{id: i}
zo.containerName = fmt.Sprintf(zeroNameFmt, c.conf.prefix, zo.id)
zo.aliasName = fmt.Sprintf(zeroAliasNameFmt, zo.id)
c.zeros = append(c.zeros, zo)
}
c.alphas = c.alphas[:0]
for i := range c.conf.numAlphas {
aa := &alpha{id: i}
aa.containerName = fmt.Sprintf(alphaNameFmt, c.conf.prefix, aa.id)
aa.aliasName = fmt.Sprintf(alphaLNameFmt, aa.id)
c.alphas = append(c.alphas, aa)
}
if err := c.setupSecrets(); err != nil {
return errors.Wrap(err, "error setting up secrets")
}
if err := c.setupBeforeCluster(); err != nil {
return err
}
if err := c.createContainers(); err != nil {
return err
}
return nil
}
func (c *LocalCluster) createNetwork() error {
c.net.name = c.conf.prefix + "-net"
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
// Check if network already exists
existingNet, err := c.dcli.NetworkInspect(ctx, c.net.name, network.InspectOptions{})
if err == nil {
// Network exists, reuse it
log.Printf("[INFO] reusing existing network %s (ID: %s)", c.net.name, existingNet.ID)
c.net.id = existingNet.ID
return nil
}
// Network doesn't exist, create it
opts := network.CreateOptions{
Driver: "bridge",
IPAM: &network.IPAM{Driver: "default"},
}
networkResp, err := c.dcli.NetworkCreate(ctx, c.net.name, opts)
if err != nil {
// If network already exists (race condition), try to inspect and reuse it
if strings.Contains(err.Error(), "already exists") {
log.Printf("[INFO] network %s already exists (race condition), inspecting", c.net.name)
existingNet, inspectErr := c.dcli.NetworkInspect(ctx, c.net.name, network.InspectOptions{})
if inspectErr == nil {
log.Printf("[INFO] reusing existing network %s (ID: %s)", c.net.name, existingNet.ID)
c.net.id = existingNet.ID
return nil
}
// If inspect also fails, return original create error
log.Printf("[WARNING] failed to inspect network after creation conflict: %v", inspectErr)
}
return errors.Wrap(err, "error creating network")
}
c.net.id = networkResp.ID
return nil
}
func (c *LocalCluster) createVolume(name string) error {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
req := volume.CreateOptions{Driver: "local", Name: name}
if _, err := c.dcli.VolumeCreate(ctx, req); err != nil {
return errors.Wrapf(err, "error creating volume [%v]", name)
}
return nil
}
func (c *LocalCluster) setupBeforeCluster() error {
if err := c.setupBinary(); err != nil {
return errors.Wrapf(err, "error setting up binary")
}
higher, err := IsHigherVersion(c.GetVersion(), "v21.03.0")
if err != nil {
return errors.Wrapf(err, "error checking if version %s is older than v21.03.0", c.GetVersion())
}
c.lowerThanV21 = !higher
return nil
}
func (c *LocalCluster) createContainers() error {
var wg sync.WaitGroup
errChan := make(chan error, len(c.zeros)+len(c.alphas))
for _, zo := range c.zeros {
wg.Add(1)
go func(z *zero) {
defer wg.Done()
cid, err := c.createContainer(z)
if err != nil {
errChan <- err
return
}
z.containerID = cid
}(zo)
}
for _, aa := range c.alphas {
wg.Add(1)
go func(a *alpha) {
defer wg.Done()
cid, err := c.createContainer(a)
if err != nil {
errChan <- err
return
}
a.containerID = cid
}(aa)
}
wg.Wait()
close(errChan)
for err := range errChan {
return err
}
return nil
}
func (c *LocalCluster) createContainer(dc dnode) (string, error) {
cmd := dc.cmd(c)
image := c.dgraphImage()
mts, err := dc.mounts(c)
if err != nil {
return "", err
}
// Verify the network still exists before creating container
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
if c.net.id != "" {
_, err := c.dcli.NetworkInspect(ctx, c.net.id, network.InspectOptions{})
if err != nil {
// Use mutex to prevent multiple goroutines from recreating network simultaneously
c.netMutex.Lock()
// Double-check after acquiring lock - another goroutine may have recreated it
_, recheckErr := c.dcli.NetworkInspect(ctx, c.net.id, network.InspectOptions{})
if recheckErr != nil {
log.Printf("[WARNING] network %s (ID: %s) not found, recreating", c.net.name, c.net.id)
if err := c.createNetwork(); err != nil {
c.netMutex.Unlock()
return "", errors.Wrap(err, "error recreating network")
}
}
c.netMutex.Unlock()
}
}
cconf := &container.Config{Cmd: cmd, Image: image, WorkingDir: dc.workingDir(), ExposedPorts: dc.ports()}
hconf := &container.HostConfig{Mounts: mts, PublishAllPorts: true, PortBindings: dc.bindings(c.conf.portOffset)}
networkConfig := &network.NetworkingConfig{
EndpointsConfig: map[string]*network.EndpointSettings{
c.net.name: {
Aliases: []string{dc.cname(), dc.aname()},
NetworkID: c.net.id,
},
},
}
resp, err := c.dcli.ContainerCreate(ctx, cconf, hconf, networkConfig, nil, dc.cname())
if err != nil {
return "", errors.Wrapf(err, "error creating container %v", dc.cname())
}
return resp.ID, nil
}
func (c *LocalCluster) destroyContainers() error {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
var wg sync.WaitGroup
errChan := make(chan error, len(c.zeros)+len(c.alphas))
ro := container.RemoveOptions{RemoveVolumes: true, Force: true}
for _, zo := range c.zeros {
wg.Add(1)
go func(z *zero) {
defer wg.Done()
if err := c.dcli.ContainerRemove(ctx, z.cid(), ro); err != nil && !cerrdefs.IsNotFound(err) {
errChan <- errors.Wrapf(err, "error removing zero [%v]", z.cname())
}
}(zo)
}
for _, aa := range c.alphas {
wg.Add(1)
go func(a *alpha) {
defer wg.Done()
if err := c.dcli.ContainerRemove(ctx, a.cid(), ro); err != nil && !cerrdefs.IsNotFound(err) {
errChan <- errors.Wrapf(err, "error removing alpha [%v]", a.cname())
}
}(aa)
}
wg.Wait()
close(errChan)
for err := range errChan {
return err
}
return nil
}
func (c *LocalCluster) printPortMappings() error {
containers, err := c.dcli.ContainerList(context.Background(), container.ListOptions{})
if err != nil {
return errors.Wrap(err, "error listing docker containers")
}
var result bytes.Buffer
for _, container := range containers {
result.WriteString(fmt.Sprintf("ID: %s, Image: %s, Command: %s, Status: %s\n",
container.ID[:10], container.Image, container.Command, container.Status))
result.WriteString("Port Mappings:\n")
info, err := c.dcli.ContainerInspect(context.Background(), container.ID)
if err != nil {
return errors.Wrapf(err, "error inspecting container [%v]", container.ID)
}
for port, bindings := range info.NetworkSettings.Ports {
if len(bindings) == 0 {
continue
}
result.WriteString(fmt.Sprintf(" %s:%s\n", port.Port(), bindings))
}
result.WriteString("\n")
}
log.Printf("[INFO] ======== CONTAINERS' PORT MAPPINGS ========")
log.Println(result.String())
return nil
}
func (c *LocalCluster) Cleanup(verbose bool) {
if c == nil {
return
}
if verbose {
if err := c.printAllLogs(); err != nil {
log.Printf("[WARNING] error printing container logs: %v", err)
}
if err := c.printInspectContainers(); err != nil {
log.Printf("[WARNING] error printing inspect container output: %v", err)
}
if err := c.printPortMappings(); err != nil {
log.Printf("[WARNING] error printing port mappings: %v", err)
}
}
log.Printf("[INFO] cleaning up cluster with prefix [%v]", c.conf.prefix)
if err := c.destroyContainers(); err != nil {
log.Printf("[WARNING] error removing container: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
for _, vol := range c.conf.volumes {
if err := c.dcli.VolumeRemove(ctx, vol, true); err != nil {
log.Printf("[WARNING] error removing volume [%v]: %v", vol, err)
}
}
if c.net.id != "" {
if err := c.dcli.NetworkRemove(ctx, c.net.id); err != nil {
log.Printf("[WARNING] error removing network [%v]: %v", c.net.name, err)
}
}
if err := os.RemoveAll(c.tempBinDir); err != nil {
log.Printf("[WARNING] error while removing temp bin dir: %v", err)
}
if err := os.RemoveAll(c.tempSecretsDir); err != nil {
log.Printf("[WARNING] error while removing temp secrets dir: %v", err)
}
}
func (c *LocalCluster) cleanupDocker() error {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
// Prune containers
contsReport, err := c.dcli.ContainersPrune(ctx, filters.Args{})
if err != nil {
// Don't fail if prune is already running - just skip it
if strings.Contains(err.Error(), "already running") {
log.Printf("[WARNING] Skipping container prune - operation already running")
} else {
log.Printf("[WARNING] Error pruning containers: %v", err)
}
} else {
log.Printf("[INFO] Pruned containers: %+v\n", contsReport)
}
// Prune networks
netsReport, err := c.dcli.NetworksPrune(ctx, filters.Args{})
if err != nil {
// Don't fail if prune is already running - just skip it
if strings.Contains(err.Error(), "already running") {
log.Printf("[WARNING] Skipping network prune - operation already running")
} else {
log.Printf("[WARNING] Error pruning networks: %v", err)
}
} else {
log.Printf("[INFO] Pruned networks: %+v\n", netsReport)
}
return nil
}
func (c *LocalCluster) Start() error {
log.Printf("[INFO] starting cluster with prefix [%v]", c.conf.prefix)
startAll := func() error {
var wg sync.WaitGroup
errCh := make(chan error, c.conf.numZeros+c.conf.numAlphas)
for i := range c.conf.numZeros {
wg.Add(1)
go func(id int) {
defer wg.Done()
if err := c.StartZero(id); err != nil {
errCh <- fmt.Errorf("failed to start zero %d: %w", id, err)
}
}(i)
}
for i := range c.conf.numAlphas {
wg.Add(1)
go func(id int) {
defer wg.Done()
if err := c.StartAlpha(id); err != nil {
errCh <- fmt.Errorf("failed to start alpha %d: %w", id, err)
}
}(i)
}
wg.Wait()
close(errCh)
for err := range errCh {
if err != nil {
return err
}
}
return c.HealthCheck(false)
}
// sometimes health check doesn't work due to unmapped ports. We dont
// know why this happens, but checking it 3 times before failing the test.
retry := 0
for {
retry++
if err := startAll(); err == nil {
return nil
} else if retry == 3 {
return err
} else {
log.Printf("[WARNING] saw the err, trying again: %v", err)
}
if err1 := c.Stop(); err1 != nil {
log.Printf("[WARNING] error while stopping :%v", err1)
}
c.Cleanup(true)
if err := c.cleanupDocker(); err != nil {
log.Printf("[ERROR] while cleaning old dockers %v", err)
}
c.conf.prefix = fmt.Sprintf("dgraphtest-%d", rand.NewSource(time.Now().UnixNano()).Int63()%1000000)
if err := c.init(); err != nil {
log.Printf("[ERROR] error while init, returning: %v", err)
return err
}
}
}
func (c *LocalCluster) StartZero(id int) error {
if id >= c.conf.numZeros {
return fmt.Errorf("invalid id of zero: %v", id)
}
return c.startContainer(c.zeros[id])
}
func (c *LocalCluster) StartAlpha(id int) error {
if id >= c.conf.numAlphas {
return fmt.Errorf("invalid id of alpha: %v", id)
}
return c.startContainer(c.alphas[id])
}
func (c *LocalCluster) startContainer(dc dnode) error {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
// verify the container still exists
_, err := c.dcli.ContainerInspect(ctx, dc.cid())
if err != nil {
log.Printf("[WARNING] container %s (ID: %s) not found, attempting to recreate", dc.cname(), dc.cid())
newCID, createErr := c.createContainer(dc)
if createErr != nil {
return errors.Wrapf(createErr, "error recreating missing container [%v]", dc.cname())
}
switch node := dc.(type) {
case *alpha, *zero:
node.setContainerID(newCID)
}
log.Printf("[INFO] successfully recreated container %s with new ID: %s", dc.cname(), newCID)
}
if err := c.dcli.ContainerStart(ctx, dc.cid(), container.StartOptions{}); err != nil {
return errors.Wrapf(err, "error starting container [%v]", dc.cname())
}
dc.changeStatus(true)
return nil
}
func (c *LocalCluster) Stop() error {
log.Printf("[INFO] stopping cluster with prefix [%v]", c.conf.prefix)
for i := range c.alphas {
if err := c.StopAlpha(i); err != nil {
return err
}
}
for i := range c.zeros {
if err := c.StopZero(i); err != nil {
return err
}
}
return nil
}
func (c *LocalCluster) StopZero(id int) error {
if id >= c.conf.numZeros {
return fmt.Errorf("invalid id of zero: %v", id)
}
return c.stopContainer(c.zeros[id])
}
// GetZeroContainerName returns the Docker container name for the specified Zero,
// which also serves as a DNS alias on the cluster network.
func (c *LocalCluster) GetZeroContainerName(id int) (string, error) {
if id >= c.conf.numZeros {
return "", fmt.Errorf("invalid id of zero: %v", id)
}
return c.zeros[id].containerName, nil
}
// SetZeroMyAddr overrides the --my flag for the specified Zero node. The next
// time the container is recreated (via RecreateZero), this address will be
// used instead of the default container alias.
func (c *LocalCluster) SetZeroMyAddr(id int, addr string) error {
if id >= c.conf.numZeros {
return fmt.Errorf("invalid id of zero: %v", id)
}
c.zeros[id].myAddrOverride = addr
return nil
}
// RecreateZero destroys the Zero container and creates a new one with the
// current command-line flags (e.g. a different --my address). The Zero's data
// directory is preserved across the recreation by extracting it from the old
// (stopped) container and injecting it into the new one. This simulates a
// process restart with persistent storage — the exact scenario where stale WAL
// addresses surface.
func (c *LocalCluster) RecreateZero(id int) error {
if id >= c.conf.numZeros {
return fmt.Errorf("invalid id of zero: %v", id)
}
z := c.zeros[id]
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
// Extract the data directory from the stopped container so the WAL survives.
dataReader, _, err := c.dcli.CopyFromContainer(ctx, z.cid(), zeroWorkingDir)
if err != nil {
return errors.Wrapf(err, "error copying data from zero container [%v]", z.cname())
}
defer dataReader.Close()
// Read the tar into memory (Zero WAL is small).
dataTar, err := io.ReadAll(dataReader)
if err != nil {
return errors.Wrap(err, "error reading zero data tar")
}
ro := container.RemoveOptions{RemoveVolumes: true, Force: true}
if err := c.dcli.ContainerRemove(ctx, z.cid(), ro); err != nil && !cerrdefs.IsNotFound(err) {
return errors.Wrapf(err, "error removing zero container [%v]", z.cname())
}
cid, err := c.createContainer(z)
if err != nil {
return errors.Wrapf(err, "error recreating zero container [%v]", z.cname())
}
z.containerID = cid
// Inject the data directory into the new container. CopyToContainer expects
// a tar archive rooted at the parent of the target path.
if err := c.dcli.CopyToContainer(ctx, cid, "/data", bytes.NewReader(dataTar),
container.CopyToContainerOptions{}); err != nil {
return errors.Wrapf(err, "error restoring data to zero container [%v]", z.cname())
}
return nil
}
func (c *LocalCluster) StopAlpha(id int) error {
if id >= c.conf.numAlphas {
return fmt.Errorf("invalid id of alpha: %v", id)
}
return c.stopContainer(c.alphas[id])
}
func (c *LocalCluster) stopContainer(dc dnode) error {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
stopTimeout := 30 // in seconds
o := container.StopOptions{Timeout: &stopTimeout}
if err := c.dcli.ContainerStop(ctx, dc.cid(), o); err != nil {
// Force kill the container if timeout exceeded
if strings.Contains(err.Error(), "context deadline exceeded") {
_ = c.dcli.ContainerKill(ctx, dc.cid(), "KILL")
return nil
}
return errors.Wrapf(err, "error stopping container [%v]", dc.cname())
}
dc.changeStatus(false)
return nil
}
func (c *LocalCluster) KillAlpha(id int) error {
if id >= c.conf.numAlphas {
return fmt.Errorf("invalid id of alpha: %v", id)
}
return c.killContainer(c.alphas[id])
}
func (c *LocalCluster) killContainer(dc dnode) error {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
if err := c.dcli.ContainerKill(ctx, dc.cid(), "SIGKILL"); err != nil {
return errors.Wrapf(err, "error killing container [%v]", dc.cname())
}
return nil
}
func (c *LocalCluster) HealthCheck(zeroOnly bool) error {
log.Printf("[INFO] checking health of containers")
var wg sync.WaitGroup
errChan := make(chan error, len(c.zeros)+len(c.alphas))
for _, zo := range c.zeros {
if !zo.isRunning {
break
}
wg.Add(1)
go func(z *zero) {
defer wg.Done()
if err := c.containerHealthCheck(z.healthURL); err != nil {
errChan <- err
return
}
log.Printf("[INFO] container [%v] passed health check", z.containerName)
if err := c.checkDgraphVersion(z.containerName); err != nil {
errChan <- err
}
}(zo)
}
if !zeroOnly {
for _, aa := range c.alphas {
if !aa.isRunning {
break
}
wg.Add(1)
go func(a *alpha) {
defer wg.Done()
if err := c.containerHealthCheck(a.healthURL); err != nil {
errChan <- err
return
}
log.Printf("[INFO] container [%v] passed health check", a.containerName)
if err := c.checkDgraphVersion(a.containerName); err != nil {
errChan <- err
}
}(aa)
}
}
wg.Wait()
close(errChan)
for err := range errChan {
return err
}
return nil
}
func (c *LocalCluster) containerHealthCheck(url func(c *LocalCluster) (string, error)) error {
endpoint, err := url(c)
if err != nil {
return errors.Wrapf(err, "error getting health URL %v", endpoint)
}
for attempt := range 120 {
time.Sleep(waitDurBeforeRetry)
endpoint, err = url(c)
if err != nil {
return errors.Wrap(err, "error getting health URL")
}
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
if attempt > 50 {
log.Printf("[WARNING] problem building req for endpoint [%v], err: [%v]", endpoint, err)
}
continue
}
body, err := dgraphapi.DoReq(req)
if err != nil {
if attempt > 50 {
log.Printf("[WARNING] problem hitting health endpoint [%v], err: [%v]", endpoint, err)
}
continue
}
resp := string(body)
// zero returns OK in the health check
if resp == "OK" {
return nil
}
// For Alpha, we always run alpha with EE features enabled
if !strings.Contains(resp, `"ee_features"`) {
continue
}
if c.conf.acl && !strings.Contains(resp, `"acl"`) {
continue
}
if err := c.waitUntilLogin(); err != nil {
return err
}
if err := c.waitUntilGraphqlHealthCheck(); err != nil {
return err
}
return nil
}
return fmt.Errorf("health failed, cluster took too long to come up [%v]", endpoint)
}
func (c *LocalCluster) waitUntilLogin() error {
if !c.conf.acl {
return nil
}
client, cleanup, err := c.Client()
if err != nil {
return errors.Wrap(err, "error setting up a client")
}
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
for attempt := range 10 {
err = client.Login(ctx, dgraphapi.DefaultUser, dgraphapi.DefaultPassword)
if err == nil {
log.Printf("[INFO] login succeeded")
return nil
}
if attempt > 5 {
log.Printf("[WARNING] problem trying to login: %v", err)
}
time.Sleep(waitDurBeforeRetry)
}
return errors.Wrap(err, "error during login")
}
func (c *LocalCluster) waitUntilGraphqlHealthCheck() error {
hc, err := c.HTTPClient()
if err != nil {
return errors.Wrap(err, "error creating http client while graphql health check")
}
if c.conf.acl {
for range 5 {
if err = hc.LoginIntoNamespace(dgraphapi.DefaultUser, dgraphapi.DefaultPassword, x.RootNamespace); err == nil {
break
}
time.Sleep(1 * time.Second)
}
if err != nil {
return errors.Wrap(err, "error during login while graphql health check")
}
}
for range 10 {
// Sleep for a second before retrying
time.Sleep(waitDurBeforeRetry)
// we do this because before v21, we used to propose the initial schema to the cluster.
// This results in schema being applied and indexes being built which could delay alpha
// starting to serve graphql schema.
err = hc.DeleteUser("nonexistent")
if err == nil {
log.Printf("[INFO] graphql health check succeeded for %v", c.conf.prefix)
return nil
}
}
return errors.Wrap(err, "error during graphql health check")
}
// Upgrades the cluster to the provided dgraph version
func (c *LocalCluster) Upgrade(version string, strategy UpgradeStrategy) error {
if version == c.conf.version {
return fmt.Errorf("cannot upgrade to the same version")
}
log.Printf("[INFO] upgrading the cluster from [%v] to [%v] using [%v]", c.conf.version, version, strategy)
switch strategy {
case BackupRestore:
hc, err := c.HTTPClient()
if err != nil {
return err
}
if c.conf.acl {
if err := hc.LoginIntoNamespace(dgraphapi.DefaultUser, dgraphapi.DefaultPassword, x.RootNamespace); err != nil {
return errors.Wrapf(err, "error during login before upgrade")
}
}
if err := hc.Backup(c, true, DefaultBackupDir); err != nil {
return errors.Wrap(err, "error taking backup during upgrade")
}
if err := c.Stop(); err != nil {
return err
}
c.conf.version = version
if err := c.recreateContainers(); err != nil {
return err
}
if err := c.Start(); err != nil {
return err
}
hc, err = c.HTTPClient()
if err != nil {
return errors.Wrapf(err, "error creating HTTP client after upgrade")
}
if c.conf.acl {
if err := hc.LoginIntoNamespace(dgraphapi.DefaultUser, dgraphapi.DefaultPassword, x.RootNamespace); err != nil {
return errors.Wrapf(err, "error during login after upgrade")
}
}
if err := hc.Restore(c, DefaultBackupDir, "", 0, 1); err != nil {
return errors.Wrap(err, "error doing restore during upgrade")
}
if err := dgraphapi.WaitForRestore(c); err != nil {
return errors.Wrap(err, "error waiting for restore to complete")
}
return nil
case ExportImport:
hc, err := c.HTTPClient()
if err != nil {
return err
}
if c.conf.acl {
if err := hc.LoginIntoNamespace(dgraphapi.DefaultUser, dgraphapi.DefaultPassword, x.RootNamespace); err != nil {
return errors.Wrapf(err, "error during login before upgrade")
}
}
// using -1 as namespace exports all the namespaces
if err := hc.Export(DefaultExportDir, "rdf", -1); err != nil {
return errors.Wrap(err, "error taking export during upgrade")
}
if err := c.Stop(); err != nil {
return err
}
c.conf.version = version
if err := c.recreateContainers(); err != nil {
return err
}
if err := c.Start(); err != nil {
return err
}
if err := c.LiveLoadFromExport(DefaultExportDir); err != nil {
return errors.Wrap(err, "error doing import using live loader")
}
return nil
case InPlace:
if err := c.Stop(); err != nil {
return err
}
c.conf.version = version
if err := c.setupBeforeCluster(); err != nil {
return err
}
return c.Start()
default:
return errors.New("unknown upgrade strategy")
}
}
func (c *LocalCluster) recreateContainers() error {
if err := c.destroyContainers(); err != nil {
return errors.Wrapf(err, "error while recreaing containers")
}
if err := c.setupBeforeCluster(); err != nil {
return errors.Wrap(err, "error while setupBeforeCluster")
}
if err := c.createContainers(); err != nil {
return errors.Wrapf(err, "error while creating containers")
}
return nil
}
// Client returns a grpc client that can talk to any Alpha in the cluster
func (c *LocalCluster) Client() (*dgraphapi.GrpcClient, func(), error) {
// TODO(aman): can we cache the connections?
retryPolicy := `{
"methodConfig": [{
"retryPolicy": {
"MaxAttempts": 4,
"InitialBackoff": ".01s",
"MaxBackoff": ".01s",
"BackoffMultiplier": 1.0,
"RetryableStatusCodes": [ "UNAVAILABLE" ]
}
}]
}`