dockerx

package
v0.0.0-...-c7b7835 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EnvDockerHost    = "DOCKER_HOST"
	EnvDockerContext = "DOCKER_CONTEXT"
	EnvDockerConfig  = "DOCKER_CONFIG"
	EnvXDGRuntime    = "XDG_RUNTIME_DIR"

	SourceEnvHost       = "DOCKER_HOST"
	SourceEnvContext    = "DOCKER_CONTEXT"
	SourceConfigContext = "docker context"
	SourceRootless      = "rootless socket"
	SourceDefault       = "default socket"
	SourceNone          = "none"
)
View Source
const (
	MutatorLabel = "khaos.mutator"
	MutatorValue = "true"
	MutatorRun   = "khaos.mutator.run"

	// MutatorNonce authorises the subcommand this container runs. The command
	// writes to a path it is given, so on the HOST it must refuse: khaos never
	// writes host-global state, and a command that would truncate any file it
	// is pointed at cannot be reachable by accident.
	MutatorNonce = "KHAOS_MUTATOR_NONCE"
)
View Source
const (
	// HeldSuffix is where the ORIGINAL container goes while a replacement runs
	// under its name. khaos never destroys it: a recreate from an inspection
	// loses the anonymous volume with its data stranded, every prior log line,
	// and the container id that invariant 8 re-verifies against. A rename
	// keeps all three and makes the revert a rename back.
	HeldSuffix = "-khaos-held"

	// HeldVarPrefix carries a variable's original value inside the container
	// while khaos is pretending it is absent, so the value never reaches
	// khaos's journal or its state directory. Same rule as the secret tier's
	// aside copy.
	HeldVarPrefix = "KHAOS_HELD_"
)
View Source
const (
	PredicateNotInspected    = "incomplete-inspection"
	PredicateConsentMissing  = "consent-label-missing"
	PredicateConsentNotTrue  = "consent-label-not-true"
	PredicateIdentityChanged = "identity-changed"
	PredicateSelfTarget      = "self-target"
	PredicateHostNetwork     = "host-network-mode"
	PredicateSharedNamespace = "shared-network-namespace"
	PredicateNamespacePeer   = "namespace-joined-by-peer"
	PredicateHostNamespace   = "host-namespace"
	PredicatePrivileged      = "privileged-container"
	PredicateDangerousCap    = "dangerous-capability"
	PredicateDeviceAccess    = "host-device-access"
	PredicateUnconfined      = "unconfined-security-profile"
	PredicateSocketReachable = "docker-socket-reachable"
	PredicateScopeMismatch   = "outside-declared-scope"
	PredicateNotRunning      = "container-not-running"
)
View Source
const (
	// These labels let an orphan survive khaos's death and be reclaimed by
	// label rather than by khaos remembering what it started.
	ResolverLabel        = "khaos.resolver"
	ResolverNetworkLabel = "khaos.resolver.network"
	ResolverNonceLabel   = "khaos.resolver.nonce"
	ResolverValue        = "true"

	// The tag carries a digest of khaos's binary, so a rebuilt khaos imports a
	// new image instead of running the previous build's resolver.
	ResolverImagePrefix = "khaos-dnsrv"

	ResolverEntrypoint = "/khaos"
	ResolverCommand    = "serve-resolver"

	// Where the control nonce travels; see resolverArgs for why not a flag.
	EnvResolverNonce = "KHAOS_RESOLVER_NONCE"
)
View Source
const (
	LabelConsent = "khaos.target"
	ConsentValue = "true"

	LabelComposeProject = "com.docker.compose.project"
	LabelComposeService = "com.docker.compose.service"
)
View Source
const (
	NetworkModeHost         = "host"
	NetworkModeContainerPfx = "container:"
	ModeHost                = "host"
)
View Source
const (
	DockerSocketPath = "/var/run/docker.sock"
)
View Source
const (
	FixNoTargets = "add `labels: [\"" + LabelConsent + "=" + ConsentValue + "\"]` to a service and recreate it, or run `khaos range up`"
)
View Source
const ShortIDLen = 12

Variables

