dockerutil

package
v0.0.0-...-f76b1da Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 12, 2024 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package dockerutil contains helpers for interacting with Docker containers.

Index

Constants

View Source
const (
	// LabelPrefix is the reverse DNS format "namespace" for ibctest Docker labels.
	LabelPrefix = "ventures.strangelove.ibctest."

	// NodeOwnerLabel indicates the logical node owning a particular object (probably a volume).
	NodeOwnerLabel = LabelPrefix + "node-owner"
)
View Source
const CleanupLabel = "ibc-test"

CleanupLabel is a docker label key targeted by DockerSetup when it cleans up docker resources.

"ibctest" is perhaps a better name. However, for backwards compatability we preserve the original name of "ibc-test" with the hyphen. Otherwise, we run the risk of causing "container already exists" errors because DockerSetup is unable to clean old resources from docker engine.

Variables

View Source
var KeepVolumesOnFailure = os.Getenv("IBCTEST_SKIP_FAILURE_CLEANUP") != ""

KeepVolumesOnFailure determines whether volumes associated with a test using DockerSetup are retained or deleted following a test failure.

The value is false by default, but can be initialized to true by setting the environment variable IBCTEST_SKIP_FAILURE_CLEANUP to a non-empty value. Alternatively, importers of the dockerutil package may set the variable to true. Because dockerutil is an _internal package, the public API for setting this value is ibctest.KeepDockerVolumesOnFailure(bool).

Functions

func CleanDockerSetup

func CleanDockerSetup(t DockerSetupTestingT, name string)

func CondenseHostName

func CondenseHostName(name string) string

CondenseHostName truncates the middle of the given name if it is 64 characters or longer.

Without this helper, you may see an error like:

API error (500): failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: sethostname: invalid argument: unknown

func CopyFile

func CopyFile(src, dst string) (int64, error)

func DockerSetup

func DockerSetup(t DockerSetupTestingT) (*client.Client, string)

DockerSetup returns a new Docker Client and the ID of a configured network, associated with t.

If any part of the setup fails, DockerSetup panics because the test cannot continue.

func GetDockerUserString

func GetDockerUserString() string

func GetHeighlinerUserString

func GetHeighlinerUserString() string

func GetHostPort

func GetHostPort(cont types.ContainerJSON, portID string) string

GetHostPort returns a resource's published port with an address. cont is the type returned by the Docker client's ContainerInspect method.

func GetRootUserString

func GetRootUserString() string

func RandLowerCaseLetterString

func RandLowerCaseLetterString(length int) string

RandLowerCaseLetterString returns a lowercase letter string of given length

func SanitizeContainerName

func SanitizeContainerName(name string) string

SanitizeContainerName returns name with any invalid characters replaced with underscores. Subtests will include slashes, and there may be other invalid characters too.

func SetVolumeOwner

func SetVolumeOwner(ctx context.Context, opts VolumeOwnerOptions) error

SetVolumeOwner configures the owner of a volume to match the default user in the supplied image reference.

func StartContainer

func StartContainer(ctx context.Context, cli *client.Client, id string) error

StartContainer attempts to start the container with the given ID.

Types

type Container

type Container struct {
	Name     string
	Hostname string
	// contains filtered or unexported fields
}

Container is a docker container. Use (*Image).Start to create a new container.

func (*Container) Stop

func (c *Container) Stop(timeout time.Duration) error

Stop gives the container up to timeout to stop and remove itself from the network.

func (*Container) Wait

func (c *Container) Wait(ctx context.Context, logTail uint64) ContainerExecResult

Wait blocks until the container exits. Calling wait is not suitable for daemons and servers. A non-zero status code returns an error.

Wait implicitly calls Stop. If logTail is non-zero, the stdout and stderr logs will be truncated at the end to that number of lines.

type ContainerExecResult

type ContainerExecResult struct {
	Err            error // Err is nil, unless some error occurs during the container lifecycle.
	ExitCode       int
	Stdout, Stderr []byte
}

ContainerExecResult is a wrapper type that wraps an exit code and associated output from stderr & stdout, along with an error in the case of some error occurring during container execution.

type ContainerLifecycle

type ContainerLifecycle struct {
	// contains filtered or unexported fields
}

func NewContainerLifecycle

func NewContainerLifecycle(log *zap.Logger, client *dockerclient.Client, containerName string) *ContainerLifecycle

func (*ContainerLifecycle) ContainerID

