container

package
v0.0.0-...-6c5e6c9 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const LabelModuleVersion = "io.thin-edge.module.version"

LabelModuleVersion is a container label used to record the exact module version string supplied by the software management layer at install time. Storing this separately from the Docker image reference avoids depending on how different Docker/Podman versions normalise image tag strings (e.g. older Docker v20 strips the registry host prefix from image names).

Variables

View Source
var ContainerGroupType string = "container-group"
View Source
var ContainerStatusHealthy = "healthy"
View Source
var ContainerType string = "container"
View Source
var ErrNoImage = errors.New("no container image found")
View Source
var ErrPodmanAPIError = errors.New("podman api not available")

Functions

func CheckPodmanComposeError

func CheckPodmanComposeError(b string) error

func CloneContainerConfig

func CloneContainerConfig(ref *container.Config, opts CloneOptions) *container.Config

func CloneHostConfig

func CloneHostConfig(ref *container.HostConfig, opts CloneOptions) *container.HostConfig

func CloneNetworkConfig

func CloneNetworkConfig(ref *container.NetworkSettings) *network.NetworkingConfig

Clone network settings, but only clone the network ids that the container is part of don't clone everything as it leads to incompatibilities between engine versions

func ConvertName

func ConvertName(v []string) string

func ConvertToTedgeStatus

func ConvertToTedgeStatus(v string) string

func EnsureExtraHost

func EnsureExtraHost(ctx context.Context, composePaths []string, _ string, hostname, ipValue string) error

EnsureExtraHost ensures every service in composePaths[0] that does not already define hostname in extra_hosts has "hostname=ipValue" added. Services that already define the hostname (under either the "=" or ":" separator convention) are left unchanged. The file is not written when no patch is required. The yaml node tree is modified in-place so existing formatting and comments are preserved.

func FilterEnvVariables

func FilterEnvVariables(l []string, exclude []string) []string

func FilterLabels

func FilterLabels(l map[string]string, exclude []string) map[string]string

func FormatContainerName

func FormatContainerName(v string) string

func FormatLabels

func FormatLabels(labels []string) map[string]string

func FormatPorts

func FormatPorts(values []container.Port) string

func GetRegistryAuth

func GetRegistryAuth(username, password string) string

func GetUserID

func GetUserID() string

func ImageRefsEqual

func ImageRefsEqual(a, b string) bool

ImageRefsEqual reports whether two image reference strings refer to the same image, normalising both sides before comparing.

func IsInsideContainer

func IsInsideContainer() bool

func NewStdWriter

func NewStdWriter(w io.Writer, t StdType) io.Writer

NewStdWriter instantiates a new Writer. Everything written to it will be encapsulated using a custom format, and written to the underlying `w` stream. This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. `t` indicates the id of the stream to encapsulate. It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr.

func NormalizeImageRef

func NormalizeImageRef(imageRef string) string

func ParseContainerGroup

func ParseContainerGroup(v string) (projectName string, serviceName string, ok bool)

func ReadImages

func ReadImages(ctx context.Context, paths []string, workingDir string) ([]string, error)

func ReadModuleName

func ReadModuleName(workingDir string) string

ReadModuleName reads the module name (line 2) from the version file stored in workingDir. Returns an empty string if the file is absent or line 2 is missing/empty, so callers should fall back to the compose project name.

func ResolveDockerIOImage

func ResolveDockerIOImage(imageRef string) (string, bool)

Check if the given docker.io image has fully qualified (e.g. docker.io/library/<image>) if not, then expand it to its fully qualified name.

func StdCopy

func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error)

StdCopy is a modified version of io.Copy.

StdCopy will demultiplex `src`, assuming that it contains two streams, previously multiplexed together using a StdWriter instance. As it reads from `src`, StdCopy will write to `dstout` and `dsterr`.

StdCopy will read until it hits EOF on `src`. It will then return a nil error. In other words: if `err` is non nil, it indicates a real underlying error.

`written` will hold the total number of bytes written to `dstout` and `dsterr`.

Types

type ClientOptions

type ClientOptions struct {
	Attempts      int
	Host          string
	RetryInterval time.Duration
}

type CloneOptions