View Source
var (
	ErrNoEndpoint       = errors.New("no Docker endpoint found")
	ErrSocketMissing    = errors.New("the Docker socket does not exist")
	ErrSocketDenied     = errors.New("permission denied on the Docker socket")
	ErrNotASocket       = errors.New("the Docker endpoint path is not a socket")
	ErrNothingListening = errors.New(
		"the Docker socket exists but nothing is listening on it",
	)
	ErrDaemonSilent = errors.New(
		"the Docker endpoint is reachable but the daemon did not answer",
	)
)
View Source
var (
	ErrNoHostConfig = errors.New(
		"the daemon returned a container with no host configuration, so khaos cannot tell whether it is safe to touch",
	)
	ErrEmptyName = errors.New("a target name is required")
)
View Source
var ErrContainerGone = errors.New("the container no longer exists")
View Source
var ErrContextUnresolvable = errors.New(
	"the selected Docker context could not be resolved",
)
View Source
var ErrDynamicSelf = errors.New(
	"this khaos binary is dynamically linked and cannot be its own container image",
)
View Source
var ErrImageDefinesVariable = errors.New(
	"the image defines that variable, so removing the container's copy changes nothing",
)
View Source
var ErrNetworkGone = errors.New(
	"the network no longer exists, so the container could not be reattached to it",
)
View Source
var ErrNoContainerConfig = errors.New(
	"the daemon returned no configuration to rebuild from",
)
View Source
var ErrResolverExists = errors.New(
	"a khaos resolver is already serving that network",
)
View Source
var ErrResolverNotFound = errors.New("no chaos resolver exists on that network")
View Source
var ErrUnreachableSecret = errors.New(
	"that path is not somewhere khaos can act and then undo",
)
View Source
var ErrVariableAbsent = errors.New(
	"that variable is not in the target's environment",
)

Functions

func ComposeEnvironment

func ComposeEnvironment(environ []string) ([]string, error)

func EnvValue

func EnvValue(environ []string, name string) (string, bool)

EnvValue reads one variable out of a captured environment, taking the LAST occurrence. Docker deduplicates on the whole `KEY=VALUE` string rather than on the key, so a shadowed variable appears twice and the last one is what the process sees - khaos has to read it the same way or it mis-reports its own fault.

func FileLevelMount

func FileLevelMount(m Mount, path string) bool

FileLevelMount reports whether the path IS the mount point rather than a file inside it. Renaming a mount point is impossible, which is the one mutation khaos has to refuse on that shape rather than approximate.

func HeldFor

func HeldFor(name string) string

HeldFor is where an unset keeps the original value: inside the replacement's own environment, under a name the target does not read.

func HeldName

func HeldName(name string) string

HeldName is the name the original container is renamed to.

func ImageDefines

func ImageDefines(imageEnv []string, name string) bool

ImageDefines reports whether the image bakes this variable in, which is the one precondition `env_unset` cannot work around.

func ResolverControlName

func ResolverControlName(networkName string) string

ResolverControlName is generated when the operator named no control. It is in `.invalid`, reserved by RFC 2606, so it can never collide with a real name.

func ResolverControlURL

func ResolverControlURL(address string) string

ResolverControlURL is on the container's own address, which the host routes to directly, so nothing is ever published.

func SelfContainerID

func SelfContainerID() string

func SelfStatic

func SelfStatic() error

SelfStatic refuses a khaos binary that cannot be its own container image. The check is on the ELF rather than a build tag because what matters is the artifact: cgo links libc for `net`, and that dies in a base-less image.

func ShadowedEmpty

func ShadowedEmpty(environ []string, name string) []string

ShadowedEmpty appends `NAME=` rather than replacing the original entry, which is what makes the fault reversible without khaos holding the value: the revert removes the LAST occurrence and the original is still underneath.

func ShortID

func ShortID(id string) string

func Variables

func Variables(environ []string) []string

Variables is every key a captured environment carries, for a refusal that names what IS there rather than only what is not.

func WithoutVariable

func WithoutVariable(environ []string, name string) []string

WithoutVariable removes every occurrence of a key, which is what an unset needs: leaving one behind would shadow the removal.

