dockerclient

package
v0.0.0-...-ad6cacf Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 17 Imported by: 6

Documentation

Index

Constants

View Source
const (
	// RunOptionsRandomPort urge docker shell client not to map an explicit source port (but rather a random one)
	RunOptionsRandomPort int = -1
	// RunOptionsNoPort urge docker shell client not to map any port
	RunOptionsNoPort int = -2
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Address

type Address struct {
	Addr      string
	PrefixLen int
}

Address represents an IP address

type BuildOptions

type BuildOptions struct {
	Image          string
	ContextDir     string
	DockerfilePath string
	NoCache        bool
	Pull           bool
	BuildArgs      map[string]string
	BuildFlags     map[string]bool
}

BuildOptions are options for building a docker image

type Client

type Client interface {

	// Build will build a docker image, given build options
	Build(buildOptions *BuildOptions) error

	// CopyObjectsFromImage copies objects (files, directories) from a given image to local storage. it does
	// this through an intermediate container which is deleted afterwards
	CopyObjectsFromImage(imageName string, objectsToCopy map[string]string, allowCopyErrors bool) error

	// PushImage pushes a local image to a remote docker repository
	PushImage(imageName string, registryURL string) error

	// PullImage pulls an image from a remote docker repository
	PullImage(imageURL string) error

	// RemoveImage will remove (delete) a local image
	RemoveImage(imageName string) error

	// RunContainer will run a container based on an image and run options
	RunContainer(imageName string, runOptions *RunOptions) (string, error)

	// ExecInContainer will run a command in a container
	ExecInContainer(containerID string, execOptions *ExecOptions) error

	// RemoveContainer removes a container given a container ID
	RemoveContainer(containerID string) error

	// StopContainer removes a container given a container ID
	StopContainer(containerID string) error

	// StartContainer starts a container given a container ID
	StartContainer(containerID string) error

	// GetContainerPort returns container port
	GetContainerPort(container *Container, boundPort int) (int, error)

	// GetContainerLogs returns raw logs from a given container ID
	GetContainerLogs(containerID string) (string, error)

	// GetContainers returns a list of containers which match a certain criteria
	GetContainers(*GetContainerOptions) ([]Container, error)

	// GetContainerEvents returns a list of container events which occurred within a time range
	GetContainerEvents(containerName string, since string, until string) ([]string, error)

	// AwaitContainerHealth blocks until the given container is healthy or the timeout passes
	AwaitContainerHealth(containerID string, timeout *time.Duration) error

	// LogIn allows docker client to access secured registries
	LogIn(options *LogInOptions) error

	// CreateNetwork creates a docker network
	CreateNetwork(*CreateNetworkOptions) error

	// GetContainerNetworkSettings returns container network settings
	GetContainerNetworkSettings(containerID string) (*NetworkSettings, error)

	// DeleteNetwork deletes a docker network
	DeleteNetwork(networkName string) error

	// CreateVolume create a docker volume
	CreateVolume(*CreateVolumeOptions) error

	// DeleteVolume delete a docker volume
	DeleteVolume(volumeName string) error

	// Save saves a docker image as tar in specified path
	Save(imageName string, outPath string) error

	// Load loads a docker image from tar as cached image
	Load(inPath string) error

	// GetVersion returns docker client and engine versions
	GetVersion(quiet bool) (string, error)

	// GetContainerIPAddresses return list of container ip addresses
	GetContainerIPAddresses(containerID string) ([]string, error)

	// GetContainerLogStream return container log stream
	GetContainerLogStream(ctx context.Context, containerID string, logOptions *ContainerLogsOptions) (io.ReadCloser, error)
}

type Config

type Config struct {
	Hostname     string              // Hostname
	Domainname   string              // Domainname
	User         string              // User that will run the command(s) inside the container, also support user:group
	AttachStdin  bool                // Attach the standard input, makes possible user interaction
	AttachStdout bool                // Attach the standard output
	AttachStderr bool                // Attach the standard error
	Tty          bool                // Attach standard streams to a tty, including stdin if it is not closed.
	OpenStdin    bool                // Open stdin
	StdinOnce    bool                // If true, close stdin after the 1 attached client disconnects.
	Env          []string            // List of environment variable to set in the container
	Cmd          StrSlice            // Command to run when starting the container
	Image        string              // Name of the image as it was passed by the operator (e.g. could be symbolic)
	Volumes      map[string]struct{} // List of volumes (mounts) used for the container
	WorkingDir   string              // Current directory (PWD) in the command will be launched
	Entrypoint   StrSlice            // Entrypoint to run when starting the container
	OnBuild      []string            // ONBUILD metadata that were defined on the image Dockerfile
	Labels       map[string]string   // List of labels set to this container
}

Config contains the configuration data about a container. It should hold only portable information about the container. Here, "portable" means "independent from the host we are running on". Non-portable information *should* appear in HostConfig. All fields added to this struct must be marked `omitempty` to keep getting predictable hashes from the old `v1Compatibility` configuration.

type Container

type Container struct {
	ID              string `json:"Id"`
	Created         string
	Path            string
	Args            []string
	State           *ContainerState
	Image           string
	ResolvConfPath  string
	HostnamePath    string
	HostsPath       string
	LogPath         string
	Name            string
	RestartCount    int
	Driver          string
	Platform        string
	MountLabel      string
	ProcessLabel    string
	AppArmorProfile string
	ExecIDs         []string
	HostConfig      *HostConfig
	Mounts          []MountPoint
	Config          *Config
	NetworkSettings *NetworkSettings
}

Container contains response of Engine API: GET "/containers/{name:.*}/json"

type ContainerLogsOptions

type ContainerLogsOptions struct {
	ShowStdout bool
	ShowStderr bool
	Since      string
	Until      string
	Timestamps bool
	Follow     bool
	Tail       string
	Details    bool
}

ContainerLogsOptions holds parameters to filter logs with https://github.com/moby/moby/blob/v20.10.6/api/types/client.go#L73

type ContainerState

type ContainerState struct {
	Status     string // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead"
	Running    bool
	Paused     bool
	Restarting bool
	OOMKilled  bool
	Dead       bool
	Pid        int
	ExitCode   int
	Error      string
	StartedAt  string
	FinishedAt string
	Health     *Health
}

ContainerState stores container's running state it's part of ContainerJSONBase and will return by "inspect" command

type CreateNetworkOptions

type CreateNetworkOptions struct {
	Name string
}

CreateNetworkOptions are options for creating a network

type CreateVolumeOptions

type CreateVolumeOptions struct {
	Name string
}

CreateVolumeOptions are options for creating a volume

type DefaultNetworkSettings

type DefaultNetworkSettings struct {
	EndpointID          string // EndpointID uniquely represents a service endpoint in a Sandbox
	Gateway             string // Gateway holds the gateway address for the network
	GlobalIPv6Address   string // GlobalIPv6Address holds network's global IPv6 address
	GlobalIPv6PrefixLen int    // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address
	IPAddress           string // IPAddress holds the IPv4 address for the network
	IPPrefixLen         int    // IPPrefixLen represents mask length of network's IPv4 address
	IPv6Gateway         string // IPv6Gateway holds gateway address specific for IPv6
	MacAddress          string // MacAddress holds the MAC address for the network
}

DefaultNetworkSettings holds network information during the 2 release deprecation period. It will be removed in Docker 1.11.

type EndpointSettings

type EndpointSettings struct {
	// Configurations
	Links   []string
	Aliases []string
	// Operational data
	NetworkID           string
	EndpointID          string
	Gateway             string
	IPAddress           string
	IPPrefixLen         int
	IPv6Gateway         string
	GlobalIPv6Address   string
	GlobalIPv6PrefixLen int
	MacAddress          string
	DriverOpts          map[string]string
}

EndpointSettings stores the network endpoint details

type ExecOptions

type ExecOptions struct {
	Command string
	Stdout  *string
	Stderr  *string
	Env     map[string]string
}

ExecOptions are options for executing a command in a container

type GetContainerOptions

type GetContainerOptions struct {
	Name    string
	Labels  map[string]string
	Stopped bool
	ID      string
}

GetContainerOptions are options for container search

type Health

type Health struct {
	Status        string
	FailingStreak int
	Log           []HealthLog
}

Health stores container health state

type HealthLog

type HealthLog struct {
	Start    string
	End      string
	ExitCode int
	Output   string
}

HealthLog stores container health logs

type HostConfig

type HostConfig struct {
	// Applicable to all platforms
	Binds           []string      // List of volume bindings for this container
	ContainerIDFile string        // File (path) where the containerId is written
	LogConfig       LogConfig     // Configuration of the logs for this container
	NetworkMode     string        // Network mode to use for the container
	PortBindings    PortMap       // Port mapping between the exposed port (container) and the host
	RestartPolicy   RestartPolicy // Restart policy to be used for the container
	AutoRemove      bool          // Automatically remove container when it exits
	VolumeDriver    string        // Name of the volume driver used to mount volumes
	VolumesFrom     []string      // List of volumes to take from other container

	// Applicable to UNIX platforms
	CapAdd          StrSlice          // List of kernel capabilities to add to the container
	CapDrop         StrSlice          // List of kernel capabilities to remove from the container
	DNS             []string          `json:"Dns"`        // List of DNS server to lookup
	DNSOptions      []string          `json:"DnsOptions"` // List of DNSOption to look for
	DNSSearch       []string          `json:"DnsSearch"`  // List of DNSSearch to look for
	ExtraHosts      []string          // List of extra hosts
	GroupAdd        []string          // List of additional groups that the container process will run as
	IpcMode         string            // IPC namespace to use for the container
	Cgroup          string            // Cgroup to use for the container
	Links           []string          // List of links (in the name:alias form)
	OomScoreAdj     int               // Container preference for OOM-killing
	PidMode         string            // PID namespace to use for the container
	Privileged      bool              // Is the container in privileged mode
	PublishAllPorts bool              // Should docker publish all exposed port for the container
	ReadonlyRootfs  bool              // Is the container root filesystem in read-only
	SecurityOpt     []string          // List of string values to customize labels for MLS systems, such as SELinux.
	StorageOpt      map[string]string `json:",omitempty"` // Storage driver options per container.
	Tmpfs           map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container
	UTSMode         string            // UTS namespace to use for the container
	UsernsMode      string            // The user namespace to use for the container
	ShmSize         int64             // Total shm memory usage
	Sysctls         map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container
	Runtime         string            `json:",omitempty"` // Runtime to use with this container

	// Applicable to Windows
	ConsoleSize [2]uint // Initial console size (height,width)
	Isolation   string  // Isolation technology of the container (e.g. default, hyperv)

	// Run a custom init inside the container, if null, use the daemon's configured settings
	Init *bool `json:",omitempty"`
}

HostConfig the non-portable Config structure of a container. Here, "non-portable" means "dependent of the host we are running on". Portable information *should* appear in Config.

type LogConfig

type LogConfig struct {
	Type   string
	Config map[string]string
}

LogConfig represents the logging configuration of the container.

type LogInOptions

type LogInOptions struct {
	Username string
	Password string
	URL      string
}

LogInOptions are options for logging in

type MockDockerClient

type MockDockerClient struct {
	mock.Mock
}

func NewMockDockerClient

func NewMockDockerClient() *MockDockerClient

func (*MockDockerClient) AwaitContainerHealth

func (mdc *MockDockerClient) AwaitContainerHealth(containerID string, timeout *time.Duration) error

AwaitContainerHealth blocks until the given container is healthy or the timeout passes

func (*MockDockerClient) Build

func (mdc *MockDockerClient) Build(buildOptions *BuildOptions) error

Build will build a docker image, given build options

func (*MockDockerClient) CopyObjectsFromImage

func (mdc *MockDockerClient) CopyObjectsFromImage(imageName string, objectsToCopy map[string]string, allowCopyErrors bool) error

CopyObjectsFromImage copies objects (files, directories) from a given image to local storage. it does this through an intermediate container which is deleted afterwards

func (*MockDockerClient) CreateNetwork

func (mdc *MockDockerClient) CreateNetwork(options *CreateNetworkOptions) error

CreateNetwork creates a docker network

func (*MockDockerClient) CreateVolume

func (mdc *MockDockerClient) CreateVolume(options *CreateVolumeOptions) error

CreateVolume creates a docker volume

func (*MockDockerClient) DeleteNetwork

func (mdc *MockDockerClient) DeleteNetwork(networkName string) error

DeleteNetwork deletes a docker network

func (*MockDockerClient) DeleteVolume

func (mdc *MockDockerClient) DeleteVolume(volumeName string) error

DeleteVolume deletes a docker volume

func (*MockDockerClient) ExecInContainer

func (mdc *MockDockerClient) ExecInContainer(containerID string, execOptions *ExecOptions) error

ExecInContainer will run a command in a container

func (*MockDockerClient) GetContainerEvents

func (mdc *MockDockerClient) GetContainerEvents(containerName string, since string, until string) ([]string, error)

GetContainerEvents returns a list of container events which occurred within a time range

func (*MockDockerClient) GetContainerIPAddresses

func (mdc *MockDockerClient) GetContainerIPAddresses(containerID string) ([]string, error)

func (*MockDockerClient) GetContainerLogStream

func (mdc *MockDockerClient) GetContainerLogStream(ctx context.Context,
	containerID string,
	logOptions *ContainerLogsOptions) (io.ReadCloser, error)

func (*MockDockerClient) GetContainerLogs

func (mdc *MockDockerClient) GetContainerLogs(containerID string) (string, error)

GetContainerLogs returns raw logs from a given container ID

func (*MockDockerClient) GetContainerNetworkSettings

func (mdc *MockDockerClient) GetContainerNetworkSettings(containerID string) (*NetworkSettings, error)

func (*MockDockerClient) GetContainerPort

func (mdc *MockDockerClient) GetContainerPort(container *Container, boundPort int) (int, error)

func (*MockDockerClient) GetContainers

func (mdc *MockDockerClient) GetContainers(options *GetContainerOptions) ([]Container, error)

GetContainers returns a list of container IDs which match a certain criteria

func (*MockDockerClient) GetVersion

func (mdc *MockDockerClient) GetVersion(quiet bool) (string, error)

func (*MockDockerClient) Load

func (mdc *MockDockerClient) Load(inPath string) error

Load loads a docker image from path

func (*MockDockerClient) LogIn

func (mdc *MockDockerClient) LogIn(options *LogInOptions) error

LogIn allows docker client to access secured registries

func (*MockDockerClient) PullImage

func (mdc *MockDockerClient) PullImage(imageURL string) error

PullImage pulls an image from a remote docker repository

func (*MockDockerClient) PushImage

func (mdc *MockDockerClient) PushImage(imageName string, registryURL string) error

PushImage pushes a local image to a remote docker repository

func (*MockDockerClient) RemoveContainer

func (mdc *MockDockerClient) RemoveContainer(containerID string) error

RemoveContainer removes a container given a container ID

func (*MockDockerClient) RemoveImage

func (mdc *MockDockerClient) RemoveImage(imageName string) error

RemoveImage will remove (delete) a local image

func (*MockDockerClient) RunContainer

func (mdc *MockDockerClient) RunContainer(imageName string, runOptions *RunOptions) (string, error)

RunContainer will run a container based on an image and run options

func (*MockDockerClient) Save

func (mdc *MockDockerClient) Save(imageName string, outPath string) error

Save saves a docker image in path

func (*MockDockerClient) StartContainer

func (mdc *MockDockerClient) StartContainer(containerID string) error

StartContainer stops a container given a container ID

func (*MockDockerClient) StopContainer

func (mdc *MockDockerClient) StopContainer(containerID string) error

StopContainer stops a container given a container ID

type MountPoint

type MountPoint struct {
	Source      string
	Destination string
	Mode        string
	RW          bool
	Type        string
	Driver      string
	Name        string
}

MountPoint represents a mount point configuration inside the container. This is used for reporting the mountpoints in use by a container.

type NetworkSettings

type NetworkSettings struct {
	NetworkSettingsBase
	DefaultNetworkSettings
	Networks map[string]*EndpointSettings
}

NetworkSettings exposes the network settings in the api

type NetworkSettingsBase

type NetworkSettingsBase struct {
	Bridge                 string  // Bridge is the Bridge name the network uses(e.g. `docker0`)
	SandboxID              string  // SandboxID uniquely represents a container's network stack
	HairpinMode            bool    // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
	LinkLocalIPv6Address   string  // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix
	LinkLocalIPv6PrefixLen int     // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address
	Ports                  PortMap // Ports is a collection of PortBinding indexed by Port
	SandboxKey             string  // SandboxKey identifies the sandbox
	SecondaryIPAddresses   []Address
	SecondaryIPv6Addresses []Address
}

NetworkSettingsBase holds basic information about networks

type Port

type Port string

Port is a string containing port number and protocol in the format "80/tcp"

type PortBinding

type PortBinding struct {
	// HostIP is the host IP Address
	HostIP string `json:"HostIp"`
	// HostPort is the host port number
	HostPort string
}

PortBinding represents a binding between a Host IP address and a Host Port

type PortMap

type PortMap map[Port][]PortBinding

PortMap is a collection of PortBinding indexed by Port

type PortSet

type PortSet map[Port]struct{}

PortSet is a collection of structs indexed by Port

type RestartPolicy

type RestartPolicy struct {
	Name              RestartPolicyName
	MaximumRetryCount int
}

RestartPolicy represents the restart policies of the container.

type RestartPolicyName

type RestartPolicyName string
const (
	RestartPolicyNameUnlessStopped RestartPolicyName = "unless-stopped"
	RestartPolicyNameAlways        RestartPolicyName = "always"
	RestartPolicyNameNo            RestartPolicyName = "no"
	RestartPolicyNameOnFailure     RestartPolicyName = "on-failure"
)

type RunOptions

type RunOptions struct {
	Ports            map[int]int
	ContainerName    string
	Env              map[string]string
	Labels           map[string]string
	Volumes          map[string]string
	Remove           bool
	Command          string
	Stdout           *string
	Stderr           *string
	Attach           bool
	ImageMayNotExist bool
	Network          string
	RestartPolicy    *RestartPolicy
	GPUs             string
	CPUs             string
	Memory           string
	MountPoints      []MountPoint
	RunAsUser        *int64
	RunAsGroup       *int64
	FSGroup          *int64
	Devices          []string
}

RunOptions are options for running a docker image

type ShellClient

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

ShellClient is a docker client that uses the shell to communicate with docker

func NewShellClient

func NewShellClient(parentLogger logger.Logger, runner cmdrunner.CmdRunner) (*ShellClient, error)

NewShellClient creates a new docker client

func (*ShellClient) AwaitContainerHealth

func (c *ShellClient) AwaitContainerHealth(containerID string, timeout *time.Duration) error

AwaitContainerHealth blocks until the given container is healthy or the timeout passes

func (*ShellClient) Build

func (c *ShellClient) Build(buildOptions *BuildOptions) error

Build will build a docker image, given build options

func (*ShellClient) CopyObjectsFromImage

func (c *ShellClient) CopyObjectsFromImage(imageName string,
	objectsToCopy map[string]string,
	allowCopyErrors bool) error

CopyObjectsFromImage copies objects (files, directories) from a given image to local storage. it does this through an intermediate container which is deleted afterwards

func (*ShellClient) CreateNetwork

func (c *ShellClient) CreateNetwork(options *CreateNetworkOptions) error

CreateNetwork creates a docker network

func (*ShellClient) CreateVolume

func (c *ShellClient) CreateVolume(options *CreateVolumeOptions) error

CreateVolume creates a docker volume

func (*ShellClient) DeleteNetwork

func (c *ShellClient) DeleteNetwork(networkName string) error

DeleteNetwork deletes a docker network

func (*ShellClient) DeleteVolume

func (c *ShellClient) DeleteVolume(volumeName string) error

DeleteVolume deletes a docker volume

func (*ShellClient) ExecInContainer

func (c *ShellClient) ExecInContainer(containerID string, execOptions *ExecOptions) error

ExecInContainer will run a command in a container

func (*ShellClient) GetContainerEvents

func (c *ShellClient) GetContainerEvents(containerName string, since string, until string) ([]string, error)

GetContainerEvents returns a list of container events which occurred within a time range

func (*ShellClient) GetContainerIPAddresses

func (c *ShellClient) GetContainerIPAddresses(containerID string) ([]string, error)

func (*ShellClient) GetContainerLogStream

func (c *ShellClient) GetContainerLogStream(ctx context.Context,
	containerID string,
	logOptions *ContainerLogsOptions) (io.ReadCloser, error)

func (*ShellClient) GetContainerLogs

func (c *ShellClient) GetContainerLogs(containerID string) (string, error)

GetContainerLogs returns raw logs from a given container ID Concatenating stdout and stderr since there's no way to re-interlace them

func (*ShellClient) GetContainerNetworkSettings

func (c *ShellClient) GetContainerNetworkSettings(containerID string) (*NetworkSettings, error)

GetContainerNetworkSettings returns container network settings

func (*ShellClient) GetContainerPort

func (c *ShellClient) GetContainerPort(container *Container, boundPort int) (int, error)

func (*ShellClient) GetContainers

func (c *ShellClient) GetContainers(options *GetContainerOptions) ([]Container, error)

GetContainers returns a list of container IDs which match a certain criteria

func (*ShellClient) GetVersion

func (c *ShellClient) GetVersion(quiet bool) (string, error)

func (*ShellClient) Load

func (c *ShellClient) Load(inPath string) error

func (*ShellClient) LogIn

func (c *ShellClient) LogIn(options *LogInOptions) error

LogIn allows docker client to access secured registries

func (*ShellClient) PullImage

func (c *ShellClient) PullImage(imageURL string) error

PullImage pulls an image from a remote docker repository

func (*ShellClient) PushImage

func (c *ShellClient) PushImage(imageName string, registryURL string) error

PushImage pushes a local image to a remote docker repository

func (*ShellClient) RemoveContainer

func (c *ShellClient) RemoveContainer(containerID string) error

RemoveContainer removes a container given a container ID

func (*ShellClient) RemoveImage

func (c *ShellClient) RemoveImage(imageName string) error

RemoveImage will remove (delete) a local image

func (*ShellClient) RunContainer

func (c *ShellClient) RunContainer(imageName string, runOptions *RunOptions) (string, error)

RunContainer will run a container based on an image and run options

func (*ShellClient) Save

func (c *ShellClient) Save(imageName string, outPath string) error

func (*ShellClient) StartContainer

func (c *ShellClient) StartContainer(containerID string) error

StartContainer stops a container given a container ID

func (*ShellClient) StopContainer

func (c *ShellClient) StopContainer(containerID string) error

StopContainer stops a container given a container ID

type StrSlice

type StrSlice []string

StrSlice represents a string or an array of strings. We need to override the json decoder to accept both options.

func (*StrSlice) UnmarshalJSON

func (e *StrSlice) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the byte slice whether it's a string or an array of strings. This method is needed to implement json.Unmarshaler.

Jump to

Keyboard shortcuts

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