示例#1
0
    def search(self, term: str, **kwargs) -> List[Dict[str, Any]]:
        """Search Images on registries.

        Args:
            term: Used to target Image results.

        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.

        Raises:
            APIError: when service returns an error
        """
        params = {
            "filters": api.prepare_filters(kwargs.get("filters")),
            "limit": kwargs.get("limit"),
            "noTrunc": True,
            "term": [term],
        }

        response = self.client.get("/images/search", params=params)
        body = response.json()

        if response.status_code == requests.codes.ok:
            return body
        raise APIError(body["cause"], response=response, explanation=body["message"])
示例#2
0
    def list(self, *_, **kwargs) -> List[Volume]:
        """Report on volumes.

        Keyword Args:
            filters (Dict[str, str]): criteria to filter Volume list
                - driver (str): filter volumes by their driver
                - label (Dict[str, str]): filter by label and/or value
                - name (str): filter by volume's name
        """
        filters = api.prepare_filters(kwargs.get("filters"))
        response = self.client.get("/volumes", params={"filters": filters})

        if response.status_code == requests.codes.not_found:
            return []

        data = response.json()
        if response.status_code != requests.codes.okay:
            raise APIError(data["cause"],
                           response=response,
                           explanation=data["message"])

        volumes: List[Volume] = list()
        for item in data:
            volumes.append(self.prepare_model(item))
        return volumes
示例#3
0
    def list(self, **kwargs) -> List[Image]:
        """Report on images.

        Keyword Args:
            name (str) – Only show images belonging to the repository name
            all (bool) – Show intermediate image layers. By default, these are filtered out.
            filters (Mapping[str, Union[str, List[str]]) – Filters to be used on the image list.
                Available filters:
                - dangling (bool)
                - label (Union[str, List[str]]): format either "key", "key=value"

        Raises:
            APIError: when service returns an error.
        """
        params = {
            "all": kwargs.get("all"),
            "name": kwargs.get("name"),
            "filters": api.prepare_filters(kwargs.get("filters")),
        }
        response = self.client.get("/images/json", params=params)
        body = response.json()

        if response.status_code == requests.codes.not_found:
            return []

        if response.status_code != requests.codes.ok:
            raise APIError(body["cause"], response=response, explanation=body["message"])

        images: List[Image] = []
        for element in body:
            images.append(self.prepare_model(attrs=element))
        return images
    def prune(self, filters: Mapping[str, str] = None) -> Dict[str, Any]:
        """Delete stopped containers.

        Args:
            filters: Criteria for determining containers to remove. Available keys are:
                - until (str): Delete containers before this time
                - label (List[str]): Labels associated with containers

        Returns:
            Keys:
                - ContainersDeleted (List[str]): Identifiers of deleted containers.
                - SpaceReclaimed (int): Amount of disk space reclaimed in bytes.

        Raises:
            APIError: when service reports an error
        """
        params = {"filters": api.prepare_filters(filters)}
        response = self.client.post("/containers/prune", params=params)
        response.raise_for_status()

        results = {"ContainersDeleted": [], "SpaceReclaimed": 0}
        for entry in response.json():
            if entry.get("error") is not None:
                raise APIError(entry["error"],
                               response=response,
                               explanation=entry["error"])

            results["ContainersDeleted"].append(entry["Id"])
            results["SpaceReclaimed"] += entry["Size"]
        return results
示例#5
0
    def list(
        self,
        since: Union[datetime, int, None] = None,
        until: Union[datetime, int, None] = None,
        filters: Optional[Dict[str, Any]] = None,
        decode: bool = False,
    ) -> Iterator[Union[str, Dict[str, Any]]]:
        """Report on networks.

        Args:
            decode: When True, decode stream into dict's. Default: False
            filters: Criteria for including events.
            since: Get events newer than this time.
            until: Get events older than this time.

        Yields:
            When decode is True, Iterator[Dict[str, Any]]

            When decode is False, Iterator[str]
        """
        params = {
            "filters": api.prepare_filters(filters),
            "since": api.prepare_timestamp(since),
            "stream": True,
            "until": api.prepare_timestamp(until),
        }
        response = self.client.get("/events", params=params, stream=True)
        response.raise_for_status()

        for item in response.iter_lines():
            if decode:
                yield json.loads(item)
            else:
                yield item
