forked from cometbft/cometbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.go
87 lines (73 loc) · 2.15 KB
/
cleanup.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
package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/KYVENetwork/cometbft/v38/libs/log"
e2e "github.com/KYVENetwork/cometbft/v38/test/e2e/pkg"
"github.com/KYVENetwork/cometbft/v38/test/e2e/pkg/exec"
"github.com/KYVENetwork/cometbft/v38/test/e2e/pkg/infra/docker"
)
// Cleanup removes the Docker Compose containers and testnet directory.
func Cleanup(testnet *e2e.Testnet) error {
err := cleanupDocker()
if err != nil {
return err
}
err = cleanupDir(testnet.Dir)
if err != nil {
return err
}
return nil
}
// cleanupDocker removes all E2E resources (with label e2e=True), regardless
// of testnet.
func cleanupDocker() error {
logger.Info("Removing Docker containers and networks")
// GNU xargs requires the -r flag to not run when input is empty, macOS
// does this by default. Ugly, but works.
xargsR := `$(if [[ $OSTYPE == "linux-gnu"* ]]; then echo -n "-r"; fi)`
err := exec.Command(context.Background(), "bash", "-c", fmt.Sprintf(
"docker container ls -qa --filter label=e2e | xargs %v docker container rm -f", xargsR))
if err != nil {
return err
}
err = exec.Command(context.Background(), "bash", "-c", fmt.Sprintf(
"docker network ls -q --filter label=e2e | xargs %v docker network rm", xargsR))
if err != nil {
return err
}
return nil
}
// cleanupDir cleans up a testnet directory
func cleanupDir(dir string) error {
if dir == "" {
return errors.New("no directory set")
}
_, err := os.Stat(dir)
if os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
logger.Info("cleanup dir", "msg", log.NewLazySprintf("Removing testnet directory %q", dir))
// On Linux, some local files in the volume will be owned by root since CometBFT
// runs as root inside the container, so we need to clean them up from within a
// container running as root too.
absDir, err := filepath.Abs(dir)
if err != nil {
return err
}
err = docker.Exec(context.Background(), "run", "--rm", "--entrypoint", "", "-v", fmt.Sprintf("%v:/network", absDir),
"cometbft/e2e-node", "sh", "-c", "rm -rf /network/*/")
if err != nil {
return err
}
err = os.RemoveAll(dir)
if err != nil {
return err
}
return nil
}