### Port Binding Configuration Examples Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers_create.html Examples of mapping container ports to host ports using various dictionary formats. ```python {'2222/tcp': 3333} ``` ```python {'2222/tcp': None} ``` ```python {'1111/tcp': ('127.0.0.1', 1111)} ``` ```python {'1111/tcp': [1234, ("127.0.0.1", 4567)]} ``` ```python {'9090': 7878, '10932/tcp': '8781', "8989/tcp": ("127.0.0.1", 9091)} ``` ```python {'2222/tcp': {"port": 3333, "range": 4}} ``` ```python {'1111/tcp': {"port": ('127.0.0.1', 1111), "range": 4}} ``` ```python {'1111/tcp': [ {"port": 1234, "range": 4}, {"ip": "127.0.0.1", "port": 4567} ] } ``` -------------------------------- ### Start Container Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Starts processes in a container, supporting optional detach keys. ```python def start(self, **kwargs) -> None: """Start processes in container. Keyword Args: detach_keys: Override the key sequence for detaching a container (Podman only) """ response = self.client.post( f"/containers/{self.id}/start", params={"detachKeys": kwargs.get("detach_keys")} ) response.raise_for_status() ``` -------------------------------- ### POST /pods/{id}/start Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/pods.html Starts the specified pod. ```APIDOC ## POST /pods/{id}/start ### Description Starts the specified pod. ### Method POST ### Endpoint /pods/{id}/start ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the pod. ``` -------------------------------- ### POST /containers/{id}/start Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Starts the processes inside a container. ```APIDOC ## POST /containers/{id}/start ### Description Starts processes in the container. ### Method POST ### Endpoint /containers/{id}/start ### Parameters #### Query Parameters - **detachKeys** (string) - Optional - Override the key sequence for detaching a container. ``` -------------------------------- ### Configure Hugepage Limits Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the hugepage_limits list. ```python huugepage_limits = [{"limit": 0, "pageSize": "string"}] ``` -------------------------------- ### Example Temporary Filesystem Configuration Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers_create.html Shows the dictionary mapping for mounting temporary filesystems with specific options. ```python {'/mnt/vol2': '', '/mnt/vol1': 'size=3G,uid=1000'} ``` -------------------------------- ### Configure container volumes Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_create.html Example dictionary structure for configuring volume mounts with bind paths and modes. ```python { ‘test_bind_1’: {‘bind’: ‘/mnt/vol1’, ‘mode’: ‘rw’}, ’test_bind_2’: {‘bind’: ‘/mnt/vol2’, ‘extended_mode’: [‘ro’, ‘noexec’]}, ’test_bind_3’: {‘bind’: ‘/mnt/vol3’, ‘extended_mode’: [‘noexec’], ‘mode’: ‘rw’} } ``` -------------------------------- ### Configure Secrets Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_create.html Examples of mounting secrets to a container using different formats. ```python [‘my_secret’, ‘my_secret2’] ``` ```python [Secret, Secret] ``` ```python [ { “source”: “my_secret”, # A string representing the ID or name of # a secret ”target”: “/my_secret”, # An optional target to mount source to, # falls back to /run/secrets/source ”uid”: 1000, # An optional UID that falls back to 0 # if not given ”gid”: 1000, # An optional GID that falls back to 0 # if not given ``` -------------------------------- ### Example Secret Environment Configuration Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers_create.html Demonstrates the dictionary structure for defining secret environment variables. ```python {"VARIABLE1": "NameOfSecret", "VARIABLE2": "NameOfAnotherSecret"} ``` -------------------------------- ### Define Container Mounts Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Example of specifying bind and tmpfs mounts using a list of dictionaries. ```python [ { "type": "bind", "source": "/a/b/c1", "target" "/d1", "read_only": True, "relabel": "Z" }, { "type": "tmpfs", # If this was not passed, the regular directory # would be created rather than tmpfs mount !!! # as this will cause to have invalid entry # in /proc/self/mountinfo "source": "tmpfs", "target" "/d2", "size": "100k", "chown": True } ] ``` -------------------------------- ### Configure Device Allowlist Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the devices list used to configure the device allowlist. ```python devices = [{ access: "string" allow: 0, major: 0, minor: 0, type: "string" }] ``` -------------------------------- ### Configure Container Restart Policy Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Example of defining a restart policy dictionary for a container. ```python {"Name": "on-failure", "MaximumRetryCount": 5} ``` -------------------------------- ### Configure Linux Network Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the network dictionary used for identification and priority configuration. ```python network = { "classID": 0, "priorities": { "name": "string", "priority": 0 } ) ``` -------------------------------- ### get(key) Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/networks_manager.html Retrieves detailed information for a specific network. ```APIDOC ## GET /networks/{key} ### Description Returns information for the specified network ID or name. ### Method GET ### Endpoint /networks/{key} ### Parameters #### Path Parameters - **key** (str) - Required - Network name or ID ``` -------------------------------- ### Get Manifest Details Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/manifests.html Retrieves a specific manifest by its name or key. ```python def get(self, key: str) -> Manifest: """Returns the manifest by name. To have Manifest conform with other PodmanResource's, we use the key that retrieved the Manifest be its name. Args: key: Manifest name for which to search Raises: NotFound: when manifest could not be found APIError: when service reports an error """ quoted_key = urllib.parse.quote_plus(key) response = self.client.get(f"/manifests/{quoted_key}/json") response.raise_for_status() body = response.json() if "names" not in body: body["names"] = key return self.prepare_model(attrs=body) ``` -------------------------------- ### Define Container Volume Mappings Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Example dictionary structure for configuring volume mounts, including bind paths, read/write modes, and extended mount options. ```python { 'test_bind_1': {'bind': '/mnt/vol1', 'mode': 'rw'}, 'test_bind_2': { 'bind': '/mnt/vol2', 'extended_mode': ['ro', 'noexec']}, 'test_bind_3': {'bind': '/mnt/vol3', 'extended_mode': ['noexec'], 'mode': 'rw'} } ``` -------------------------------- ### Define Unified Resources Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for defining unified resources as a dictionary. ```python unified = { > ”property1”: “value1”, “property2”: “value2”, … } ``` -------------------------------- ### Configure Container Port Bindings Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Examples of mapping container ports to host ports using various formats including single ports, random assignment, specific interfaces, and port ranges. ```python {‘2222/tcp’: 3333} ``` ```python {‘2222/tcp’: None} ``` ```python {‘1111/tcp’: (‘127.0.0.1’, 1111)} ``` ```python {‘1111/tcp’: [1234, (“127.0.0.1”, 4567)]} ``` ```python {‘9090’: 7878, ‘10932/tcp’: ‘8781’, "8989/tcp": ("127.0.0.1", 9091)} ``` ```python {‘2222/tcp’: {“port”: 3333, “range”: 4}} ``` ```python {‘1111/tcp’: {“port”: (‘127.0.0.1’, 1111), “range”: 4}} ``` ```python {‘1111/tcp’: [ {“port”: 1234, “range”: 4}, {“ip”: “127.0.0.1”, “port”: 4567} ]} ``` -------------------------------- ### GET /containers/{id}/top Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Reports on running processes in the container. ```APIDOC ## GET /containers/{id}/top ### Description Returns a report on running processes in the container. ### Method GET ### Endpoint /containers/{id}/top ### Parameters #### Query Parameters - **ps_args** (string) - Optional - Arguments to be passed to ps. - **stream** (bool) - Optional - When True, repeatedly return results. ``` -------------------------------- ### Configure Linux CPU Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the cpu dictionary used in cgroup resource management. ```python cpu = { "burst": 0, "cpus": "string", "idle": 0, "mems": "string", "period": 0 "quota": 0, "realtimePeriod": 0, "realtimeRuntime": 0, "shares": 0 } ``` -------------------------------- ### Define Optional File Mode Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Example of specifying an octal mode for a target file. ```python "mode": 0o400, # An optional mode to apply to the target, # use an 0o prefix for octal integers }, ``` -------------------------------- ### List Podman Networks Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/networks_manager.html Example usage of the PodmanClient to iterate through and print IDs of available networks. ```python with PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock") as client: for net in client.networks.list(): print(net.id, "\n") ``` -------------------------------- ### Secret Mounting Configuration Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers_create.html Examples of different ways to provide secrets to a container. ```python ['my_secret', 'my_secret2'] ``` ```python [Secret, Secret] ``` ```python [ { "source": "my_secret", # A string representing the ID or name of # a secret "target": "/my_secret", # An optional target to mount source to, # falls back to /run/secrets/source "uid": 1000, # An optional UID that falls back to 0 # if not given } ] ``` -------------------------------- ### Configure Linux Block IO Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the blockio dictionary used in cgroup resource management. ```python 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 }], } ``` -------------------------------- ### Define PID Limits Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Example dictionary for Linux cgroup PID resource management. ```python pids = { "limit": 0 } ``` -------------------------------- ### Define RDMA Resource Restrictions Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Example structure for RDMA resource limits per device. ```python rdma = { "property1": { "hcaHandles": 0 "hcaObjects": 0 }, "property2": { "hcaHandles": 0 "hcaObjects": 0 }, ... } ``` -------------------------------- ### Configure Container Secrets Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Examples of mounting secrets using lists of strings, Secret objects, or detailed configuration dictionaries. ```python ['my_secret', 'my_secret2'] ``` ```python [Secret, Secret] ``` ```python [ { "source": "my_secret", "target": "/my_secret", "uid": 1000, "gid": 1000 } ``` -------------------------------- ### GET /manifests/{key}/json Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/manifests.html Retrieves the details of a specific manifest list. ```APIDOC ## GET /manifests/{key}/json ### Description Returns the manifest list details by name. ### Method GET ### Endpoint /manifests/{key}/json ### Parameters #### Path Parameters - **key** (string) - Required - The name of the manifest list to retrieve. ``` -------------------------------- ### Configure Linux Pids Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the pids dictionary used in cgroup resource management. ```python pids = { "limit": 0 } ``` -------------------------------- ### Configure Linux Memory Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers.html Example structure for the memory dictionary used in cgroup resource management. ```python memory = { "checkBeforeUpdate": True, "disableOOMKiller": True, "kernel": 0, "kernelTCP": 0, "limit": 0, "reservation": 0, "swap": 0, "swappiness": 0, "useHierarchy": True, } ``` -------------------------------- ### get(key: str, **kwargs) -> Container Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Retrieves a specific container by its name or ID. ```APIDOC ## get(key: str, **kwargs) ### Description Get a container object by its name or ID. ### Parameters - **key** (str) - Required - Container name or id. ### Keyword Arguments - **compatible** (bool) - Optional - Use Docker compatibility endpoint. ### Returns - **Container** - A Container object corresponding to the key. ### Errors - **NotFound** - Raised when the container does not exist. - **APIError** - Raised when an error is returned by the service. ``` -------------------------------- ### GET /manifests/{key}/exists Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/manifests.html Checks if a manifest list exists by its name or key. ```APIDOC ## GET /manifests/{key}/exists ### Description Checks if a manifest list exists in the Podman service. ### Method GET ### Endpoint /manifests/{key}/exists ### Parameters #### Path Parameters - **key** (string) - Required - The name or identifier of the manifest list. ``` -------------------------------- ### Initialize PodmanClient with SSH Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/client.html Demonstrates how to instantiate the client using an SSH connection string and an identity file. ```python with PodmanClient(base_url="ssh://root@api.example:22/run/podman/podman.sock?secure=True", identity="~alice/.ssh/api_ed25519") ``` -------------------------------- ### GET /containers/stats Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Retrieves statistics for a container. ```APIDOC ## GET /containers/stats ### Description Returns statistics for a container, optionally streaming the results. ### Method GET ### Endpoint /containers/stats ### Parameters #### Query Parameters - **containers** (string) - Required - The ID of the container. - **stream** (bool) - Optional - Stream statistics until cancelled. ``` -------------------------------- ### GET /containers/{id}/json Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Inspect a container. ```APIDOC ## GET /containers/{id}/json ### Description Returns detailed information about the container. ### Method GET ### Endpoint /containers/{id}/json ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container. ``` -------------------------------- ### PodmanClient.__init__ Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/client.html Initializes a new PodmanClient instance to connect to a Podman service. ```APIDOC ## PodmanClient(base_url, version, timeout, user_agent, credstore_env, use_ssh_client, max_pool_size, connection, identity) ### Description Initializes the PodmanClient to establish a connection to the Podman service. The client supports multiple connection types including Unix sockets, TCP, and SSH. ### Parameters - **base_url** (str) - Optional - Full URL to Podman service (e.g., http+unix://, http+ssh://, tcp://). - **version** (str) - Optional - API version to use. Default: auto. - **timeout** (int) - Optional - Timeout for API calls in seconds. - **user_agent** (str) - Optional - User agent for service connections. - **credstore_env** (Mapping[str, str]) - Optional - Environment variables for credential store. - **use_ssh_client** (bool) - Optional - Whether to use system SSH client for SSH connections. - **max_pool_size** (int) - Optional - Number of connections to save in pool. - **connection** (str) - Optional - Identifier of connection from containers.conf. - **identity** (str) - Optional - SSH key path for authentication. ``` -------------------------------- ### GET /volumes/json Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/volumes.html Lists all volumes managed by the service. ```APIDOC ## GET /volumes/json ### Description Retrieves a list of all volumes, optionally filtered by driver, label, or name. ### Method GET ### Endpoint /volumes/json ### Parameters #### Query Parameters - **filters** (dict) - Optional - Criteria to filter the volume list (driver, label, name) ``` -------------------------------- ### POST /containers/{id}/init Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Initialize a container. ```APIDOC ## POST /containers/{id}/init ### Description Initializes the specified container. ### Method POST ### Endpoint /containers/{id}/init ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container. ``` -------------------------------- ### GET /containers/{id}/logs Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Retrieve logs from a container. ```APIDOC ## GET /containers/{id}/logs ### Description Fetches logs from the specified container. ### Method GET ### Endpoint /containers/{id}/logs ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container. #### Query Parameters - **follow** (bool) - Optional - Follow log output. - **since** (int) - Optional - Show logs since a given timestamp. - **stderr** (bool) - Optional - Include stderr. - **stdout** (bool) - Optional - Include stdout. - **tail** (string/int) - Optional - Number of lines to show. - **timestamps** (bool) - Optional - Show timestamps. - **until** (int) - Optional - Show logs until a given timestamp. ``` -------------------------------- ### get(name: str) Source: https://podman-py.readthedocs.io/en/latest/podman.domain.images_manager.html Retrieves an image by name or ID. ```APIDOC ## get(name: str) ### Description Returns an image by name or id. ### Parameters - **name** (str) - Required - Image id or name for which to search. ``` -------------------------------- ### Create a Manifest Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/manifests.html Creates a new manifest list with the specified images and configuration. ```python def create( self, name: str, images: Optional[list[Union[Image, str]]] = None, all: Optional[bool] = None, # pylint: disable=redefined-builtin ) -> Manifest: """Create a Manifest. Args: name: Name of manifest list. images: Images or Image identifiers to be included in the manifest. all: When True, add all contents from images given. Raises: ValueError: when no names are provided NotFoundImage: when a given image does not exist """ params: dict[str, Any] = {} if images is not None: params["images"] = [] for item in images: # avoid redefinition of the loop variable, then ensure it's an image img_item = item if isinstance(img_item, Image): img_item = img_item.attrs["RepoTags"][0] params["images"].append(img_item) if all is not None: params["all"] = all name_quoted = urllib.parse.quote_plus(name) response = self.client.post(f"/manifests/{name_quoted}", params=params) response.raise_for_status(not_found=ImageNotFound) body = response.json() manifest = self.get(body["Id"]) manifest.attrs["names"] = name if manifest.attrs["manifests"] is None: manifest.attrs["manifests"] = [] return manifest ``` -------------------------------- ### Configure Image Build Parameters Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images_build.html Maps container limits, host configurations, and labels to build parameters, ensuring a default Dockerfile is generated if none is provided. ```python if "container_limits" in kwargs: params["cpuperiod"] = kwargs["container_limits"].get("cpuperiod") params["cpuquota"] = kwargs["container_limits"].get("cpuquota") params["cpusetcpus"] = kwargs["container_limits"].get("cpusetcpus") params["cpushares"] = kwargs["container_limits"].get("cpushares") params["memory"] = kwargs["container_limits"].get("memory") params["memswap"] = kwargs["container_limits"].get("memswap") if "extra_hosts" in kwargs: params["extrahosts"] = json.dumps(kwargs.get("extra_hosts")) if "labels" in kwargs: params["labels"] = json.dumps(kwargs.get("labels")) if params["dockerfile"] is None: params["dockerfile"] = f".containerfile.{random.getrandbits(160):x}" # Remove any unset parameters return dict(filter(lambda i: i[1] is not None, params.items())) ``` -------------------------------- ### GET /networks/json Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/networks_manager.html List all networks available in the Podman service. ```APIDOC ## GET /networks/json ### Description Returns a list of network objects. ### Method GET ### Endpoint /networks/json ### Query Parameters - **filters** (dict) - Optional - Criteria for filtering the network list. ``` -------------------------------- ### Initialize PodmanClient from environment Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/client.html Initializes a new PodmanClient instance using environment variables like CONTAINER_HOST or DOCKER_HOST. ```python environment = environment or os.environ credstore_env = credstore_env or {} if version == "auto": version = None kwargs = { 'version': version, 'timeout': timeout, 'tls': False, 'credstore_env': credstore_env, 'max_pool_size': max_pool_size, } host = environment.get("CONTAINER_HOST") or environment.get("DOCKER_HOST") or None if host is not None: kwargs['base_url'] = host return PodmanClient(**kwargs) ``` -------------------------------- ### GET /images/{id}/get Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images.html Returns the image as a tarball. ```APIDOC ## GET /images/{id}/get ### Description Returns Image as tarball. Format is set to docker-archive. ### Method GET ### Endpoint /images/{id}/get ### Parameters #### Path Parameters - **id** (string) - Required - The ID or tag of the image. #### Query Parameters - **format** (string) - Required - Set to 'docker-archive'. ``` -------------------------------- ### Get Registry Data Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images_manager.html Fetches registry-related metadata for a specific image. ```python def get_registry_data( self, name: str, auth_config=Mapping[str, str], # pylint: disable=unused-argument ) -> RegistryData: """Returns registry data for an image. Provided for compatibility Args: name: Image name auth_config: Override configured credentials. Keys username and password are required. Raises: APIError: when service returns an error """ # FIXME populate attrs using auth_config image = self.get(name) return RegistryData( image_name=name, attrs=image.attrs, client=self.client, collection=self, ) ``` -------------------------------- ### from_env(version='auto', timeout=None, max_pool_size=None, ssl_version=None, assert_hostname=False, environment=None, credstore_env=None, use_ssh_client=True) Source: https://podman-py.readthedocs.io/en/latest/podman.client.html Returns a connection to the Podman service using environment variables and provided parameters. ```APIDOC ## from_env ### Description Returns a client instance used to communicate with a Podman service based on environment variables and configuration parameters. ### Parameters - **version** (str) - Optional - API version to use. Default: 'auto'. - **timeout** (int | None) - Optional - Timeout for API calls in seconds. - **max_pool_size** (int | None) - Optional - Number of connections to save in the pool. - **ssl_version** (int | None) - Optional - Ignored. - **assert_hostname** (bool) - Optional - Ignored. - **environment** (dict[str, str] | None) - Optional - Dictionary containing input environment. Default: os.environ. - **credstore_env** (dict[str, str] | None) - Optional - Dictionary containing environment for credential store. - **use_ssh_client** (bool) - Optional - Use system ssh client. Default: True. ### Returns - **PodmanClient** - Client used to communicate with a Podman service. ### Raises - **ValueError** - Raised when a required environment variable is not set. ``` -------------------------------- ### GET /images/{id}/history Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images.html Retrieves the history of the specified image. ```APIDOC ## GET /images/{id}/history ### Description Returns the history of the Image. ### Method GET ### Endpoint /images/{id}/history ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the image. ``` -------------------------------- ### create(image, command=None, **kwargs) Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Creates a new container using the specified image and optional configuration parameters. ```APIDOC ## create(image, command=None, **kwargs) ### Description Creates a new container. Returns a Container object. ### Parameters - **image** (Image | str) - Required - Image to run. - **command** (str | list[str]) - Optional - Command to run in the container. ### Keyword Arguments - **auto_remove** (bool) - Optional - Enable auto-removal of the container on daemon side when the container’s process exits. - **blkio_weight_device** (dict[str, Any]) - Optional - Block IO weight (relative device weight). - **blkio_weight** (int) - Optional - Block IO weight (relative weight), accepts a weight value between 10 and 1000. - **cap_add** (list[str]) - Optional - Add kernel capabilities. - **cap_drop** (list[str]) - Optional - Drop kernel capabilities. - **cgroup_parent** (str) - Optional - Override the default parent cgroup. - **cpu_count** (int) - Optional - Number of usable CPUs (Windows only). - **cpu_percent** (int) - Optional - Usable percentage of the available CPUs (Windows only). - **cpu_period** (int) - Optional - The length of a CPU period in microseconds. - **cpu_quota** (int) - Optional - Microseconds of CPU time that the container can get in a CPU period. - **cpu_rt_period** (int) - Optional - Limit CPU real-time period in microseconds. - **cpu_rt_runtime** (int) - Optional - Limit CPU real-time runtime in microseconds. - **cpu_shares** (int) - Optional - CPU shares (relative weight). - **cpuset_cpus** (str) - Optional - CPUs in which to allow execution. - **cpuset_mems** (str) - Optional - Memory nodes (MEMs) in which to allow execution. - **detach** (bool) - Optional - Run container in the background and return a Container object. - **device_cgroup_rules** (list[str]) - Optional - A list of cgroup rules to apply to the container. - **devices** (list[str]) - Optional - Expose host devices to the container. ``` -------------------------------- ### PodmanClient.from_env Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/client.html Creates a PodmanClient instance using environment variables and provided parameters. ```APIDOC ## PodmanClient.from_env(version, timeout, max_pool_size, environment, credstore_env, use_ssh_client) ### Description Returns a connection to the Podman service by reading configuration from environment variables (e.g., DOCKER_HOST, CONTAINER_HOST) and overriding with provided parameters. ### Parameters - **version** (str) - Optional - API version to use. Default: auto. - **timeout** (int) - Optional - Timeout for API calls in seconds. - **max_pool_size** (int) - Optional - Number of connections to save in pool. - **environment** (dict) - Optional - Input environment dictionary. Default: os.environ. - **credstore_env** (dict) - Optional - Environment variables for credential store. - **use_ssh_client** (bool) - Optional - Use system ssh client. Default: True. ``` -------------------------------- ### Get Container Statistics Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Retrieves container statistics, optionally streaming the output. ```python def stats( self, **kwargs ) -> Union[bytes, dict[str, Any], Iterator[bytes], Iterator[dict[str, Any]]]: """Return statistics for container. Keyword Args: 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 """ # FIXME Errors in stream are not handled, need content and json to read Errors. stream = kwargs.get("stream", True) decode = kwargs.get("decode", False) params = { "containers": self.id, "stream": stream, } response = self.client.get("/containers/stats", params=params, stream=stream) response.raise_for_status() if stream: return api.stream_helper(response, decode_to_json=decode) return json.loads(response.content) if decode else response.content ``` -------------------------------- ### GET /containers/{id}/archive Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Retrieve a tar archive of a resource from the container. ```APIDOC ## GET /containers/{id}/archive ### Description Retrieves a tar archive of a file or folder from the specified container. ### Method GET ### Endpoint /containers/{id}/archive ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container. #### Query Parameters - **path** (string) - Required - The path to the file or directory to archive. ``` -------------------------------- ### Get Image Details Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images_manager.html Retrieves specific image information by name or ID. ```python def get(self, name: str) -> Image: # pylint: disable=arguments-differ,arguments-renamed """Returns an image by name or id. Args: name: Image id or name for which to search Raises: ImageNotFound: when image does not exist APIError: when service returns an error """ name = urllib.parse.quote_plus(name) response = self.client.get(f"/images/{name}/json") response.raise_for_status(not_found=ImageNotFound) return self.prepare_model(response.json()) ``` -------------------------------- ### SystemManager.login() Source: https://podman-py.readthedocs.io/en/latest/podman.domain.system.html Authenticates the user with a container registry. ```APIDOC ## SystemManager.login() ### Description Logs into the Podman service or a specified registry. ### Parameters - **username** (str) - Registry username - **password** (str) - Registry plaintext password - **email** (str) - Registry account email address - **registry** (str) - URL for registry access - **reauth** (bool) - Refresh existing authentication - **dockercfg_path** (str) - Path to custom configuration file - **auth** (str) - Authentication string - **identitytoken** (str) - Identity token for authentication - **registrytoken** (str) - Bearer token for registry - **tls_verify** (bool/str) - Whether to verify TLS certificates ``` -------------------------------- ### create(name, **kwargs) Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/networks_manager.html Creates a new network resource in Podman. ```APIDOC ## POST /networks/create ### Description Creates a new network resource with the specified name and configuration options. ### Method POST ### Endpoint /networks/create ### Parameters #### Request Body - **name** (str) - Required - Name of the network to be created - **driver** (str) - Optional - Network driver to use - **dns_enabled** (bool) - Optional - When True, do not provision DNS - **enable_ipv6** (bool) - Optional - Enable IPv6 on the network - **internal** (bool) - Optional - Restrict external access - **labels** (dict[str, str]) - Optional - Map of labels - **options** (dict[str, Any]) - Optional - Driver options - **ipam** (IPAMConfig) - Optional - Custom IP scheme ``` -------------------------------- ### POST /manifests/{name} Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/manifests.html Creates a new manifest list with the specified name and optional images. ```APIDOC ## POST /manifests/{name} ### Description Creates a new manifest list in the Podman service. ### Method POST ### Endpoint /manifests/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the manifest list to create. #### Query Parameters - **images** (list) - Optional - List of images or image identifiers to include. - **all** (boolean) - Optional - When True, add all contents from the provided images. ``` -------------------------------- ### GET /volumes/{id}/json Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/volumes.html Inspects a specific volume by its ID or name. ```APIDOC ## GET /volumes/{id}/json ### Description Returns the detailed attributes of a specific volume. ### Method GET ### Endpoint /volumes/{id}/json ### Parameters #### Path Parameters - **id** (str) - Required - The ID or name of the volume #### Query Parameters - **tlsVerify** (bool) - Optional - Require TLS verification. Default: True. ``` -------------------------------- ### Get Pod Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/pods_manager.html Retrieves detailed information for a specific pod by its name or ID. ```APIDOC ## GET /pods/{pod_id}/json ### Description Return information for a Pod by name or ID. ### Method GET ### Endpoint /pods/{pod_id}/json ### Path Parameters - **pod_id** (string) - Required - Pod name or ID. ``` -------------------------------- ### Get Pod information Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/pods_manager.html Retrieves details for a specific pod by its name or ID. ```python def get(self, pod_id: str) -> Pod: # pylint: disable=arguments-differ,arguments-renamed """Return information for Pod by name or id. Args: pod_id: Pod name or id. Raises: NotFound: when network does not exist APIError: when error returned by service """ response = self.client.get(f"/pods/{pod_id}/json") response.raise_for_status() return self.prepare_model(attrs=response.json()) ``` -------------------------------- ### System and utility methods Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/client.html Methods for interacting with system-level operations and resource management. ```python @docs def df(self) -> dict[str, Any]: # pylint: disable=missing-function-docstring,invalid-name return self.system.df() df.__doc__ = SystemManager.df.__doc__ @docs def events(self, *args, **kwargs): # pylint: disable=missing-function-docstring return EventsManager(client=self.api).list(*args, **kwargs) events.__doc__ = EventsManager.list.__doc__ @docs def info(self, *args, **kwargs): # pylint: disable=missing-function-docstring return self.system.info(*args, **kwargs) info.__doc__ = SystemManager.info.__doc__ @docs def login(self, *args, **kwargs): # pylint: disable=missing-function-docstring return self.system.login(*args, **kwargs) login.__doc__ = SystemManager.login.__doc__ @docs def ping(self) -> bool: # pylint: disable=missing-function-docstring return self.system.ping() ping.__doc__ = SystemManager.ping.__doc__ @docs def version(self, *args, **kwargs): # pylint: disable=missing-function-docstring _ = args return self.system.version(**kwargs) version.__doc__ = SystemManager.version.__doc__ @docs def close(self): """Release PodmanClient Resources.""" return self.api.close() ``` -------------------------------- ### GET /pods/{id}/top Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/pods.html Reports on running processes in the specified pod. ```APIDOC ## GET /pods/{id}/top ### Description Reports on running processes in the specified pod. ### Method GET ### Endpoint /pods/{id}/top ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the pod. #### Query Parameters - **ps_args** (string) - Optional - Arguments passed to ps. ### Response #### Success Response (200) - **Processes** (list) - List of running processes. - **Titles** (list) - Titles for the process list. ``` -------------------------------- ### ContainersManager.run() Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Runs a new container. ```APIDOC ## ContainersManager.run() ### Description Creates and starts a new container. ### Signature `run(image, command=None, **kwargs)` ``` -------------------------------- ### Get archive from container Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Downloads a specific file or folder from the container's filesystem. ```python def get_archive( self, path: str, chunk_size: int = api.DEFAULT_CHUNK_SIZE ) -> tuple[Iterable, dict[str, Any]]: """Download a file or folder from the container's filesystem. Args: path: Path to file or folder. chunk_size: <= number of bytes to return for each iteration of the generator. ``` -------------------------------- ### Initialize Container Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers.html Initializes a container by sending a POST request to the container's init endpoint. ```python def init(self) -> None: """Initialize the container.""" response = self.client.post(f"/containers/{self.id}/init") response.raise_for_status() ``` -------------------------------- ### BuildMixin.build Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images_build.html Builds a container image from a specified path or file object and returns the resulting image object along with the build logs. ```APIDOC ## BuildMixin.build ### Description Builds an image using the provided configuration. Returns a tuple containing the built Image object and an iterator of build logs. ### Parameters - **path** (str) - Optional - Path to the directory containing the Dockerfile - **fileobj** (object) - Optional - A file object to use as the Dockerfile - **tag** (str) - Optional - A tag to add to the final image - **quiet** (bool) - Optional - Whether to return the status - **nocache** (bool) - Optional - Don’t use the cache when set to True - **rm** (bool) - Optional - Remove intermediate containers. Default True - **timeout** (int) - Optional - HTTP timeout - **buildargs** (Mapping[str,str]) - Optional - A dictionary of build arguments - **container_limits** (dict) - Optional - Limits applied to each container created by the build process (memory, memswap, cpushares, cpusetcpus, cpuperiod, cpuquota) - **labels** (Mapping[str,str]) - Optional - A dictionary of labels to set on the image - **target** (str) - Optional - Name of the build-stage to build in a multi-stage Dockerfile - **platform** (str) - Optional - Platform in the format os[/arch[/variant]] ### Returns - **Image** (podman.domain.images.Image) - The built image - **Iterator[bytes]** - The build logs ``` -------------------------------- ### Create a Pod Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/pods_manager.html Creates a new pod using the provided name and optional keyword arguments. ```python def create(self, name: str, **kwargs) -> Pod: """Create a Pod. Keyword Args: See (API documentation)[ https://docs.podman.io/en/latest/_static/api.html#operation/CreatePod] for complete list of keywords. """ data = {} if kwargs is None else kwargs.copy() data["name"] = name response = self.client.post("/pods/create", data=json.dumps(data)) response.raise_for_status() body = response.json() return self.get(body["Id"]) ``` -------------------------------- ### Configure Restart Policy and Resource Limits Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers_create.html Sets restart policy parameters and PID limits from the input arguments. ```python if "restart_policy" in args: params["restart_policy"] = args["restart_policy"].get("Name") params["restart_tries"] = args["restart_policy"].get("MaximumRetryCount") args.pop("restart_policy") params["resource_limits"]["pids"] = {"limit": args.pop("pids_limit", None)} ``` -------------------------------- ### run(image, command=None, **kwargs) Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Runs a container from a specified image. ```APIDOC ## run(image, command=None, **kwargs) ### Description Run a container. By default, this method waits for the container to finish and returns its logs. If detach=True, it returns a Container object instead. ### Parameters - **image** (str | Image) - Required - Image to run. - **command** (str | list[str]) - Optional - Command to run in the container. - **stdout** (bool) - Optional - Include stdout. Default: True. - **stderr** (bool) - Optional - Include stderr. Default: False. - **remove** (bool) - Optional - Delete container on the client side when processes exit. Default: False. ``` -------------------------------- ### Container Creation Implementation Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/containers_create.html The internal method implementation for preparing the payload and executing the POST request to the Podman API. ```python if isinstance(image, Image): image = image.id if isinstance(command, str): command = [command] payload = {"image": image, "command": command} payload.update(kwargs) payload = self._render_payload(payload) payload = api.prepare_body(payload) response = self.client.post( "/containers/create", headers={"content-type": "application/json"}, data=payload, ) response.raise_for_status(not_found=ImageNotFound) ``` -------------------------------- ### Build Image Execution Logic Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/images_build.html Handles the creation of build context from paths or file objects and processes the resulting build stream. ```python body = None path = None if kwargs.get("custom_context"): if "fileobj" not in kwargs: raise PodmanError( "Custom context requires fileobj to be set to a binary file-like object " "containing a build-directory tarball." ) if "dockerfile" not in kwargs: # TODO: Scan the tarball for either a Dockerfile or a Containerfile. # This could be slow if the tarball is large, # and could require buffering/copying the tarball if `fileobj` is not seekable. # As a workaround for now, don't support omitting the filename. raise PodmanError( "Custom context requires specifying the name of the Dockerfile " "(typically 'Dockerfile' or 'Containerfile')." ) body = kwargs["fileobj"] elif "fileobj" in kwargs: path = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with filename = pathlib.Path(path.name) / params["dockerfile"] with open(filename, "w", encoding='utf-8') as file: shutil.copyfileobj(kwargs["fileobj"], file) body = api.create_tar(anchor=path.name, gzip=kwargs.get("gzip", False)) elif "path" in kwargs: filename = pathlib.Path(kwargs["path"]) / params["dockerfile"] # The Dockerfile will be copied into the context_dir if needed params["dockerfile"] = api.prepare_containerfile(kwargs["path"], str(filename)) excludes = api.prepare_containerignore(kwargs["path"]) body = api.create_tar( anchor=kwargs["path"], exclude=excludes, gzip=kwargs.get("gzip", False) ) post_kwargs = {} if kwargs.get("timeout"): post_kwargs["timeout"] = float(kwargs.get("timeout")) response = self.client.post( "/build", params=params, data=body, headers={ "Content-type": "application/x-tar", # "X-Registry-Config": "TODO", }, stream=True, **post_kwargs, ) if hasattr(body, "close"): body.close() if hasattr(path, "cleanup"): path.cleanup() response.raise_for_status(not_found=ImageNotFound) image_id = unknown = None marker = re.compile(r"(^[0-9a-f]+)\n$") report_stream, stream = itertools.tee(response.iter_lines()) for line in stream: result = json.loads(line) if "error" in result: raise BuildError(result["error"], report_stream) if "stream" in result: match = marker.match(result["stream"]) if match: image_id = match.group(1) unknown = line if image_id: return self.get(image_id), report_stream raise BuildError(unknown or "Unknown", report_stream) ``` -------------------------------- ### SystemManager.login Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/system.html Authenticates the user with the Podman service. ```APIDOC ## POST /auth ### Description Logs into the Podman service using registry credentials. ### Method POST ### Endpoint /auth ### Request Body - **username** (string) - Required - Registry username - **password** (string) - Optional - Registry plaintext password - **email** (string) - Optional - Registry account email address - **serveraddress** (string) - Optional - URL for registry access - **auth** (string) - Optional - Authentication token - **identitytoken** (string) - Optional - Identity token for registry access - **registrytoken** (string) - Optional - Bearer token for registry access ### Response #### Success Response (200) - **response** (dict) - Authentication result. ``` -------------------------------- ### Retrieve a Network Resource Source: https://podman-py.readthedocs.io/en/latest/_modules/podman/domain/networks.html Demonstrates how to access a specific network by name using the Podman client. ```python with PodmanClient(base_url="unix:///run/user/1000/podman/podman.sock") as client: net = client.networks.get("db_network") print(net.name, "\n") ``` -------------------------------- ### ContainersManager.create() Source: https://podman-py.readthedocs.io/en/latest/podman.domain.containers_manager.html Creates a new container instance. ```APIDOC ## ContainersManager.create() ### Description Creates a new container using the specified configuration. ### Signature `create(*args, **kwargs)` ```