Types

type Check

type Check struct {
	Name   string
	Status Status
	Detail string
	Fix    string
}

func Diagnose

func Diagnose(ctx context.Context) []Check

func DiagnoseWith

func DiagnoseWith(
	ctx context.Context,
	environ func(string) string,
	home string,
) []Check

func (Check) OK

func (c Check) OK() bool

type Client

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

func Connect

func Connect(ctx context.Context, endpoint Endpoint) (*Client, error)

func Open

func Open(ctx context.Context) (*Client, error)

func (*Client) APIVersion

func (c *Client) APIVersion() string

func (*Client) Accept

func (c *Client) Accept(
	ctx context.Context,
	name string,
	filter Filter,
	guard Guard,
) (Target, error)

func (*Client) BridgeGateway

func (c *Client) BridgeGateway(ctx context.Context) (string, error)

BridgeGateway is the address a container reaches the host on: the DEFAULT bridge's gateway, discovered rather than assumed, since it is not 172.17.0.1 on every host. A user-defined network's own gateway is that network's default route and answers a ping, but a HOST LISTENER bound on it is refused from containers on the network, which is why this is not that address.

func (*Client) Capture

func (c *Client) Capture(
	ctx context.Context,
	containerID string,
) (Spec, error)

Capture reads a container back. The per-network EndpointSettings travel whole and are cleaned of the daemon's own identifiers: reconnecting with only a network NAME silently drops the static address, the MAC and every alias, and on a compose project the service name lives in the aliases, so every peer addressing it by name would get NXDOMAIN forever.

func (*Client) Close

func (c *Client) Close() error

func (*Client) Connect

func (c *Client) Connect(
	ctx context.Context,
	networkID, containerID string,
	settings *network.EndpointSettings,
) error

func (*Client) ContainerEnv

func (c *Client) ContainerEnv(
	ctx context.Context,
	containerID string,
) (map[string]string, error)

ContainerEnv reads where a target is ALREADY addressing its dependency. Environment is fixed at creation, so the container is the only authority on what it will dial.

func (*Client) Daemon

func (c *Client) Daemon() string

Daemon is a stable identity for the daemon this client is attached to, empty when the daemon would not say, which callers must treat as unknown rather than as a match.

func (*Client) DiscardResolver

func (c *Client) DiscardResolver(
	ctx context.Context,
	id string,
	cause error,
) error

func (*Client) Disconnect

func (c *Client) Disconnect(
	ctx context.Context,
	networkID, containerID string,
) error

func (*Client) Endpoint

func (c *Client) Endpoint() Endpoint

func (*Client) Endpoints

func (c *Client) Endpoints(
	ctx context.Context,
	containerID string,
) (map[string]*network.EndpointSettings, error)

func (*Client) FindResolver

func (c *Client) FindResolver(
	ctx context.Context,
	networkName string,
) (Resolver, error)

FindResolver matches by LABEL and not by name, because reclaim works from a cold start and a renamed resolver would otherwise be duplicated.

func (*Client) Gateways

func (c *Client) Gateways(ctx context.Context) ([]string, error)

Gateways is every address DOCKER manages as a network gateway, which is a narrower question than "is this a bridge". `/sys/class/net/<if>/bridge` exists for every kernel bridge device: measured on this host, that includes a CNI pod bridge, a swarm overlay's gateway bridge and forty-nine user-defined ones carrying unrelated projects' containers -- and on a host whose LAN interface is enslaved to a bridge, the routable LAN address itself. khaos binds listeners that answer whatever asks them, so the allowed set has to come from the daemon rather than from sysfs.

func (*Client) Identify

func (c *Client) Identify(ctx context.Context, ref string) (string, error)

Identify resolves a name to the IMMUTABLE container id behind it, or ErrContainerGone when nothing answers to it. A name is a label the daemon lets any container hold, and the environment tier hands one container's name to another on purpose, so anything destructive resolves first.

func (*Client) ImageEnv

func (c *Client) ImageEnv(ctx context.Context, image string) ([]string, error)

