containers¶
Model and Manager for Container resources.
- class Container(attrs: Mapping[str, Any] | None = None, client: APIClient | None = None, collection: Manager | None = None, podman_client: PodmanClient | None = None)[source]¶
Bases:
PodmanResourceDetails and configuration for a container managed by the Podman service.
Initialize base class for PodmanResource’s.
- Parameters:
attrs – Mapping of attributes for resource from Podman service.
client – Configured connection to a Podman service.
collection – Manager of this category of resource, named collection for compatibility
podman_client – PodmanClient() configured to connect to Podman object.
- attach(**kwargs) str | Iterator[str][source]¶
Attach to container’s tty.
- Keyword Arguments:
stdout (bool) – Include stdout. Default: True
stderr (bool) – Include stderr. Default: True
stream (bool) – Return iterator of string(s) vs single string. Default: False
logs (bool) – Include previous container output. Default: False
- Raises:
NotImplementedError – method not implemented.
- attach_socket(**kwargs)[source]¶
Not Implemented.
- Raises:
NotImplementedError – method not implemented.
- commit(repository: str = None, tag: str = None, **kwargs) Image[source]¶
Save container to given repository.
- Parameters:
repository – Where to save Image
tag – Tag to push with Image
- Keyword Arguments:
author (str) – Name of commit author
changes (list[str]) – Instructions to apply during commit
comment (str) – Commit message to include with Image, overrides keyword message
conf (dict[str, Any]) – Ignored.
format (str) – Format of the image manifest and metadata
message (str) – Commit message to include with Image
pause (bool) – Pause the container before committing it
- diff() list[dict[str, int]][source]¶
Report changes of a container’s filesystem.
- Raises:
APIError – when service reports an error
- exec_run(cmd: str | list[str], *, stdout: bool = True, stderr: bool = True, stdin: bool = False, tty: bool = False, privileged: bool = False, user=None, detach: bool = False, stream: bool = False, socket: bool = False, environment: Mapping[str, str] | list[str] = None, workdir: str = None, demux: bool = False) tuple[int | None, Iterator[bytes | tuple[bytes, bytes]] | Any | tuple[bytes, bytes]][source]¶
Run given command inside container and return results.
- Parameters:
cmd – Command to be executed
stdout – Attach to stdout. Default: True
stderr – Attach to stderr. Default: True
stdin – Attach to stdin. Default: False
tty – Allocate a pseudo-TTY. Default: False
privileged – Run as privileged.
user – User to execute command as.
detach – If true, detach from the exec command. Default: False
stream – Stream response data. Ignored if
detachisTrue. Default: Falsesocket – Return the connection socket to allow custom read/write operations. Default: False
environment – A dictionary or a list[str] in the following format [“PASSWORD=xxx”] or {“PASSWORD”: “xxx”}.
workdir – Path to working directory for this exec session
demux – Return stdout and stderr separately
- Returns:
A tuple of (
response_code,output).response_code:The exit code of the provided command.
Noneifstream.output:If
stream, then a generator yielding response chunks. Ifdemux, then a tuple of (stdout,stderr). Else the response content.
- Raises:
NotImplementedError – method not implemented.
APIError – when service reports error
- export(chunk_size: int = 2097152) Iterator[bytes][source]¶
Download container’s filesystem contents as a tar archive.
- Parameters:
chunk_size – <= number of bytes to return for each iteration of the generator.
- Yields:
tarball in size/chunk_size chunks
- Raises:
NotFound – when container has been removed from service
APIError – when service reports an error
- get_archive(path: str, chunk_size: int = 2097152) tuple[Iterable, dict[str, Any]][source]¶
Download a file or folder from the container’s filesystem.
- Parameters:
path – Path to file or folder.
chunk_size – <= number of bytes to return for each iteration of the generator.
- Returns:
First item is a raw tar data stream. Second item is a dict containing os.stat() information on the specified path.
- kill(signal: str | int | None = None) None[source]¶
Send signal to container.
- Raises:
APIError – when service reports an error
- logs(**kwargs) bytes | Iterator[bytes][source]¶
Get logs from the container.
- Keyword Arguments:
stdout (bool) – Include stdout. Default: True
stderr (bool) – Include stderr. Default: True
stream (bool) – Return generator of strings as the response. Default: False
timestamps (bool) – Show timestamps in output. Default: False
tail (Union[str, int]) – Output specified number of lines at the end of logs. Integer representing the number of lines to display, or the string all. Default: all
since (Union[datetime, int]) – Show logs since a given datetime or integer epoch (in seconds)
follow (bool) – Follow log output. Default: False
until (Union[datetime, int]) – Show logs that occurred before the given datetime or integer epoch (in seconds)
- put_archive(path: str, data: bytes = None) bool[source]¶
Upload tar archive containing a file or folder to be written into container.
- Parameters:
path – File to write data into
data – Contents to write to file, when None path will be read on client to build tarfile.
- Returns:
True when successful
- Raises:
APIError – when server reports error
- reload(**kwargs) None¶
Refresh this object’s data from the service.
- Keyword Arguments:
compatible (bool) – Use Docker compatibility endpoint
- remove(**kwargs) None[source]¶
Delete container.
- Keyword Arguments:
v (bool) – Delete associated volumes as well.
link (bool) – Ignored.
force (bool) – Kill a running container before deleting.
- rename(name: str) None[source]¶
Rename container.
Container updated in-situ to avoid reload().
- Parameters:
name – New name for container.
- resize(height: int = None, width: int = None) None[source]¶
Resize the tty session.
- Parameters:
height – New height of tty session.
width – New width of tty session.
- restart(**kwargs) None[source]¶
Restart processes in container.
- Keyword Arguments:
timeout (int) – Seconds to wait for container to stop before killing container.
- start(**kwargs) None[source]¶
Start processes in container.
- Keyword Arguments:
detach_keys – Override the key sequence for detaching a container (Podman only)
- stats(**kwargs) bytes | dict[str, Any] | Iterator[bytes] | Iterator[dict[str, Any]][source]¶
Return statistics for container.
- Keyword Arguments:
decode (bool) – If True and stream is True, stream will be decoded into dict’s. Default: False.
stream (bool) – Stream statistics until cancelled. Default: True.
- Raises:
APIError – when service reports an error
- stop(**kwargs) None[source]¶
Stop container.
- Keyword Arguments:
all (bool) – When True, stop all containers. Default: False (Podman only)
ignore (bool) – When True, ignore error if container already stopped (Podman only)
timeout (int) – Number of seconds to wait on container to stop before killing it.
- top(**kwargs) Iterator[dict[str, Any]] | dict[str, Any][source]¶
Report on running processes in the container.
- Keyword Arguments:
ps_args (str) – When given, arguments will be passed to ps
stream (bool) – When True, repeatedly return results. Default: False
- Raises:
NotFound – when the container no longer exists
APIError – when the service reports an error
- update(**kwargs) None[source]¶
Update resource configuration of the containers. :keyword Please refer to Podman API documentation for details: :keyword https: //docs.podman.io/en/latest/_static/api.html#tag/containers/operation/ContainerUpdateLibpod :keyword restart_policy: New restart policy for the container. :kwtype restart_policy: str :keyword restart_retries: New amount of retries for the container’s restart policy.
Only allowed if restartPolicy is set to on-failure
- Keyword Arguments:
tuple (blkio_weight_device) – Block IO weight (relative device weight) in the form: (device_path, weight)
blockio (dict) –
LinuxBlockIO for Linux cgroup ‘blkio’ resource management Example: blockio = {
”leafWeight”: 0 “throttleReadBpsDevice”: [{
”major”: 0, “minor”: 0, “rate”: 0
}], “throttleReadIopsDevice”: [{
”major”: 0, “minor”: 0, “rate”: 0
}], “throttleWriteBpsDevice”: [{
”major”: 0, “minor”: 0, “rate”: 0
}], “throttleWriteIopsDevice”: [{
”major”: 0, “minor”: 0, “rate”: 0
}], “weight”: 0, “weightDevice”: [{
”leafWeight”: 0, “major”: 0, “minor”: 0, “weight”: 0
}],
}
cpu (dict) –
LinuxCPU for Linux cgroup ‘cpu’ resource management Example: cpu = {
”burst”: 0, “cpus”: “string”, “idle”: 0, “mems”: “string”, “period”: 0 “quota”: 0, “realtimePeriod”: 0, “realtimeRuntime”: 0, “shares”: 0
}
device_read_bps (list(dict)) – Limit read rate (bytes per second) from a device, in the form: [{“Path”: “string”, “Rate”: 0}]
device_read_iops (list(dict)) – Limit read rate (IO operations per second) from a device, in the form: [{“Path”: “string”, “Rate”: 0}]
device_write_bps (list(dict)) – Limit write rate (bytes per second) to a device, in the form: [{“Path”: “string”, “Rate”: 0}]
device_write_iops (list(dict)) – Limit write rate (IO operations per second) to a device, in the form: [{“Path”: “string”, “Rate”: 0}]
devices (list(dict)) –
Devices configures the device allowlist. Example: devices = [{
access: “string” allow: 0, major: 0, minor: 0, type: “string”
}]
health_cmd (str) – set a healthcheck command for the container (‘None’ disables the existing healthcheck)
health_interval (str) – set an interval for the healthcheck (a value of disable results in no automatic timer setup)(Changing this setting resets timer.) (default “30s”)
health_log_destination (str) – set the destination of the HealthCheck log. Directory path, local or events_logger (local use container state file)(Warning: Changing this setting may cause the loss of previous logs.) (default “local”)
health_max_log_count (int) – set maximum number of attempts in the HealthCheck log file. (‘0’ value means an infinite number of attempts in the log file) (default 5)
health_max_logs_size (int) – set maximum length in characters of stored HealthCheck log. (‘0’ value means an infinite log length) (default 500)
health_on_failure (str) – action to take once the container turns unhealthy (default “none”)
health_retries (int) – the number of retries allowed before a healthcheck is considered to be unhealthy (default 3)
health_start_period (str) – the initialization time needed for a container to bootstrap (default “0s”)
health_startup_cmd (str) – Set a startup healthcheck command for the container
health_startup_interval (str) – Set an interval for the startup healthcheck. Changing this setting resets the timer, depending on the state of the container. (default “30s”)
health_startup_retries (int) – Set the maximum number of retries before the startup healthcheck will restart the container
health_startup_success (int) – Set the number of consecutive successes before the startup healthcheck is marked as successful and the normal healthcheck begins (0 indicates any success will start the regular healthcheck)
health_startup_timeout (str) – Set the maximum amount of time that the startup healthcheck may take before it is considered failed (default “30s”)
health_timeout (str) – the maximum time allowed to complete the healthcheck before an interval is considered failed (default “30s”)
no_healthcheck (bool) – Disable healthchecks on container
hugepage_limits (list(dict)) –
Hugetlb limits (in bytes). Default to reservation limits if supported. .. admonition:: Example
huugepage_limits = [{“limit”: 0, “pageSize”: “string”}]
memory (dict) –
LinuxMemory for Linux cgroup ‘memory’ resource management Example: memory = {
”checkBeforeUpdate”: True, “disableOOMKiller”: True, “kernel”: 0, “kernelTCP”: 0, “limit”: 0, “reservation”: 0, “swap”: 0, “swappiness”: 0, “useHierarchy”: True,
}
network (dict) –
LinuxNetwork identification and priority configuration Example: network = {
”classID”: 0, “priorities”: {
”name”: “string”, “priority”: 0
}
)
pids (dict) –
LinuxPids for Linux cgroup ‘pids’ resource management (Linux 4.3) .. admonition:: Example
- pids = {
“limit”: 0
}
rdma (dict) –
Rdma resource restriction configuration. Limits are a set of key value pairs that define RDMA resource limits, where the key is device name and value is resource limits. Example: rdma = {
- ”property1”: {
“hcaHandles”: 0 “hcaObjects”: 0
}, “property2”: {
”hcaHandles”: 0 “hcaObjects”: 0
}
unified (dict) –
Unified resources. Example: unified = {
”property1”: “value1”, “property2”: “value2”, …
}
- wait(**kwargs) int[source]¶
Block until the container enters given state.
- Keyword Arguments:
condition (Union[str, list[str]]) – Container state on which to release. One or more of: “configured”, “created”, “running”, “stopped”, “paused”, “exited”, “removing”, “stopping”.
interval (int) – Time interval to wait before polling for completion.
- Returns:
“Error” key has a dictionary value with the key “Message”.
- Raises:
NotFound – when Container not found
ReadTimeoutError – when timeout is exceeded
APIError – when service returns an error
- property id¶
Returns the identifier for the object.
- Type:
str
- property image¶
Returns Image object used to create Container.
- property labels¶
Returns labels associated with container.
- Type:
dict[str, str]
- property name¶
Returns container’s name.
- Type:
str
- property ports¶
Return ports exposed by container.
- Type:
dict[str, int]
- property short_id¶
Returns truncated identifier. ‘sha256’ preserved when included in the id.
No attempt is made to ensure the returned value is semantically meaningful for all resources.
- Type:
str
- property status¶
Literal[“created”, “initialized”, “running”, “stopped”, “exited”, “unknown”]: Returns status of container.