type CloneOptions struct {
	Name         string
	Image        string
	HealthyAfter time.Duration
	StopAfter    time.Duration
	StopTimeout  time.Duration
	WaitForExit  bool
	AutoRemove   bool
	Env          []string
	ExtraHosts   []string
	Cmd          strslice.StrSlice
	Entrypoint   strslice.StrSlice
	IgnorePorts  bool
	Labels       map[string]string

	SkipNetwork   bool
	IgnoreEnvVars []string
}

type Container

type Container struct {
	Name        string   `json:"-"`
	Id          string   `json:"containerId,omitempty"`
	State       string   `json:"state,omitempty"`
	Status      string   `json:"containerStatus,omitempty"`
	CreatedAt   string   `json:"createdAt,omitempty"`
	Image       string   `json:"image,omitempty"`
	Ports       string   `json:"ports,omitempty"`
	NetworkIDs  []string `json:"-"`
	Networks    string   `json:"networks,omitempty"`
	RunningFor  string   `json:"runningFor,omitempty"`
	Filesystem  string   `json:"filesystem,omitempty"`
	Command     string   `json:"command,omitempty"`
	NetworkMode string   `json:"networkMode,omitempty"`

	// Only used for container groups
	ServiceName string `json:"serviceName,omitempty"`
	ProjectName string `json:"projectName,omitempty"`
	ModuleName  string `json:"-"`

	// Private values
	Labels map[string]string `json:"-"`
}

func (*Container) GetName

func (c *Container) GetName() string

type ContainerClient

type ContainerClient struct {
	Client *client.Client
	Engine EngineCapabilities
	// LibPod is a client for the podman-native libpod REST API. It is non-nil
	// only when Engine.HasLibPodAPI is true and the API responded successfully
	// during initialisation.
	LibPod *SocketClient
}

func NewContainerClient

func NewContainerClient(ctx context.Context, opts ...Opt) (*ContainerClient, error)

func (*ContainerClient) CloneContainer

func (c *ContainerClient) CloneContainer(ctx context.Context, containerID string, opts CloneOptions) error

Clone an existing container by spawning a new container with the same configuration but using a new image

func (*ContainerClient) ComposeDown

func (c *ContainerClient) ComposeDown(ctx context.Context, w io.Writer, projectName string, defaultWorkingDir string) error

func (*ContainerClient) ComposeUp

func (c *ContainerClient) ComposeUp(ctx context.Context, w io.Writer, projectName string, workingDir string, extraArgs ...string) error

func (*ContainerClient) ContainerLogs

func (c *ContainerClient) ContainerLogs(ctx context.Context, w io.Writer, containerID string, opts LogsOptions) error

func (*ContainerClient) CreateSharedNetwork

func (c *ContainerClient) CreateSharedNetwork(ctx context.Context, name string) error

Create shared network

func (*ContainerClient) DockerCommand

func (c *ContainerClient) DockerCommand(args ...string) (string, []string, error)

func (*ContainerClient) Fork

func (c *ContainerClient) Fork(ctx context.Context, currentContainer container.InspectResponse, cloneOptions CloneOptions) error

func (*ContainerClient) GetContainer

func (c *ContainerClient) GetContainer(ctx context.Context, containerID string) (*TedgeContainer, error)

func (*ContainerClient) GetNetworkGateway

func (c *ContainerClient) GetNetworkGateway(ctx context.Context, name string) string

GetNetworkGateway returns the IPv4 gateway address of the named network, or an empty string if it cannot be determined.

func (*ContainerClient) GetRestartCount

func (c *ContainerClient) GetRestartCount(ctx context.Context, containerID string) (int, error)

GetRestartCount returns the number of times the Docker daemon has restarted this container since it was created. The value comes from ContainerInspect because ContainerList (Summary) does not expose it. Daemon-initiated restarts (restart policy) increment the counter; manual "docker restart" commands do not.

func (*ContainerClient) GetStats

func (c *ContainerClient) GetStats(ctx context.Context, containerID string) (*ContainerTelemetryMessage, error)

func (*ContainerClient) ImagePullWithRetries

func (c *ContainerClient) ImagePullWithRetries(ctx context.Context, imageRef string, alwaysPull bool, opts ImagePullOptions) (*image.InspectResponse, error)

Pull a container image. The image will be verified if it exists afterwards