ImageEnv is what the IMAGE bakes in, which is not the same question as what the container carries. The daemon merges the image's environment into any key a create request omits, so a variable defined in both places cannot be taken away by omission.

func (*Client) ImportResolverImage

func (c *Client) ImportResolverImage(ctx context.Context) (string, error)

ImportResolverImage builds a single-layer image out of khaos's own binary, with no base image, no registry and no network, because a published image needs a registry and building one needs a source tree khaos may not have.

func (*Client) Lookup

func (c *Client) Lookup(
	ctx context.Context,
	name string,
	filter Filter,
) (Target, error)

func (*Client) Mutators

func (c *Client) Mutators(ctx context.Context) ([]string, error)

Mutators lists the helper containers khaos has left behind. Filtered by label=KEY=VALUE, never label=KEY: moby's MatchKVList splits on the first `=` and never compares a missing value, and this list is what a reclaim would force-remove.

func (*Client) NetworkAddress

func (c *Client) NetworkAddress(
	ctx context.Context,
	containerID, networkName string,
) (string, error)

func (*Client) OwnAddress

func (c *Client) OwnAddress(
	ctx context.Context,
	containerID string,
) (string, string, error)

OwnAddress is where khaos dials a target DIRECTLY, on the container's own address rather than on a published host port. The host routes to a bridge network's addresses, which is what makes a stateful dependency reachable with nothing published, and the network with the lowest name is chosen so two runs against a multi-homed container agree.

func (*Client) Pause

func (c *Client) Pause(ctx context.Context, containerID string) error

func (*Client) Paused

func (c *Client) Paused(ctx context.Context, containerID string) (bool, error)

func (*Client) PublishedPort

func (c *Client) PublishedPort(
	ctx context.Context,
	containerID string,
	internal int,
) (int, error)

func (*Client) Recreate

func (c *Client) Recreate(
	ctx context.Context,
	spec Spec,
	environ []string,
) (string, error)

Recreate creates and starts a container from a captured spec with a replaced environment, and returns its id. The caller has already renamed the original aside, so this is additive: nothing has been destroyed when it fails.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, containerID string) error

Remove removes a container khaos CREATED, and only ever the replacement it made itself. A container that is already gone is success, because a revert runs again after a reclaim.

func (*Client) RemoveMutator

func (c *Client) RemoveMutator(ctx context.Context, containerID string) error

func (*Client) RemoveResolver

func (c *Client) RemoveResolver(ctx context.Context, containerID string) error

RemoveResolver treats a missing container as success: the resolver went with it, and an error would wedge a journal record and stop `khaos reap` sweeping.

func (*Client) Rename

func (c *Client) Rename(ctx context.Context, containerID, name string) error

Rename is how the original is kept. The replacement takes the name, so every peer addressing the service by name reaches the replacement.

func (*Client) Resolvers

func (c *Client) Resolvers(ctx context.Context) ([]Resolver, error)

Resolvers lists every chaos resolver on this daemon.

func (*Client) RunMutator

func (c *Client) RunMutator(
	ctx context.Context,
	spec MutatorSpec,
) (string, error)

RunMutator creates the container, waits for it, and removes it. The exit code is read from the daemon rather than from the logs, and a non-zero one carries the container's own output, because a mutation that failed silently would leave khaos measuring an unfaulted target.

func (*Client) RunResolver

func (c *Client) RunResolver(
	ctx context.Context,
	spec ResolverSpec,
) (Resolver, error)

RunResolver reads the address back out of the daemon rather than choosing one, because Docker refuses `--ip` on a network whose subnet it picked, which is also why arming happens in band instead of by recreating the container.

func (*Client) Running

func (c *Client) Running(
	ctx context.Context,
	containerID string,
) (bool, error)

Running reports whether the container is up, which is how a restart obligation knows there is still something to put back.

func (*Client) ServerVersion

func (c *Client) ServerVersion() string

func (*Client) Start

func (c *Client) Start(ctx context.Context, containerID string) error

Start brings the original back after a revert has renamed it into place.

func (*Client) StatSecret

func (c *Client) StatSecret(
	ctx context.Context,
	containerID, path string,
) (SecretStat, error)

