Skip to content

Commit

Permalink
Introduce sphinx processing for html API web site
Browse files Browse the repository at this point in the history
* Add docs target to Makefile
* Started updating some docstrings
* Added support for connections from containers.conf
* Ported more uses of XDG_* envvar to xdg package
* Downgrade modules in requirements.txt as needed by RHEL/Fedora
  packaging.

Signed-off-by: Jhon Honce <[email protected]>
  • Loading branch information
jwhonce committed May 5, 2021
1 parent cd6d151 commit 003423b
Show file tree
Hide file tree
Showing 17 changed files with 131 additions and 83 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# podman-py [![Build Status](https://api.cirrus-ci.com/github/containers/podman-py.svg)](https://cirrus-ci.com/github/containers/podman-py/master)
# podman-py
[![Build Status](https://api.cirrus-ci.com/github/containers/podman-py.svg)](https://cirrus-ci.com/github/containers/podman-py/master)
[![Bors enabled](https://bors.tech/images/badge_small.svg)](https://app.bors.tech/repositories/23171)

This python package is a library of bindings to use the RESTful API for [Podman](https://github.com/containers/podman).
This python package is a library of bindings to use the RESTful API of [Podman](https://github.com/containers/podman).
It is currently under development and contributors are welcome!


Expand Down
23 changes: 20 additions & 3 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import os
import sys

from sphinx.domains.python import PythonDomain

sys.path.insert(0, os.path.abspath('../../..'))


Expand Down Expand Up @@ -48,7 +50,8 @@
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# html_theme = 'alabaster'
html_theme = 'default'
html_theme_options = {
'description': 'A Python library for the Podman service API',
'fixed_sidebar': True,
Expand All @@ -68,7 +71,7 @@
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = False
napoleon_use_admonition_for_examples = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = True
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
Expand All @@ -79,11 +82,25 @@
napoleon_attr_annotations = True


class PatchedPythonDomain(PythonDomain):
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
if 'refspecific' in node:
del node['refspecific']
return super(PatchedPythonDomain, self).resolve_xref(
env, fromdocname, builder, typ, target, node, contnode
)


def skip(app, what, name, obj, would_skip, options):
if name in ("ApiConnection", "DockerClient"):
# isort: unique-list
cls = ['ApiConnection', 'DockerClient', 'DockerException']

if name in cls:
return True

return None


def setup(app):
app.connect("autodoc-skip-member", skip)
app.add_domain(PatchedPythonDomain, override=True)
16 changes: 12 additions & 4 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@

Welcome to PodmanPy's documentation!
.. image:: https://github.com/containers/podman/blob/master/logo/podman-logo.png?raw=true

What is PodmanPy?
====================================

PodmanPy is a Python3 module that allows you to write Python scripts that access resources
maintained by a Podman service.

PodmanPy leverages the Podman service RESTful API. Connections via http+ssh://, http+unix:// or
tcp:// are supported.

.. automodule:: podman
:members:
:inherited-members:

.. toctree::
:maxdepth: 2
:caption: Contents:

:maxdepth: 2
:caption: Contents:

modules

Indices and tables
==================
Expand Down
6 changes: 6 additions & 0 deletions podman/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,17 @@ def _api_version(release: str, significant: int = 3) -> str:
VERSION: str = _api_version(version.__version__)
COMPATIBLE_VERSION: str = _api_version(version.__compatible_version__, 2)

try:
from typing_extensions import Literal
except ModuleNotFoundError:
from typing import Literal

# isort: unique-list
__all__ = [
'APIClient',
'COMPATIBLE_VERSION',
'DEFAULT_CHUNK_SIZE',
'Literal',
'VERSION',
'cached_property',
'create_tar',
Expand Down
8 changes: 4 additions & 4 deletions podman/api/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,13 +219,13 @@ class SSHPoolManager(urllib3.PoolManager):
)

# Map supported schemes to Pool Classes
pool_classes_by_scheme = {
_pool_classes_by_scheme = {
"http": SSHConnectionPool,
"http+ssh": SSHConnectionPool,
}

# Map supported schemes to Pool Key index generator
key_fn_by_scheme = {
_key_fn_by_scheme = {
"http": functools.partial(_key_normalizer, _PoolKey),
"http+ssh": functools.partial(_key_normalizer, _PoolKey),
}
Expand All @@ -238,8 +238,8 @@ def __init__(self, num_pools=10, headers=None, **kwargs):
headers: Additional headers to add to operations.
"""
super().__init__(num_pools, headers, **kwargs)
self.pool_classes_by_scheme = SSHPoolManager.pool_classes_by_scheme
self.key_fn_by_scheme = SSHPoolManager.key_fn_by_scheme
self.pool_classes_by_scheme = SSHPoolManager._pool_classes_by_scheme
self.key_fn_by_scheme = SSHPoolManager._key_fn_by_scheme


class SSHAdapter(HTTPAdapter):
Expand Down
10 changes: 5 additions & 5 deletions podman/api/uds.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,13 @@ class UDSPoolManager(urllib3.PoolManager):
)

# Map supported schemes to Pool Classes
pool_classes_by_scheme = {
_pool_classes_by_scheme = {
"http": UDSConnectionPool,
"http+ssh": UDSConnectionPool,
}

# Map supported schemes to Pool Key index generator
key_fn_by_scheme = {
_key_fn_by_scheme = {
"http": functools.partial(_key_normalizer, _PoolKey),
"http+ssh": functools.partial(_key_normalizer, _PoolKey),
}
Expand All @@ -124,8 +124,8 @@ def __init__(self, num_pools=10, headers=None, **kwargs):
headers: Additional headers to add to operations.
"""
super().__init__(num_pools, headers, **kwargs)
self.pool_classes_by_scheme = UDSPoolManager.pool_classes_by_scheme
self.key_fn_by_scheme = UDSPoolManager.key_fn_by_scheme
self.pool_classes_by_scheme = UDSPoolManager._pool_classes_by_scheme
self.key_fn_by_scheme = UDSPoolManager._key_fn_by_scheme


class UDSAdapter(HTTPAdapter):
Expand All @@ -151,7 +151,7 @@ def __init__(
pool_maxsize: The maximum number of connections to save in the pool.
Keyword Args:
timeout (float):
timeout (float): Time in seconds to wait for response
Examples:
requests.Session.mount(
Expand Down
18 changes: 10 additions & 8 deletions podman/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,17 @@


class PodmanClient(AbstractContextManager):
"""Create client to Podman service.
"""Client to connect to a Podman service.
Examples:
with PodmanClient("ssh://[email protected]:22/run/podman/podman.sock?secure=True",
identity="~alice/.ssh/api_ed25519"
)
"""

def __init__(self, *args, **kwargs) -> None:
"""Instantiate PodmanClient object
"""Initialize PodmanClient.
Keyword Args:
base_url (str): Full URL to Podman service. See examples.
Expand Down Expand Up @@ -95,22 +96,23 @@ def from_env(
"""Returns connection to service using environment variables and parameters.
Environment variables:
DOCKER_HOST, CONTAINER_HOST: URL to Podman service
DOCKER_TLS_VERIFY, CONTAINER_TLS_VERIFY: Verify host against CA certificate
DOCKER_CERT_PATH, CONTAINER_CERT_PATH: Path to TLS certificates for host connection
- DOCKER_HOST, CONTAINER_HOST: URL to Podman service
- DOCKER_TLS_VERIFY, CONTAINER_TLS_VERIFY: Verify host against CA certificate
- DOCKER_CERT_PATH, CONTAINER_CERT_PATH: Path to TLS certificates for host connection
Args:
version: API version to use. Default: auto, use version from server
timeout: Timeout for API calls, in seconds.
max_pool_size: Number of connections to save in pool.
ssl_version: Ignored. SSH configuration delegated to SSH client configuration.
ssl_version: SSH configuration delegated to SSH client configuration. Ignored.
assert_hostname: Ignored.
environment: Dict containing input environment. Default: os.environ
credstore_env: Dict containing environment for credential store
use_ssh_client: Use system ssh client rather than ssh module. Always, True.
Returns:
PodmanClient: used to communicate with Podman service
Client used to communicate with a Podman service.
"""
environment = environment or os.environ
credstore_env = credstore_env or dict()
Expand Down Expand Up @@ -220,4 +222,4 @@ def swarm(self):

# Aliases to minimize effort to port to PodmanPy
DockerClient = PodmanClient
from_env = PodmanClient.from_env #: :meta hide-value:
from_env = PodmanClient.from_env
16 changes: 8 additions & 8 deletions podman/domain/containers_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ def create(
For example,
/dev/sda:/dev/xvda:rwm allows the container to have read-write access to the
host's /dev/sda via a node named /dev/xvda inside the container.
dns (List[str]): Set custom DNS servers.
dns_opt (List[str]): Additional options to be added to the container's resolv.conf file.
dns_search (List[str]): DNS search domains.
Expand Down Expand Up @@ -123,7 +124,7 @@ def create(
pids_limit (int): Tune a container's pids limit. Set -1 for unlimited.
platform (str): Platform in the format os[/arch[/variant]]. Only used if the method
needs to pull the requested image.
ports (Dict[str, Union[int, Tuple[str, int], List[int]): Ports to bind inside
ports (Dict[str, Union[int, Tuple[str, int], List[int]]]): Ports to bind inside
the container.
The keys of the dictionary are the ports to bind inside the container, either as an
Expand All @@ -135,13 +136,12 @@ def create(
- The port number, as an integer. For example,
{'2222/tcp': 3333} will expose port 2222 inside the container as port 3333 on the
host.
- None, to assign a random host port. For example,
{'2222/tcp': None}.
host.
- None, to assign a random host port. For example, {'2222/tcp': None}.
- A tuple of (address, port) if you want to specify the host interface. For example,
{'1111/tcp': ('127.0.0.1', 1111)}.
- A list of integers, if you want to bind multiple host ports to a single container
port. For example, {'1111/tcp': [1234, 4567]}.
port. For example, {'1111/tcp': [1234, 4567]}.
privileged (bool): Give extended privileges to this container.
publish_all_ports (bool): Publish all ports to the host.
Expand All @@ -153,7 +153,7 @@ def create(
- Name: One of on-failure, or always.
- MaximumRetryCount: Number of times to restart the container on failure.
For example:
For example,
{"Name": "on-failure", "MaximumRetryCount": 5}
runtime (str): Runtime to use with this container.
Expand All @@ -172,7 +172,7 @@ def create(
tmpfs (Dict[str, str]): Temporary filesystems to mount, as a dictionary mapping a
path inside the container to options for that path.
For example:
For example,
{
'/mnt/vol2': '',
Expand All @@ -194,7 +194,7 @@ def create(
volume_driver (str): The name of a volume driver/plugin.
volumes (Dict[str, Dict[str, str]]): A dictionary to configure volumes mounted inside
the container. The key is either the host path or a volume name, and the value is
a dictionary with the keys:
a dictionary with the keys:
- bind The path to mount the volume inside the container
- mode Either rw to mount the volume read/write, or ro to mount it read-only.
Expand Down
9 changes: 4 additions & 5 deletions podman/domain/images_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def remove(
image: Union[Image, str],
force: Optional[bool] = None,
noprune: bool = False, # pylint: disable=unused-argument
) -> List[Dict[str, Union[str, int]]]:
) -> List[Dict[api.Literal["Deleted", "Untagged", "Errors", "ExitCode"], Union[str, int]]]:
"""Delete image from Podman service.
Args:
Expand All @@ -327,14 +327,11 @@ def remove(
noprune: Ignored.
Returns:
List[Dict[Literal["Deleted", "Untagged", "Errors", "ExitCode"], Union[str, int]]]
Dictionaries of the images deleted and untagged.
Raises:
ImageNotFound: when image does not exist
APIError: when service returns an error
Notes:
The dictionaries with keys Errors and ExitCode are added.
"""
if isinstance(image, Image):
image = image.id
Expand All @@ -359,9 +356,11 @@ def search(self, term: str, **kwargs) -> List[Dict[str, Any]]:
Keyword Args:
filters (Mapping[str, List[str]): Refine results of search. Available filters:
- is-automated (bool): Image build is automated.
- is-official (bool): Image build is owned by product provider.
- stars (int): Image has at least this number of stars.
noTrunc (bool): Do not truncate any result string. Default: True.
limit (int): Maximum number of results.
Expand Down
3 changes: 3 additions & 0 deletions podman/domain/manifests.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ def create(
body = response.json()
manifest = self.get(body["Id"])
manifest.attrs["names"] = names

if manifest.attrs["manifests"] is None:
manifest.attrs["manifests"] = list()
return manifest

def exists(self, key: str) -> bool:
Expand Down
23 changes: 14 additions & 9 deletions podman/domain/networks_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,25 +135,29 @@ def list(self, **kwargs) -> List[Network]:
Keyword Args:
names (List[str]): List of names to filter by.
ids (List[str]): List of ids to filter by.
filters (Mapping[str,str]): Criteria for listing networks.
Available filters:
ids (List[str]): List of identifiers to filter by.
filters (Mapping[str,str]): Criteria for listing networks. Available filters:
- driver="bridge": Matches a network's driver. Only "bridge" is supported.
- label=(Union[str, List[str]]): format either "key", "key=value"
or a list of such.
or a list of such.
- type=(str): Filters networks by type, legal values are:
- "custom"
- "builtin"
- plugin=(List[str]]): Matches CNI plugins included in a network,
legal values are (Podman only):
- plugin=(List[str]]): Matches CNI plugins included in a network, legal
values are (Podman only):
- bridge
- portmap
- firewall
- tuning
- dnsname
- macvlan
greedy (bool): Fetch more details for each network individually.
You might want this to get the containers attached to them. (ignored)
You might want this to get the containers attached to them. Ignored.
Raises:
APIError: when error returned by service
Expand All @@ -173,13 +177,14 @@ def list(self, **kwargs) -> List[Network]:

return [self.prepare_model(i) for i in response.json()]

def prune(self, filters: Optional[Dict[str, Any]] = None, **kwargs) -> Dict[str, Any]:
def prune(
self, filters: Optional[Dict[str, Any]] = None, **kwargs
) -> Dict[api.Literal["NetworksDeleted", "SpaceReclaimed"], Any]:
"""Delete unused Networks.
Args:
filters: Criteria for selecting volumes to delete. Ignored.
Keyword Args:
compatible (bool): Should compatible API be used. Default: True
Expand Down
Loading

0 comments on commit 003423b

Please sign in to comment.