示例#6
0
    def prune(self,
              filters: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
        """Delete unused Pods.

        Returns:
            Dictionary Keys:
                - PodsDeleted (List[str]): List of pod ids deleted.
                - SpaceReclaimed (int): Always zero.

        Raises:
            APIError: when service reports error
        """
        response = self.client.post(
            "/pods/prune", params={"filters": api.prepare_filters(filters)})
        response.raise_for_status()

        deleted: List[str] = list()
        for item in response.json():
            if item["Err"] is not None:
                raise APIError(
                    item["Err"],
                    response=response,
                    explanation=f"""Failed to prune network '{item["Id"]}'""",
                )
            deleted.append(item["Id"])
        return {"PodsDeleted": deleted, "SpaceReclaimed": 0}
示例#7
0
    def list(self, **kwargs) -> List[Pod]:
        """Report on pods.

        Keyword Args:
            filters (Mapping[str, str]): Criteria for listing pods. Available filters:
                - ctr-ids (List[str]): List of container ids to filter by.
                - ctr-names (List[str]): List of container names to filter by.
                - ctr-number (List[int]): list pods with given number of containers.
                - ctr-status (List[str]): List pods with containers in given state.
                    Legal values are: "created", "running", "paused",
                    "stopped", "exited", "unknown"
                - id (str) - List pod with this id.
                - name (str) - List pod with this name.
                - status (List[str]): List pods in given state. Legal values are: "created",
                    "running", "paused", "stopped", "exited", "unknown"
                - label (List[str]): List pods with given labels.
                - network (List[str]): List pods associated with given Network Ids (not Names).

        Raises:
            APIError: when an error returned by service
        """
        params = {"filters": api.prepare_filters(kwargs.get("filters"))}
        response = self.client.get("/pods/json", params=params)
        response.raise_for_status()
        return [self.prepare_model(attrs=i) for i in response.json()]
示例#8
0
    def list(self, **kwargs) -> List[Pod]:
        """Report on pods.

        Keyword Args:
            filters (Mapping[str, str]): Criteria for listing pods. Available filters:
                - ctr-ids (List[str]): List of container ids to filter by.
                - ctr-names (List[str]): List of container names to filter by.
                - ctr-number (List[int]): list pods with given number of containers.
                - ctr-status (List[str]): List pods with containers in given state.
                    Legal values are: "created", "running", "paused",
                    "stopped", "exited", "unknown"
                - id (str) - List pod with this id.
                - name (str) - List pod with this name.
                - status (List[str]): List pods in given state. Legal values are: "created",
                    "running", "paused", "stopped", "exited", "unknown"
                - label (List[str]): List pods with given labels.
                - network (List[str]): List pods associated with given Network Ids (not Names).

        Raises:
            APIError: Error returned by service.
        """
        params = {"filters": api.prepare_filters(kwargs.get("filters"))}
        response = self.client.get("/pods/json", params=params)
        body = response.json()

        if response.status_code != requests.codes.okay:
            raise APIError(body["cause"],
                           response=response,
                           explanation=body["message"])

        pods: List[Pod] = list()
        for item in body:
            pods.append(self.prepare_model(attrs=item))
        return pods
示例#9
0
    def list(self, **kwargs) -> List[Image]:
        """Report on images.

        Keyword Args:
            name (str) – Only show images belonging to the repository name
            all (bool) – Show intermediate image layers. By default, these are filtered out.
            filters (Mapping[str, Union[str, List[str]]) – Filters to be used on the image list.
                Available filters:

                - dangling (bool)
                - label (Union[str, List[str]]): format either "key" or "key=value"

        Raises:
            APIError: when service returns an error
        """
        params = {
            "all": kwargs.get("all"),
            "name": kwargs.get("name"),
            "filters": api.prepare_filters(kwargs.get("filters")),
        }
        response = self.client.get("/images/json", params=params)
        if response.status_code == requests.codes.not_found:
            return []
        response.raise_for_status()

        return [self.prepare_model(attrs=i) for i in response.json()]
示例#10
0
    def list(self, **kwargs) -> List[Container]:
        """Report on containers.

        Keyword Args:
            all: If False, only show running containers. Default: False.
            since: Show containers created after container name or id given.
            before: Show containers created before container name or id given.
            limit: Show last N created containers.
            filters: Filter container reported.
                Available filters:

                - exited (int): Only containers with specified exit code
                - status (str): One of restarting, running, paused, exited
                - label (Union[str, List[str]]): Format either "key", "key=value" or a list of such.
                - id (str): The id of the container.
                - name (str): The name of the container.
                - ancestor (str): Filter by container ancestor. Format of
                    <image-name>[:tag], <image-id>, or <image@digest>.
                - before (str): Only containers created before a particular container.
                    Give the container name or id.
                - since (str): Only containers created after a particular container.
                    Give container name or id.
            sparse: Ignored
            ignore_removed: If True, ignore failures due to missing containers.

        Raises:
            APIError: If service returns an error.
        """
        params = {
            "all": kwargs.get("all"),
            "filters": kwargs.get("filters", dict()),
            "limit": kwargs.get("limit"),
        }
        if "before" in kwargs:
            params["filters"]["before"] = kwargs.get("before")
        if "since" in kwargs:
            params["filters"]["since"] = kwargs.get("since")

        # filters formatted last because some kwargs may need to be mapped into filters
        params["filters"] = api.prepare_filters(params["filters"])

        response = self.client.get("/containers/json", params=params)
        body = response.json()

        if response.status_code != requests.codes.okay:
            raise APIError(body["cause"],
                           response=response,
                           explanation=body["message"])

        containers: List[Container] = list()
        for item in body:
            containers.append(self.prepare_model(attrs=item))
        return containers
示例#11
0
    def list(self, **kwargs) -> List[Network]:
        """Report on networks.

        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:
                - 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.
                - 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):
                        - 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)

        Raises:
            APIError: Error returned by service.
        """
        compatible = kwargs.get("compatible", True)

        filters = kwargs.get("filters", dict())
        filters["name"] = kwargs.get("names")
        filters["id"] = kwargs.get("ids")
        filters = api.prepare_filters(filters)

        params = {"filters": filters}
        path = f"/networks{'' if compatible else '/json'}"

        response = self.client.get(path, params=params, compatible=compatible)
        body = response.json()

        if response.status_code != requests.codes.okay:
            raise APIError(body["cause"],
                           response=response,
                           explanation=body["message"])

        nets: List[Network] = list()
        for item in body:
            nets.append(self.prepare_model(item))
        return nets
示例#12
0
    def list(self, **kwargs) -> List[Network]:
        """Report on networks.

        Keyword Args:
            names (List[str]): List of names to filter by.
            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.
                - 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):

                        - 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.

        Raises:
            APIError: when error returned by service
        """
        compatible = kwargs.get("compatible", True)

        filters = kwargs.get("filters", {})
        filters["name"] = kwargs.get("names")
        filters["id"] = kwargs.get("ids")
        filters = api.prepare_filters(filters)

        params = {"filters": filters}
        path = f"/networks{'' if compatible else '/json'}"

        response = self.client.get(path, params=params, compatible=compatible)
        response.raise_for_status()

        return [self.prepare_model(i) for i in response.json()]
示例#13
0
    def prune(self, filters: Optional[Mapping[str, Any]] = None) -> Dict[str, Any]:
        """Delete unused images.

        Args:
            filters: Qualify Images to prune. Available filters:
                - dangling (bool): when true, only delete unused and untagged images.
                - until (str): Delete images older than this timestamp.

        Raises:
            APIError: when service returns an error.

        Note:
            The Untagged key will always be "".
        """
        response = self.client.post(
            "/images/prune", params={"filters": api.prepare_filters(filters)}
        )
        body = response.json()

        if response.status_code != requests.codes.ok:
            raise APIError(body["cause"], response=response, explanation=body["message"])

        deleted: List[Dict[str, str]] = []
        error: List[str] = []
        reclaimed: int = 0
        for element in response.json():
            if "Err" in element and element["Err"] is not None:
                error.append(element["Err"])
            else:
                reclaimed += element["Size"]
                deleted.append(
                    {
                        "Deleted": element["Id"],
                        "Untagged": "",
                    }
                )
        if len(error) > 0:
            raise APIError(response.url, response=response, explanation="; ".join(error))

        # body -> Dict[Literal["ImagesDeleted", "SpaceReclaimed"],
        #   List[Dict[Literal["Deleted", "Untagged"], str]
        return {
            "ImagesDeleted": deleted,
            "SpaceReclaimed": reclaimed,
        }
示例#14
0
    def list(self, *_, **kwargs) -> List[Volume]:
        """Report on volumes.

        Keyword Args:
            filters (Dict[str, str]): criteria to filter Volume list
                - driver (str): filter volumes by their driver
                - label (Dict[str, str]): filter by label and/or value
                - name (str): filter by volume's name
        """
        filters = api.prepare_filters(kwargs.get("filters"))
        response = self.client.get("/volumes/json",
                                   params={"filters": filters})

        if response.status_code == requests.codes.not_found:
            return []
        response.raise_for_status()

        return [self.prepare_model(i) for i in response.json()]
示例#15
0
    def prune(self,
              filters: Optional[Dict[str, Any]] = None,
              **kwargs) -> Dict[str, Any]:
        """Delete unused Networks.

        Args:
            filters: Criteria for selecting volumes to delete. Ignored.


        Keyword Args:
            compatible (bool): Should compatible API be used. Default: True

        Raises:
            APIError when service reports error

        Notes:
            SpaceReclaimed always reported as 0
        """
        compatible = kwargs.get("compatible", True)

        response = self.client.post("/networks/prune",
                                    filters=api.prepare_filters(filters),
                                    compatible=compatible)
        body = response.json()

        if response.status_code != requests.codes.okay:
            raise APIError(body["cause"],
                           response=response,
                           explanation=body["message"])

        if compatible:
            return body

        deleted = list()
        for item in body:
            if item["Error"] is not None:
                raise APIError(
                    item["Error"],
                    response=response,
                    explanation=f"""Failed to prune network '{item["Name"]}'""",
                )
            deleted.append(item["Name"])

        return {"NetworksDeleted": deleted, "SpaceReclaimed": 0}
示例#16
0
    def list(
        self,
        since: Union[datetime, int, None] = None,
        until: Union[datetime, int, None] = None,
        filters: Optional[Dict[str, Any]] = None,
        decode: bool = False,
    ):
        """Report on networks.

        Args:
            decode: When True, decode stream into dict's. Default: False
            filters: Criteria for including events.
            since: Get events newer than this time.
            until: Get events older than this time.

        Yields:
            When decode is True, Iterator[Dict[str, Any]]
            When decode is False, Iterator[str]
        """
        params = {
            "filters": api.prepare_filters(filters),
            "since": api.prepare_timestamp(since),
            "stream": True,
            "until": api.prepare_timestamp(until),
        }
        response = self.client.get("/events", params=params, stream=True)
        if response.status_code != requests.codes.okay:
            body = response.json()
            raise APIError(body["cause"],
                           response=response,
                           explanation=body["message"])

        for item in response.iter_lines():
            if decode:
                yield json.loads(item)
            else:
                yield item