StatSecret never turns a missing file into an error, because absence is one of the four faults and has to be reportable as an observation.

func (*Client) Stop

func (c *Client) Stop(ctx context.Context, containerID string) error

Stop stops a container before it is renamed aside, because two containers cannot both hold a network's static address and a service's aliases. A container that is already stopped is success.

func (*Client) Targets

func (c *Client) Targets(ctx context.Context, filter Filter) ([]Target, error)

func (*Client) Unpause

func (c *Client) Unpause(ctx context.Context, containerID string) error

type Endpoint

type Endpoint struct {
	Host   string
	Source string
	Name   string
}

func ResolveEndpoint

func ResolveEndpoint(
	environ func(string) string,
	home string,
) (Endpoint, error)

func (Endpoint) SocketPath

func (e Endpoint) SocketPath() (string, bool)

type Filter

type Filter struct {
	Project string
}

type Guard

type Guard struct {
	Project    string
	SelfID     string
	ExpectedID string
}

type Mount

type Mount struct {
	Type        string `json:"type"`
	Source      string `json:"source"`
	Destination string `json:"destination"`
	ReadWrite   bool   `json:"read_write"`
	Name        string `json:"name,omitempty"`
}

Mount is one of the target's own mounts, read off its inspection. khaos replicates exactly the one containing the file it acts on, and never anything else the target can see.

func MountFor

func MountFor(target Target, path string) (Mount, error)

MountFor finds the mount that contains a path in the target's namespace, and refuses the two shapes khaos cannot act on reversibly.

type MutatorSpec

type MutatorSpec struct {
	RunID string
	Mount Mount
	Nonce string
	Args  []string
}

type Predicate

type Predicate struct {
	Name  string
	Check func(Target, Guard) *Refusal
}

type Refusal

type Refusal struct {
	Predicate string
	Target    string
	Reason    string
	Fix       string
}

func Refuse

func Refuse(t Target, g Guard) *Refusal

func (*Refusal) Error

func (r *Refusal) Error() string

type Resolver

type Resolver struct {
	ID      string
	Name    string
	Network string
	Address string
	Nonce   string
}

Resolver is a running chaos resolver container, as khaos addresses it.

type ResolverSpec

type ResolverSpec struct {
	Network string

	// Carries the network, so two resolvers on two networks cannot collide.
	Name string

	// Stored as a LABEL as well as passed in, so khaos reads it back off the
	// container rather than remembering what it chose.
	Nonce string

	Zone map[string]string

	Control string
}

ResolverSpec is what khaos needs to stand one up.

type SecretStat

type SecretStat struct {
	Exists bool
	Size   int64
	Mode   uint32
	Link   string
}

SecretStat is the TARGET's own view of a file, read through the archive endpoint's HEAD. It is the confirmation read-back for every secret fault: the mutator writes through a helper, and this is khaos asking the container under test what it now has. Measured to work on every mount shape, including the one the archive API cannot write.

type Spec

type Spec struct {
	Name       string
	Config     *container.Config
	HostConfig *container.HostConfig
	Networks   map[string]*network.EndpointSettings
}

Spec is everything needed to recreate one container. It is captured from the daemon rather than assembled, so nothing khaos forgot to copy can go missing.

type Status

type Status int
const (
	StatusPass Status = iota
	StatusFail
	StatusSkipped
)

type Target

type Target struct {
	ID           string
	Name         string
	Image        string
	ImageID      string
	Project      string
	Service      string
	Labels       map[string]string
	Running      bool
	NetworkMode  string
	PidMode      string
	IpcMode      string
	UsernsMode   string
	Privileged   bool
	Capabilities []string
	Devices      []string
	SecurityOpt  []string
	BindSources  []string

	// Mounts is every mount with its type and destination, which is what the
	// mutator tier needs to reach a file inside one. BindSources carries only
	// the sources, because the refusal predicates judge by resolved path.
	Mounts         []Mount
	NamespacePeers []string
	Inspected      bool
}

func (Target) Consented

func (t Target) Consented() bool

func (Target) Short

func (t Target) Short() string

Jump to

Keyboard shortcuts

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