Use credentials function to generate initial credentials and call again if the credentials fail which gives the credentials helper to invalid its own cache

func (*ContainerClient) ImagesPruneUnused

func (c *ContainerClient) ImagesPruneUnused(ctx context.Context) (image.PruneReport, error)

Prune both unused and dangling images

func (*ContainerClient) IsPodman

func (c *ContainerClient) IsPodman() bool

IsPodman reports whether the connected container engine is podman.

func (*ContainerClient) List

func (c *ContainerClient) List(ctx context.Context, options FilterOptions) ([]TedgeContainer, error)

func (*ContainerClient) LookupProject

func (c *ContainerClient) LookupProject(ctx context.Context, projectName string, serviceName string) ([]container.Summary, error)

func (*ContainerClient) MonitorEvents

func (c *ContainerClient) MonitorEvents(ctx context.Context) (<-chan events.Message, <-chan error)

func (*ContainerClient) ResolveComposeProjectName

func (c *ContainerClient) ResolveComposeProjectName(ctx context.Context, name string) (string, error)

ResolveComposeProjectName resolves a name that may be either a Docker compose project name (from the com.docker.compose.project label) or a stored module name (line 2 of the version file in the project working dir). It returns the actual Docker compose project name to use for API calls, or the input name unchanged if no match is found.

func (*ContainerClient) RestartContainer

func (c *ContainerClient) RestartContainer(ctx context.Context, containerID string) error

RestartContainer a container

func (*ContainerClient) Self

Get the container id which is running the current process

Finding the container that the process is running in is fairly complicated due to the differences between the container engines and versions (e.g. podman, docker etc.)

  1. Check if hostname matches the container id/name
  2. Look through each con 2.1 Check container ID file (if the file exists) 2.2 Check HOSTNAME env variable (e.g. HOSTNAME={hostname}) 2.3 Check HostConfig.Hostname value

func (*ContainerClient) StartContainer

func (c *ContainerClient) StartContainer(ctx context.Context, containerID string) error

func (*ContainerClient) StopContainer

func (c *ContainerClient) StopContainer(ctx context.Context, containerID string) error

func (*ContainerClient) StopRemoveContainer

func (c *ContainerClient) StopRemoveContainer(ctx context.Context, containerID string) error

Stop and remove a container Don't fail if the container does not exist

func (*ContainerClient) UpdateRequired

func (c *ContainerClient) UpdateRequired(ctx context.Context, containerID string, newImage string) (bool, container.InspectResponse, error)

func (*ContainerClient) WaitForHealthy

func (c *ContainerClient) WaitForHealthy(ctx context.Context, containerID string) error

func (*ContainerClient) WaitForStop

func (c *ContainerClient) WaitForStop(ctx context.Context, containerID string) error

Wait for a container to be stopped by polling it's status Avoid using ContainerWait is it is not compatible with older docker versions and probably less compatible with podman

type ContainerStats

type ContainerStats struct {
	Cpu    LowPrecisionFloat `json:"cpu"`
	Memory LowPrecisionFloat `json:"memory"`
	NetIO  LowPrecisionFloat `json:"netio"`
}

type ContainerTelemetryMessage

type ContainerTelemetryMessage struct {
	Container ContainerStats `json:"container"`
}

type EngineCapabilities

type EngineCapabilities struct {
	// Type is the engine variant, e.g. EnginePodman or EngineDocker.
	Type EngineType

	// HasLibPodAPI indicates that the libpod REST API is available at the same
	// socket. Only true for podman instances.
	HasLibPodAPI bool

	// Version is the server version string reported by the engine (e.g. "4.6.1").
	Version string
}

EngineCapabilities describes the features available from the detected engine. Adding a new engine in the future means adding fields here (and a new case in detectEngineCapabilities) without touching any call sites.

type EngineType

type EngineType string

EngineType identifies the container engine backend. Use the typed constants rather than raw string comparisons throughout the codebase.

const (
	EngineDocker  EngineType = "docker"
	EnginePodman  EngineType = "podman"
	EngineUnknown EngineType = "unknown"
)

type FilterOptions

type FilterOptions struct {
	Names  []string
	Labels []string
	IDs    []string

	// Client side filters
	Types            []string
	ExcludeNames     []string
	ExcludeWithLabel []string
}