func (c *ContainerLifecycle) ContainerID() string

func (*ContainerLifecycle) CreateContainer

func (c *ContainerLifecycle) CreateContainer(
	ctx context.Context,
	testName string,
	networkID string,
	image ibc.DockerImage,
	ports nat.PortSet,
	volumeBinds []string,
	hostName string,
	cmd []string,
	env []string,
) error

func (*ContainerLifecycle) GetHostPorts

func (c *ContainerLifecycle) GetHostPorts(ctx context.Context, portIDs ...string) ([]string, error)

func (*ContainerLifecycle) RemoveContainer

func (c *ContainerLifecycle) RemoveContainer(ctx context.Context) error

func (*ContainerLifecycle) StartContainer

func (c *ContainerLifecycle) StartContainer(ctx context.Context) error

func (*ContainerLifecycle) StopContainer

func (c *ContainerLifecycle) StopContainer(ctx context.Context) error

type ContainerOptions

type ContainerOptions struct {
	// bind mounts: https://docs.docker.com/storage/bind-mounts/
	Binds []string

	// Environment variables
	Env []string

	// If blank, defaults to the container's default user.
	User string

	// If non-zero, will limit the amount of log lines returned.
	LogTail uint64
}

ContainerOptions optionally configures starting a Container.

type DockerSetupTestingT

type DockerSetupTestingT interface {
	Helper()

	Name() string

	Failed() bool
	Cleanup(func())

	Logf(format string, args ...any)
}

DockerSetupTestingT is a subset of testing.T required for DockerSetup.

type FileRetriever

type FileRetriever struct {
	// contains filtered or unexported fields
}

FileRetriever allows retrieving a single file from a Docker volume. In the future it may allow retrieving an entire directory.

func NewFileRetriever

func NewFileRetriever(log *zap.Logger, cli *client.Client, testName string) *FileRetriever

NewFileRetriever returns a new FileRetriever.

func (*FileRetriever) SingleFileContent

func (r *FileRetriever) SingleFileContent(ctx context.Context, volumeName, relPath string) ([]byte, error)

SingleFileContent returns the content of the file named at relPath, inside the volume specified by volumeName.

type FileWriter

type FileWriter struct {
	// contains filtered or unexported fields
}

FileWriter allows retrieving a single file from a Docker volume. In the future it may allow retrieving an entire directory.

func NewFileWriter

func NewFileWriter(log *zap.Logger, cli *client.Client, testName string) *FileWriter

NewFileWriter returns a new FileWriter.

func (*FileWriter) WriteFile

func (w *FileWriter) WriteFile(ctx context.Context, volumeName, relPath string, content []byte) error

WriteFile writes the single file containing content, at relPath within the given volume.

type Image

type Image struct {
	// contains filtered or unexported fields
}

Image is a docker image.

func NewImage

func NewImage(logger *zap.Logger, cli *client.Client, networkID string, testName string, repository, tag string) *Image

NewImage returns a valid Image.

"pool" and "networkID" are likely from DockerSetup. "testName" is from a (*testing.T).Name() and should match the t.Name() from DockerSetup to ensure proper cleanup.

Most arguments (except tag) must be non-zero values or this function panics. If tag is absent, defaults to "latest". Currently, only public docker images are supported.

func (*Image) Run

func (image *Image) Run(ctx context.Context, cmd []string, opts ContainerOptions) ContainerExecResult

Run creates and runs a container invoking "cmd". The container resources are removed after exit.

Run blocks until the command completes. Thus, Run is not suitable for daemons or servers. Use Start instead. A non-zero status code returns an error.

func (*Image) Start

func (image *Image) Start(ctx context.Context, cmd []string, opts ContainerOptions) (*Container, error)

Start pulls the image if not present, creates a container, and runs it.

type Listeners

type Listeners []net.Listener

func GeneratePortBindings

func GeneratePortBindings(portSet nat.PortSet) (nat.PortMap, Listeners, error)

GeneratePortBindings will find open ports on the local machine and create a PortBinding for every port in the portSet.

func (Listeners) CloseAll

func (l Listeners) CloseAll()

type VolumeOwnerOptions

type VolumeOwnerOptions struct {
	Log *zap.Logger

	Client *client.Client

	VolumeName string
	ImageRef   string
	TestName   string
	UidGid     string
}

VolumeOwnerOptions contain the configuration for the SetVolumeOwner function.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL