Repository navigation
Expand file tree
/
Copy pathtesttools.go
More file actions
2533 lines (2225 loc) · 69.4 KB
/
Copy pathtesttools.go
File metadata and controls
2533 lines (2225 loc) · 69.4 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
package citools
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"testing"
"time"
"github.com/gorilla/rpc/v2/json2"
)
var DEBUG_ENV = map[string]string{"DEBUG_MODE": "1"}
// props to https://github.com/kubernetes/kubernetes/issues/49387
var KUBE_DEBUG_CMD = `(
echo 'SEARCHABLE HEADER: KUBE DEBUG'
echo ' _ ___ _ ____ _____ ____ _____ ____ _ _ ____ '
echo '| |/ / | | | __ )| ____| | _ \| ____| __ )| | | |/ ___|'
echo "| ' /| | | | _ \| _| | | | | _| | _ \| | | | | _ "
echo '| . \| |_| | |_) | |___ | |_| | |___| |_) | |_| | |_| |'
echo '|_|\_\\___/|____/|_____| |____/|_____|____/ \___/ \____|'
echo ' '
for INTERESTING_POD in $(kubectl get pods --all-namespaces --no-headers \
|grep -v Running | tr -s ' ' |cut -d ' ' -f 1,2,4 |tr ' ' '/'); do
NS=$(echo $INTERESTING_POD |cut -d "/" -f 1)
NAME=$(echo $INTERESTING_POD |cut -d "/" -f 2)
PHASE=$(echo $INTERESTING_POD |cut -d "/" -f 3)
echo "--> status of $INTERESTING_POD"
kubectl describe pod $NAME -n $NS
if [ "$PHASE" != "ContainerCreating" ]; then
for CONTAINER in $(kubectl get pods $NAME -n $NS -o \
jsonpath={.spec.containers[*].name}); do
echo "--> logs of $INTERESTING_POD/$CONTAINER"
kubectl logs --tail 10 $NAME -n $NS $CONTAINER
done
fi
if [ "$PHASE" == "ImagePullBackOff" ]; then
echo "QUITTING, image could not be found for pod ${INTERESTING_POD}"
echo "IMAGEPULLBACKOFF Describe output -->"
kubectl describe $INTERESTING_POD -n $NS
exit 1
fi
if [ "$PHASE" == "CrashLoopBackOff" ]; then
echo "WARNING crashLoopBackOff, will try again then exit."
kubectl describe $INTERESTING_POD -n $NS
fi
if [ "$PHASE" == "Evicted" ]; then
echo "WARNING evicted, will try again then exit."
kubectl describe $INTERESTING_POD -n $NS
fi
if [ "$PHASE" == "CreateContainerConfigError" ]; then
echo "QUITTING, Create Container config error for pod ${INTERESTING_POD}"
echo "CREATECONTAINERCONFIGERROR Describe output -->"
kubectl describe $INTERESTING_POD -n $NS
exit 1
fi
done
kubectl get pods --all-namespaces
echo ' ___ ___ _ ____ _____ ____ _____ ____ _ _ ____ '
echo ' / / |/ / | | | __ )| ____| | _ \| ____| __ )| | | |/ ___|'
echo " / /| ' /| | | | _ \| _| | | | | _| | _ \| | | | | _ "
echo ' / / | . \| |_| | |_) | |___ | |_| | |___| |_) | |_| | |_| |'
echo '/_/ |_|\_\\___/|____/|_____| |____/|_____|____/ \___/ \____|'
echo ' '
exit 0)` // never let the debug command failing cause us to fail the tests!
// return a list of names of pods which are crashing. If there are some, exit 1.
var checkCrashLoopCmd = `(
kubectl get pod --all-namespaces -o json | jq '.items[] | if .status.phase == "CrashLoopBackOff" then .metadata.name else empty end'
if [ ! -z $result ]; then
echo $result
exit 1
fi
exit 0)`
var timings map[string]float64
var lastTiming int64
// An arbitrary point in time that all test runs after this commit
// should be after, so we can use it as an epoch for our timestamps
// and therefore make them much shorter strings... Update this every
// decade or so to keep them short.
const DAWN_OF_DOTMESH_TIME = 1533034862684223659
var stamp int64
// DOTMESH_TEST_CLEANUP_ENV - cleanup policy for the tests
var DOTMESH_TEST_CLEANUP_ENV = "DOTMESH_TEST_CLEANUP"
type cleanupStrategy int
const (
cleanupStrategyNone cleanupStrategy = iota
cleanupStrategyAlways
cleanupStrategyNever
cleanupStrategyOnSuccess
cleanupStrategyLater
)
var defaultCleanupStrategy = cleanupStrategyOnSuccess
func getCleanupStrategy() cleanupStrategy {
c := strings.ToLower(os.Getenv(DOTMESH_TEST_CLEANUP_ENV))
switch c {
case "always":
return cleanupStrategyAlways
case "never":
return cleanupStrategyNever
case "onsuccess":
return cleanupStrategyOnSuccess
case "later":
return cleanupStrategyLater
}
return defaultCleanupStrategy
}
var getFieldsByNewLine = func(c rune) bool {
return c == '\n'
}
func Contains(arr []string, str string) bool {
for _, a := range arr {
if strings.Contains(a, str) {
return true
}
}
return false
}
func AddFuncToCleanups(f func()) {
globalCleanupFuncs = append(globalCleanupFuncs, f)
}
var globalCleanupFuncs []func()
func StartTiming() {
lastTiming = time.Now().UnixNano()
timings = make(map[string]float64)
}
func LogTiming(tag string) {
now := time.Now().UnixNano()
timings[tag] = float64(now-lastTiming) / (1000 * 1000 * 1000)
lastTiming = now
}
func DumpTiming() {
fmt.Printf("=== TIMING ===\n")
for tag, timing := range timings {
fmt.Printf("%s => %.2f\n", tag, timing)
}
fmt.Printf("=== END TIMING ===\n")
timings = map[string]float64{}
}
func System(cmd string, args ...string) error {
log.Printf("[system] running %s %s", cmd, args)
c := exec.Command(cmd, args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return c.Run()
}
func SilentSystem(cmd string, args ...string) error {
log.Printf("[silentSystem] running %s %s", cmd, args)
c := exec.Command(cmd, args...)
return c.Run()
}
func TryUntilSucceeds(f func() error, desc string) error {
attempt := 0
for {
err := f()
if err != nil {
if attempt > 20 {
return err
} else {
fmt.Printf("Error %s: %v, pausing and trying again...\n", desc, err)
time.Sleep(time.Duration(attempt) * time.Second)
}
} else {
return nil
}
attempt++
}
}
func TryForever(f func() error, desc string) error {
attempt := 0
for {
err := f()
if err != nil {
fmt.Printf("Error %s: %v, pausing and trying again...\n", desc, err)
time.Sleep(time.Duration(attempt) * time.Second)
} else {
return nil
}
attempt++
}
}
func TestMarkForCleanup(f Federation) {
log.Printf(`Entering TestMarkForCleanup:
____ _ _____ _ _ _ ___ _ _ ____ _ _ ____
/ ___| | | ____| / \ | \ | |_ _| \ | |/ ___| | | | | _ \
| | | | | _| / _ \ | \| || || \| | | _ | | | | |_) |
| |___| |___| |___ / ___ \| |\ || || |\ | |_| | | |_| | __/
\____|_____|_____/_/ \_\_| \_|___|_| \_|\____| \___/|_|
`)
for _, c := range f {
for _, n := range c.GetNodes() {
node := n.Container
err := TryUntilSucceeds(func() error {
return System("bash", "-c", fmt.Sprintf(
`docker exec -t %s bash -c 'touch /CLEAN_ME_UP'`, node,
))
}, fmt.Sprintf("marking %s for cleanup", node))
if err != nil {
log.Printf("Error marking %s for cleanup: %s, giving up.\n", node, err)
} else {
log.Printf("Marked %s for cleanup.", node)
}
}
}
// Attempt log extraction only after we've safely touched all those CLEAN_ME_UP files, *phew*.
for _, c := range f {
if !c.isBlank() {
for _, n := range c.GetNodes() {
node := n.Container
containers := []string{"dotmesh-server", "dotmesh-server-inner"}
for _, container := range containers {
logDir := "../extracted_logs"
logFile := fmt.Sprintf(
"%s/%s-%s.log",
logDir, container, node,
)
err := SilentSystem(
"bash", "-c",
fmt.Sprintf(
"mkdir -p %s && touch %s && chmod -R a+rwX %s && "+
"docker exec -i %s "+
"docker logs %s > %s",
logDir, logFile, logDir, node, container, logFile,
),
)
if err != nil {
log.Printf("Unable to stream docker logs to artifacts directory for %s: %s", node, err)
}
}
}
}
}
}
func testSetup(t *testing.T, f Federation) error {
err := System("bash", "-c", fmt.Sprintf(`
# Create a home for the test pools to live that can have the same path
# both from ZFS's perspective and that of the inner container.
# (Bind-mounts all the way down.)
mkdir -p %s
# tmpfs makes etcd not completely rinse your IOPS (which it can do
# otherwise); create if doesn't exist
if [ $(mount |grep "/tmpfs " |wc -l) -eq 0 ]; then
mkdir -p /tmpfs && mount -t tmpfs -o size=4g tmpfs /tmpfs
fi
# Attempt to mitigate https://github.com/kinvolk/kube-spawn/issues/14#issuecomment-293207134
echo 131072 > /sys/module/nf_conntrack/parameters/hashsize || true
`, testDirName(stamp)))
if err != nil {
return err
}
cwd, err := os.Getwd()
if err != nil {
return err
}
dindClusterScriptName := fmt.Sprintf("%s/dind-cluster-%d.sh", cwd, os.Getpid())
runScriptDir := os.Getenv("DIND_RUN_FROM_PATH")
if runScriptDir == "" {
runScriptDir = cwd
}
// we write the dind-script.sh file out from go because we need to distribute
// that .sh script as a go package using dep
err = ioutil.WriteFile(dindClusterScriptName, []byte(DIND_SCRIPT), 0755)
if err != nil {
return err
}
// XXX do we actually use this for anything at all???
dindConfig := `
# Apiserver port
APISERVER_PORT=${APISERVER_PORT:-8080}
# Use prebuilt DIND image
DIND_IMAGE="${DIND_IMAGE:-quay.io/dotmesh/kubeadm-dind-cluster:v1.10}"
# Define which DNS service to run
# possible values are kube-dns (default) and coredns
DNS_SERVICE="${DNS_SERVICE:-kube-dns}"
`
err = ioutil.WriteFile(fmt.Sprintf("%s/config.sh", runScriptDir), []byte(dindConfig), 0644)
if err != nil {
return err
}
// dind-script.sh needs config.sh
// don't leave copies of the script around once we have used it
defer func() {
os.Remove(dindClusterScriptName)
}()
for i, c := range f {
clusterIpPrefix := getUniqueIpPrefix()
c.SetIpPrefix(clusterIpPrefix)
for j := 0; j < c.GetDesiredNodeCount(); j++ {
node := nodeName(stamp, i, j)
fmt.Printf(">>> Using RunArgs %s\n", c.RunArgs(i, j))
dockerAuthFile := os.Getenv("MOUNT_DOCKER_AUTH")
mountDockerAuth := ""
if dockerAuthFile != "" {
if _, err := os.Stat(dockerAuthFile); err == nil {
mountDockerAuth = fmt.Sprintf(" -v %s:/root/.dockercfg ", dockerAuthFile)
}
}
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
// XXX the following only works if overlay is working
err = TryUntilSucceeds(
func() error {
return System("bash", "-c", fmt.Sprintf(`
set -xe
MOUNTPOINT=/dotmesh-test-pools
DOTMESH_MOUNTS=/var/lib/dotmesh-mounts
mkdir -p $MOUNTPOINT
mkdir -p $DOTMESH_MOUNTS
NODE=%s
if [ $(mount |grep $MOUNTPOINT |wc -l) -eq 0 ]; then
echo "Creating and bind-mounting shared $MOUNTPOINT"
mount --bind $MOUNTPOINT $MOUNTPOINT && \
mount --make-shared $MOUNTPOINT;
fi
if [ $(mount |grep $DOTMESH_MOUNTS |wc -l) -eq 0 ]; then
echo "Creating and bind-mounting shared $DOTMESH_MOUNTS"
mount --bind $DOTMESH_MOUNTS $DOTMESH_MOUNTS && \
mount --make-shared $DOTMESH_MOUNTS;
fi
(cd %s
EXTRA_DOCKER_ARGS="\
-v /var/lib/dotmesh-mounts:/var/lib/dotmesh-mounts:rshared \
-v /dotmesh-test-pools:/dotmesh-test-pools:rshared \
-v /var/run/docker.sock:/hostdocker.sock %s " \
DIND_SUBNET="10.200.0.0" \
DIND_SUBNET_SIZE="16" \
SERVICE_CIDR="%s" \
POD_NETWORK_CIDR="%s" \
CNI_PLUGIN=bridge %s run $NODE "%s" %d)
sleep 1
echo "About to run docker exec on $NODE"
docker exec -t $NODE bash -c '
set -xe
# from dind::fix-mounts
mount --make-shared /lib/modules/
mount --make-shared /run
echo "%s '$(hostname)'.local" >> /etc/hosts
echo -n "10.%d." > /POD_IP_PREFIX
mkdir -p /etc/docker
echo "{\"insecure-registries\" : [\"%s.local:80\"]}" > /etc/docker/daemon.json
systemctl daemon-reload
systemctl restart docker
'
ret=$?
echo "Return code for docker exec was $ret"
if [[ $ret -ne 0 ]]; then
# Do it again
echo "Retrying after 5 seconds..."
sleep 5
docker exec -t $NODE bash -c '
set -xe
echo "%s '$(hostname)'.local" >> /etc/hosts
echo -n "10.%d." > /POD_IP_PREFIX
mkdir -p /etc/docker
echo "{\"insecure-registries\" : [\"%s.local:80\"]}" > /etc/docker/daemon.json
systemctl daemon-reload
systemctl restart docker
'
fi
`, node, runScriptDir, mountDockerAuth,
// clusterIpPrefix is used here to generate a
// SERVICE_CIDR...
serviceCIDR(clusterIpPrefix),
// ... and a POD_NETWORK_CIDR, which gets broken up
// into per-node /24s below (j+11)
podNetworkCIDR(clusterIpPrefix),
dindClusterScriptName, c.RunArgs(i, j),
// See also "k+11" elsewhere - this is the per-node pod
// network subnet, passed as the third argument to
// dind::run in dind-cluster-patched.sh.
// This transforms the 10.x.0.0/16 POD_NETWORK_CIDR
// above into a 10.x.j+11.0/24 pod network sub-range
// per node.
j+11,
hostIpFromContainer(c.GetIpPrefix()), clusterIpPrefix, hostname,
hostIpFromContainer(c.GetIpPrefix()), clusterIpPrefix, hostname),
)
},
fmt.Sprintf("starting container %s", node),
)
if err != nil {
return err
}
RegisterCleanupAction(10, fmt.Sprintf(
"NODE=%s ; docker exec -i $NODE systemctl stop docker || true; "+
"docker exec -i $NODE systemctl stop docker || true ; "+
"docker exec -i $NODE systemctl stop kubelet || true ; "+
"docker exec -i $NODE systemctl stop systemd-journald || true ; "+
"docker rm -f $NODE || true", node))
// as soon as this completes, add it to c.Nodes. more detail gets
// filled in later (eg dotmesh secrets), but it's important that
// the basics are in here so that the nodes get marked for cleanup
// if the setup fails (common w/kubernetes)
clusterName := fmt.Sprintf("cluster_%d", i)
c.AppendNode(NodeFromNodeName(t, stamp, i, j, clusterName))
// if we are testing dotmesh - then the binary under test will have
// already been created - otherwise, download the latest master build
// this is to be consistent with LocalImage()
serviceBeingTested := os.Getenv("CI_SERVICE_BEING_TESTED")
getDmCommand := fmt.Sprintf("NODE=%s\n", node)
ciJobId := os.Getenv("CI_JOB_ID")
if ciJobId == "" {
ciJobId = "local"
}
// if the CI_SERVICE_BEING_TESTED is empty it means we are in local testing mode
if serviceBeingTested == "dotmesh" || serviceBeingTested == "" {
// use the dm binary we have as part of the CI build
getDmCommand += "docker cp ../binaries/Linux/dm $NODE:/usr/local/bin/dm"
} else {
// otherwise download the dm binary from our release url
getDmCommand += fmt.Sprintf(`
CI_JOB_ID=%s
curl -L -o /tmp/dm-$CI_JOB_ID https://get.dotmesh.io/unstable/master/Linux/dm
chmod a+x /tmp/dm-$CI_JOB_ID
docker cp /tmp/dm-$CI_JOB_ID $NODE:/usr/local/bin/dm
rm -f /tmp/dm-$CI_JOB_ID
`, ciJobId)
}
err = System("bash", "-c", getDmCommand)
if err != nil {
return err
}
fmt.Printf("=== Started up %s\n", node)
}
}
return nil
}
type N struct {
Timestamp int64
ClusterNum string
NodeNum string
}
// InitialCleanup is called before starting tests
func InitialCleanup() {
// currently we only remove previous tests if we're using a cleanup strategy that leaves them lurking
switch getCleanupStrategy() {
case cleanupStrategyOnSuccess, cleanupStrategyNever, cleanupStrategyNone:
TeardownFinishedTestRuns()
case cleanupStrategyAlways:
// nothing to do
}
}
// FinalCleanup is called after running all the tests
func FinalCleanup(retcode int) {
// final cleanup is done based on cleanup strategy. For CI runs
// it should be set to 'always'
switch getCleanupStrategy() {
case cleanupStrategyAlways:
TeardownThisTestRun()
case cleanupStrategyOnSuccess:
if retcode == 0 {
TeardownThisTestRun()
} else {
fmt.Printf("[Final Cleanup] skipping cleanup as tests didn't pass, return code: %d", retcode)
}
case cleanupStrategyLater:
fd, err := os.OpenFile(testDirName(stamp)+"/finished", os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
fmt.Printf("[Final Cleanup] we failed to write the cleanup later file: %s", err.Error())
return
}
fd.Close()
case cleanupStrategyNever, cleanupStrategyNone:
// nothing to do
}
}
func RegisterCleanupAction(phase int, command string) {
err := System("mkdir",
"-p",
testDirName(stamp),
)
if err != nil {
panic(err)
}
f, err := os.OpenFile(fmt.Sprintf("%s/cleanup-actions.%02d", testDirName(stamp), phase),
os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0700)
if err != nil {
panic(err)
}
defer f.Close()
fmt.Fprintf(f, "%s\n", command)
}
func TeardownThisTestRun() {
// run cleanup actions, in order
err := System("bash", "-c", fmt.Sprintf(`for SCRIPT in %s/cleanup-actions.*; do set -x; . $SCRIPT; done`,
testDirName(stamp),
))
if err != nil {
fmt.Printf("err cleaning up test resources: %s\n", err)
}
}
func TeardownFinishedTestRuns() {
// Handle SIGQUIT and mark tests for cleanup in that case, then immediately
// exit.
go func() {
// From https://golang.org/pkg/os/signal/#Notify
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGQUIT)
signal.Notify(c, syscall.SIGINT)
signal.Notify(c, syscall.SIGTERM)
signal.Notify(c, syscall.SIGPIPE)
// Block until a signal is received.
s := <-c
log.Printf("Got signal: %s", s)
for _, f := range globalCleanupFuncs {
f()
}
os.Exit(131)
}()
cs, err := exec.Command(
"bash", "-c", "docker ps |grep cluster- || true",
).Output()
if err != nil {
panic(err)
}
fmt.Printf("============\nContainers running before cleanup:\n%s\n============\n", cs)
defer func() {
cs, err = exec.Command(
"bash", "-c", "docker ps |grep cluster- || true",
).Output()
if err != nil {
panic(err)
}
fmt.Printf("============\nContainers running after cleanup:\n%s\n============\n", cs)
}()
// There maybe other teardown processes running in parallel with this one.
// Check, and if there are, wait for it to complete and then return.
lockfile := "/dotmesh-test-cleanup.lock"
// if path exists, wait until it doesn't and then return.
if _, err := os.Stat(lockfile); err == nil {
for {
log.Printf(
"Waiting for %s to be deleted "+
"by some other cleanup process finishing...", lockfile,
)
time.Sleep(1 * time.Second)
if _, err := os.Stat(lockfile); os.IsNotExist(err) {
return
}
}
}
// if path doesn't exist, create it and clean it up on return
if _, err := os.Stat(lockfile); os.IsNotExist(err) {
f, err := os.Create(lockfile)
if err != nil {
return
}
if os.Getenv("CI_DOCKER_TAG") != "" {
// GitLab runner sets this env variable
_, err = f.WriteString(fmt.Sprintf("Time: %s Commit: %s\n", time.Now().String(), os.Getenv("CI_DOCKER_TAG")))
if err != nil {
log.Printf("Error writing timestamp and commit into the lockfile: %s", err)
}
} else {
// local run
_, err = f.WriteString(fmt.Sprintf("Time: %s", time.Now().String()))
if err != nil {
log.Printf("Error writing timestamp into the lockfile: %s\n", err)
}
}
f.Close()
defer os.RemoveAll(lockfile)
}
// Containers that weren't marked as CLEAN_ME_UP but which are older than
// an hour, assume they should be cleaned up.
err = System("../scripts/mark-old-cleanup.sh")
if err != nil {
log.Printf("Error running mark-old-cleanup.sh: %s", err)
}
cs, err = exec.Command(
"bash", "-c", "docker ps --format {{.Names}} |grep cluster- || true",
).Output()
if err != nil {
panic(err)
}
log.Printf("[TeardownFinishedTestRuns] cs = %s", cs)
stamps := map[int64][]N{}
for _, line := range strings.Split(string(cs), "\n") {
shrap := strings.Split(line, "-")
if len(shrap) > 4 {
// cluster-<timestamp>-<clusterNum>-node-<nodeNum>
stamp := shrap[1]
clusterNum := shrap[2]
nodeNum := shrap[4]
i, err := strconv.ParseInt(stamp, 10, 64)
if err != nil {
panic(err)
}
_, ok := stamps[i]
if !ok {
stamps[i] = []N{}
}
stamps[i] = append(stamps[i], N{
Timestamp: i,
ClusterNum: clusterNum,
NodeNum: nodeNum,
})
}
}
for stamp, ns := range stamps {
func() {
for _, n := range ns {
cn, err := strconv.Atoi(n.ClusterNum)
if err != nil {
fmt.Printf("can't deduce clusterNum: %d \n", cn)
return
}
nn, err := strconv.Atoi(n.NodeNum)
if err != nil {
fmt.Printf("can't deduce nodeNum: %d \n", nn)
return
}
node := nodeName(stamp, cn, nn)
existsErr := SilentSystem("docker", "inspect", node)
notExists := false
if existsErr != nil {
// must have been a single-node test, don't return on our
// behalf, we have zpool etc cleanup to do
notExists = true
}
err = System("docker", "exec", "-i", node, "test", "-e", "/CLEAN_ME_UP")
if err != nil {
fmt.Printf("not cleaning up %s because /CLEAN_ME_UP not found\n", node)
if !notExists {
return
}
}
err = System("docker", "rm", "-f", "-v", node)
if err != nil {
fmt.Printf("err during teardown %s\n", err)
}
// workaround https://github.com/docker/docker/issues/20398
err = System("docker", "network", "disconnect", "-f", "bridge", node)
if err != nil {
fmt.Printf("err during network force-disconnect %s\n", err)
}
// cleanup after a previous test run; this is a pretty gross hack
err = System("bash", "-c", fmt.Sprintf(`
for X in $(findmnt -P -R /tmpfs |grep %s); do
eval $X
if [ "$TARGET" != "/tmpfs" ]; then
umount $TARGET >/dev/null 2>&1 || true
fi
done
rm -rf /tmpfs/%s`, node, node),
)
if err != nil {
fmt.Printf("err during teardown %s\n", err)
}
}
// clean up any leftover zpools
out, err := exec.Command("zpool", "list", "-H").Output()
if err != nil {
fmt.Printf("unable to list zpools: %s\n", err)
}
shrap := strings.Split(string(out), "\n")
for _, s := range shrap {
shr := strings.Fields(string(s))
if len(shr) > 0 {
// Manually umount them and disregard failures
if strings.HasPrefix(shr[0], fmt.Sprintf("testpool-%d", stamp)) {
o, _ := exec.Command("bash", "-c",
fmt.Sprintf(
"for X in `cat /proc/self/mounts|grep testpool-%d"+
"|grep -v '/mnt '|cut -d ' ' -f 2`; do "+
"umount -f $X || true;"+
"done", stamp),
).CombinedOutput()
fmt.Printf("Attempted pre-cleanup output: %s\n", o)
o, err = exec.Command("zpool", "destroy", "-f", shr[0]).CombinedOutput()
if err != nil {
fmt.Printf("error running zpool destroy %s: %s %s\n", shr[0], o, err)
time.Sleep(1 * time.Second)
o, err := exec.Command("zpool", "destroy", "-f", shr[0]).CombinedOutput()
if err != nil {
fmt.Printf("Failed second try: %s %s", err, o)
}
}
fmt.Printf("=== Cleaned up zpool %s\n", shr[0])
}
}
}
// we can only clean up zpool data dirs after we release the zpools.
for _, n := range ns {
nodeSuffix := fmt.Sprintf("%d-%s-node-%s", stamp, n.ClusterNum, n.NodeNum)
// cleanup stray mounts, e.g. shm mounts
err = System("bash", "-c", fmt.Sprintf(`
for X in $(mount|cut -d ' ' -f 3 |grep %s); do
umount $X || true
done`, nodeSuffix),
)
if err != nil {
fmt.Printf("err during cleanup mounts: %s\n", err)
}
}
}()
out, err := exec.Command("docker", "volume", "prune", "-f").Output()
if err != nil {
fmt.Printf("unable to prune docker volumes: %s, %s\n", err, out)
}
}
err = System("docker", "container", "prune", "-f")
if err != nil {
fmt.Printf("Error from docker container prune -f: %v", err)
}
}
func FindAHostIP() (string, error) {
// Some terrible shell magic to find an interface that doesn't look
// like a docker, bridge, or loopback one and find its IP
// The intention is to find an IP that we can bind servers to on the
// host, that things running in Docker containers can connect to.
c := exec.Command("sh", "-c", "ip addr show `ifconfig -a | grep '^[a-z0-9]*:' | sed 's/:.*$//' | egrep -v 'docker|br-|lo|veth' | head -n 1` | grep -w inet | awk '{ print $2 }' | sed 's,/.*,,'")
out, err := c.CombinedOutput()
ip := strings.TrimRight(string(out), " \n")
return ip, err
}
func docker(node string, cmd string, env map[string]string) (string, error) {
args := []string{"exec"}
if env != nil {
for name, value := range env {
args = append(args, []string{"-e", fmt.Sprintf("%s=%s", name, value)}...)
}
}
args = append(args, []string{"-i", node, "bash", "-c", cmd}...)
c := exec.Command("docker", args...)
var b bytes.Buffer
var o, e io.Writer
if _, ok := env["DEBUG_MODE"]; ok {
o = io.MultiWriter(&b, os.Stdout)
e = io.MultiWriter(&b, os.Stderr)
} else {
o = io.MultiWriter(&b)
e = io.MultiWriter(&b)
}
c.Stdout = o
c.Stderr = e
err := c.Run()
return string(b.Bytes()), err
}
func dockerContext(ctx context.Context, node string, cmd string, env map[string]string) (string, error) {
args := []string{"exec"}
if env != nil {
for name, value := range env {
args = append(args, []string{"-e", fmt.Sprintf("%s=%s", name, value)}...)
}
}
args = append(args, []string{"-i", node, "bash", "-c", cmd}...)
c := exec.CommandContext(ctx, "docker", args...)
var b bytes.Buffer
var o, e io.Writer
if _, ok := env["DEBUG_MODE"]; ok {
o = io.MultiWriter(&b, os.Stdout)
e = io.MultiWriter(&b, os.Stderr)
} else {
o = io.MultiWriter(&b)
e = io.MultiWriter(&b)
}
c.Stdout = o
c.Stderr = e
err := c.Run()
return string(b.Bytes()), err
}
func RunOnNodeErr(node string, cmd string) (string, error) {
fmt.Printf("RUNNING on %s: %s\n", node, cmd)
return docker(node, cmd, nil)
}
// the same as RunOnNodeErr but will stream the outout to os.Stdout & os.Stderr
func RunOnNodeErrDebug(node string, cmd string) (string, error) {
fmt.Printf("RUNNING on %s: %s\n", node, cmd)
return docker(node, cmd, DEBUG_ENV)
}
func dockerSystem(node string, cmd string) error {
return System("docker", "exec", "-i", node, "sh", "-c", cmd)
}
func RunOnNode(t *testing.T, node string, cmd string) {
t.Helper()
fmt.Printf("RUNNING on %s: %s\n", node, cmd)
debugEnv := map[string]string{}
s, err := docker(node, cmd, debugEnv)
if err != nil {
t.Fatalf("%s while running %s on %s: %s", err, cmd, node, s)
}
}
func RunOnNodeContext(ctx context.Context, t *testing.T, node string, cmd string) {
t.Helper()
fmt.Printf("RUNNING on %s: %s\n", node, cmd)
debugEnv := map[string]string{}
s, err := dockerContext(ctx, node, cmd, debugEnv)
if err != nil {
select {
case <-ctx.Done():
// nothing to do, ctx was cancelled
return
default:
t.Fatalf("%s while running %s on %s: %s", err, cmd, node, s)
}
}
}
func RunOnNodeDebug(t *testing.T, node string, cmd string) {
fmt.Printf("RUNNING on %s: %s\n", node, cmd)
s, err := docker(node, cmd, DEBUG_ENV)
if err != nil {
t.Fatalf("%s while running %s on %s: %s", err, cmd, node, s)
}
}
// e.g. KubectlApply(t, node1, `yaml...`)
func KubectlApply(t *testing.T, node string, input string) {
c := exec.Command("docker", "exec", "-i", node, "kubectl", "apply", "-f", "-")
var b bytes.Buffer
o := io.MultiWriter(&b, os.Stdout)
e := io.MultiWriter(&b, os.Stderr)
c.Stdout = o
c.Stderr = e
stdin, err := c.StdinPipe()
if err != nil {
panic(err)
}
go func() {
stdin.Write([]byte(input))
stdin.Close()
}()
err = c.Run()
if err != nil {
t.Error(fmt.Errorf("%s while applying the following manifest on %s: %s\n%s", err, node, string(b.Bytes()), input))
}
}
func OutputFromRunOnNode(t *testing.T, node string, cmd string) string {
s, err := docker(node, cmd, nil)
if err != nil {
t.Error(fmt.Errorf("%s while running %s on %s: %s", err, cmd, node, s))
}
return s
}
func StreamOutputFromRunOnNode(t *testing.T, node string, cmd string) string {
env := make(map[string]string)
env["DEBUG_MODE"] = "1"
s, err := docker(node, cmd, env)
if err != nil {
t.Error(fmt.Errorf("%s while running %s on %s: %s", err, cmd, node, s))
}
return s
}
func LocalImage(service string) string {
var registry string
// See .gitlab-ci.yml in the dotmesh repo for where these are set up
if reg := os.Getenv("CI_REGISTRY"); reg != "" {
repo := os.Getenv("CI_PROJECT_PATH")
if repo == "" {
repo = os.Getenv("CI_REPOSITORY")
}
registry = reg + "/" + repo
}
var tag string
tagPreference := []string{"CI_DOCKER_TAG", "CI_COMMIT_TAG", "CI_COMMIT_SHA"}
for _, tagVariable := range tagPreference {
tag = os.Getenv(tagVariable)
if tag != "" {
break
}
}
if tag == "" {
tag = "latest"
}
// this means that if the X service is the one being tested - then
// use the GIT_HASH from CI for that service and 'latest-passing-tests' for everything else