func (FilterOptions) IsEmpty

func (fo FilterOptions) IsEmpty() bool

type ImagePullOptions

type ImagePullOptions struct {
	AuthFunc    func(context.Context, int) (string, error)
	MaxAttempts int
	Wait        time.Duration
}

type JSONTime

type JSONTime struct {
	time.Time
	AsRFC3339 bool
}

func NewJSONTime

func NewJSONTime(t time.Time) JSONTime

func (JSONTime) MarshalJSON

func (t JSONTime) MarshalJSON() ([]byte, error)

func (*JSONTime) UnmarshalJSON

func (t *JSONTime) UnmarshalJSON(data []byte) error

type LibPodHostConfig

type LibPodHostConfig struct {
	// UsernsMode is the user-namespace mode as stored by podman, e.g. "" (host),
	// "private", "keep-id", "keep-id:uid=X,gid=Y", "nomap", etc.
	// NOTE: podman 4.x normalises "keep-id" to "private" here; use IDMappings
	// to detect the original mode when this field cannot be trusted.
	UsernsMode string            `json:"UsernsMode"`
	IDMappings *LibPodIDMappings `json:"IDMappings,omitempty"`
}

LibPodHostConfig mirrors the HostConfig portion of a libpod container inspect response. Unlike the Docker-compat API, podman returns the original value for fields like UsernsMode (e.g. "keep-id") rather than a normalised substitute (e.g. "private").

type LibPodIDMappings

type LibPodIDMappings struct {
	UIDMap []string `json:"UIDMap"`
	GIDMap []string `json:"GIDMap"`
}

LibPodIDMappings holds the UID/GID mapping tables for a container's user namespace. Each entry is in "containerID:hostID:size" format.

type LibPodInfo

type LibPodInfo struct {
	Host LibPodInfoHost `json:"host"`
}

LibPodInfo is a minimal subset of GET /libpod/info, used to surface diagnostically-relevant configuration (e.g. the events backend).

type LibPodInfoHost

type LibPodInfoHost struct {
	EventLogger string `json:"eventLogger"`
}

type LibPodInspectResponse

type LibPodInspectResponse struct {
	HostConfig LibPodHostConfig `json:"HostConfig"`
}

LibPodInspectResponse is a minimal subset of the JSON returned by GET /libpod/containers/{name}/json. Only the fields needed to recover namespace settings that the Docker-compat API normalises away are captured here. Add fields as needed; unused fields are silently ignored during JSON deserialisation.

type LogsOptions

type LogsOptions container.LogsOptions

Log options type alias

type LowPrecisionFloat

type LowPrecisionFloat struct {
	// Value
	Value float64

	// Number of digital to display
	Digits int
}

Custom float representation which controls how many decimal places are used when marshalling the value to JSON

func NewLowerPrecisionFloat64

func NewLowerPrecisionFloat64(value float64, precision int) LowPrecisionFloat

func (LowPrecisionFloat) MarshalJSON

func (l LowPrecisionFloat) MarshalJSON() ([]byte, error)

type Opt

type Opt func(o *ClientOptions) error

func WithAttempts

func WithAttempts(total int) Opt

func WithHost

func WithHost(host string) Opt

func WithInfiniteRetries

func WithInfiniteRetries() Opt

func WithRetryInterval

func WithRetryInterval(v time.Duration) Opt

type PodmanAPIPullOptions

type PodmanAPIPullOptions struct {
	AllTags   *bool  `url:"allTags,omitempty"`
	Quiet     *bool  `url:"quiet,omitempty"`
	Policy    string `url:"policy,omitempty"`
	Reference string `url:"reference"`
}

func (*PodmanAPIPullOptions) WithAllTags

func (po *PodmanAPIPullOptions) WithAllTags(v bool) *PodmanAPIPullOptions

func (*PodmanAPIPullOptions) WithPolicy

func (*PodmanAPIPullOptions) WithQuiet

type PodmanPullOptions

type PodmanPullOptions struct {
	image.PullOptions

	Quiet bool
}

type ResponsePruneImage

type ResponsePruneImage struct {
	Id   string `json:"Id,omitempty"`
	Size uint64 `json:"Size,omitempty"`
}

type SocketClient

