github.com/vipernet-xyz/tm@v0.34.24/test/e2e/runner/cleanup.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/vipernet-xyz/tm/libs/log"
    10  	e2e "github.com/vipernet-xyz/tm/test/e2e/pkg"
    11  )
    12  
    13  // Cleanup removes the Docker Compose containers and testnet directory.
    14  func Cleanup(testnet *e2e.Testnet) error {
    15  	err := cleanupDocker()
    16  	if err != nil {
    17  		return err
    18  	}
    19  	err = cleanupDir(testnet.Dir)
    20  	if err != nil {
    21  		return err
    22  	}
    23  	return nil
    24  }
    25  
    26  // cleanupDocker removes all E2E resources (with label e2e=True), regardless
    27  // of testnet.
    28  func cleanupDocker() error {
    29  	logger.Info("Removing Docker containers and networks")
    30  
    31  	// GNU xargs requires the -r flag to not run when input is empty, macOS
    32  	// does this by default. Ugly, but works.
    33  	xargsR := `$(if [[ $OSTYPE == "linux-gnu"* ]]; then echo -n "-r"; fi)`
    34  
    35  	err := exec("bash", "-c", fmt.Sprintf(
    36  		"docker container ls -qa --filter label=e2e | xargs %v docker container rm -f", xargsR))
    37  	if err != nil {
    38  		return err
    39  	}
    40  
    41  	err = exec("bash", "-c", fmt.Sprintf(
    42  		"docker network ls -q --filter label=e2e | xargs %v docker network rm", xargsR))
    43  	if err != nil {
    44  		return err
    45  	}
    46  
    47  	return nil
    48  }
    49  
    50  // cleanupDir cleans up a testnet directory
    51  func cleanupDir(dir string) error {
    52  	if dir == "" {
    53  		return errors.New("no directory set")
    54  	}
    55  
    56  	_, err := os.Stat(dir)
    57  	if os.IsNotExist(err) {
    58  		return nil
    59  	} else if err != nil {
    60  		return err
    61  	}
    62  
    63  	logger.Info("cleanup dir", "msg", log.NewLazySprintf("Removing testnet directory %q", dir))
    64  
    65  	// On Linux, some local files in the volume will be owned by root since Tendermint
    66  	// runs as root inside the container, so we need to clean them up from within a
    67  	// container running as root too.
    68  	absDir, err := filepath.Abs(dir)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	err = execDocker("run", "--rm", "--entrypoint", "", "-v", fmt.Sprintf("%v:/network", absDir),
    73  		"tendermint/e2e-node", "sh", "-c", "rm -rf /network/*/")
    74  	if err != nil {
    75  		return err
    76  	}
    77  
    78  	err = os.RemoveAll(dir)
    79  	if err != nil {
    80  		return err
    81  	}
    82  
    83  	return nil
    84  }