type SocketClient struct {
	BaseURL string
	Client  *http.Client
}

func NewDefaultLibPodHTTPClient

func NewDefaultLibPodHTTPClient() *SocketClient

func NewLibPodHTTPClient

func NewLibPodHTTPClient(sock string) *SocketClient

func (*SocketClient) ContainerInspect

func (c *SocketClient) ContainerInspect(ctx context.Context, nameOrID string) (*LibPodInspectResponse, error)

ContainerInspect fetches the libpod-native inspect data for the named container. The returned struct contains fields that the Docker-compat API normalises away (e.g. UsernsMode "keep-id" becomes "private" via compat).

func (*SocketClient) Events

func (c *SocketClient) Events(ctx context.Context) (<-chan events.Message, <-chan error)

Events subscribes to the libpod native events stream (GET /libpod/events) and returns channels with the same signature as the Docker-compat client Events API so that MonitorEvents can use it transparently.

The libpod events endpoint sends newline-delimited JSON objects whose field names match the Go docker/docker events.Message type directly (Type, Action, Actor.ID, Actor.Attributes, time, timeNano), so we decode straight into events.Message without a separate intermediate type.

func (*SocketClient) GetEventsBackend

func (c *SocketClient) GetEventsBackend(ctx context.Context) string

GetEventsBackend queries GET /libpod/info and returns the configured events backend (e.g. "journald", "file", "none"). An empty string is returned if the field cannot be read; callers should treat that as unknown and proceed.

func (*SocketClient) PruneImages

func (c *SocketClient) PruneImages(body io.Reader) (report image.PruneReport, err error)

Prune all images and return object in same format as the docker prune response

func (*SocketClient) PullImages

func (c *SocketClient) PullImages(ctx context.Context, imageRef string, alwaysPull bool, pullOptions PodmanPullOptions) error

func (*SocketClient) Test

func (c *SocketClient) Test(ctx context.Context) error

type Stats

type Stats struct {
	StatsEntry
	// contains filtered or unexported fields
}

Stats represents an entity to store containers statistics synchronously

func NewStats

func NewStats(container string) *Stats

NewStats returns a new Stats entity and sets in it the given name

func (*Stats) GetError

func (cs *Stats) GetError() error

GetError returns the container statistics error. This is used to determine whether the statistics are valid or not

func (*Stats) GetStatistics

func (cs *Stats) GetStatistics() StatsEntry

GetStatistics returns container statistics with other meta data such as the container name

func (*Stats) SetError

func (cs *Stats) SetError(err error)

SetError sets container statistics error

func (*Stats) SetErrorAndReset

func (cs *Stats) SetErrorAndReset(err error)

SetErrorAndReset zeroes all the container statistics and store the error. It is used when receiving time out error during statistics collecting to reduce lock overhead

func (*Stats) SetStatistics

func (cs *Stats) SetStatistics(s StatsEntry)

SetStatistics set the container statistics

type StatsEntry

type StatsEntry struct {
	Container        string
	Name             string
	ID               string
	CPUPercentage    float64
	Memory           float64 // On Windows this is the private working set
	MemoryLimit      float64 // Not used on Windows
	MemoryPercentage float64 // Not used on Windows
	NetworkRx        float64
	NetworkTx        float64
	BlockRead        float64
	BlockWrite       float64
	PidsCurrent      uint64 // Not used on Windows
	IsInvalid        bool
}

StatsEntry represents the statistics data collected from a container

type StdType

type StdType byte

StdType is the type of standard stream a writer can multiplex to.

const (
	// Stdin represents standard input stream type.
	Stdin StdType = iota
	// Stdout represents standard output stream type.
	Stdout
	// Stderr represents standard error steam type.
	Stderr
	// Systemerr represents errors originating from the system that make it
	// into the multiplexed stream.
	Systemerr
)

type TedgeContainer

type TedgeContainer struct {
	Name        string    `json:"name"`
	Status      string    `json:"status"`
	ServiceType string    `json:"serviceType"`
	Container   Container `json:"container"`
	Time        JSONTime  `json:"time"`
}

func NewContainerFromDockerContainer

func NewContainerFromDockerContainer(item *container.Summary) TedgeContainer

Jump to

Keyboard shortcuts

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