-
Notifications
You must be signed in to change notification settings - Fork 128
Implement client.quadlets.install #633
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,9 @@ | |
|
|
||
| import builtins | ||
| import logging | ||
| from typing import Optional, Union | ||
| import os | ||
| import pathlib | ||
| from typing import Any, Optional, Union | ||
|
|
||
| import requests | ||
|
|
||
|
|
@@ -223,3 +225,118 @@ def delete( | |
|
|
||
| response.raise_for_status() | ||
| return response.json()["Removed"] | ||
|
|
||
| def install( | ||
| self, | ||
| files: Union[ | ||
| "QuadletFileItem", | ||
| builtins.list["QuadletFileItem"], | ||
| ], | ||
| *, | ||
| replace: bool = False, | ||
| reload_systemd: bool = True, | ||
| ) -> dict[str, Any]: | ||
| """Install a Quadlet file and additional asset files. | ||
|
|
||
| The function will make a single request. Each request must contain exactly | ||
| one quadlet file (identified by its extension: .container, .volume, | ||
| .network, ... etc.) and may optionally include asset files such as | ||
| Containerfiles, kube YAML, or other configuration files. | ||
|
|
||
| Quadlets and asset files can be provided as a tuple (filename, content) | ||
| or a string/path that represents a file path. Both can be combined in a | ||
| list to be included as part of the same request. | ||
|
|
||
| The path to a single ``.tar`` file can also be provided; it will be posted | ||
| directly with ``Content-Type: application/x-tar``. In all other cases the | ||
| items are uploaded as ``multipart/form-data``. | ||
|
|
||
| Args: | ||
| files (Union[QuadletFileItem, list[QuadletFileItem]]): File(s) to install. | ||
| QuadletFileItem is a Union[tuple[str, str], str, os.PathLike]. | ||
| replace (bool): Replace existing files if they already exist. | ||
| Defaults to False. | ||
| reload_systemd (bool): Reload systemd after installing quadlets. | ||
| Defaults to True. | ||
|
|
||
| Returns: | ||
| A dict with keys: | ||
| - ``InstalledQuadlets``: mapping of source path to installed | ||
| path for successfully installed files. | ||
| - ``QuadletErrors``: mapping of source path to error message | ||
| for failed installations (empty on success). | ||
|
|
||
| Raises: | ||
| APIError: when the service reports an error (e.g. no quadlet files | ||
| found, multiple quadlet files, file already exists without | ||
| replace, or other server errors). | ||
| FileNotFoundError: when a provided file path does not exist on | ||
| disk. | ||
| """ | ||
| if not isinstance(files, builtins.list): | ||
| files = [files] | ||
|
|
||
| params = { | ||
| "replace": replace, | ||
| "reload-systemd": reload_systemd, | ||
| } | ||
|
|
||
| first = files[0] | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What happens if the files are empty?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the function will fail before with TypeError because file is a named arg
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What about |
||
| if len(files) == 1 and isinstance(first, (str, os.PathLike)) and self._is_tar_path(first): | ||
| tar_path = pathlib.Path(first) | ||
| if not tar_path.is_file(): | ||
| raise FileNotFoundError(f"No such file: '{tar_path}'") | ||
| response = self.client.post( | ||
| "/quadlets", | ||
| params=params, | ||
| data=tar_path.read_bytes(), | ||
| headers={"Content-Type": "application/x-tar"}, | ||
| ) | ||
| else: | ||
| multipart = self._prepare_install_body(files) | ||
| response = self.client.post( | ||
| "/quadlets", | ||
| params=params, | ||
| files=multipart, | ||
| ) | ||
|
|
||
| response.raise_for_status() | ||
| return response.json() | ||
|
|
||
| @staticmethod | ||
| def _is_tar_path(item: "QuadletFileItem") -> bool: | ||
| """Return True if *item* looks like a path to a tar archive.""" | ||
| if not isinstance(item, (str, os.PathLike)): | ||
| return False | ||
| name = str(item) | ||
| return name.endswith(".tar") or name.endswith(".tar.gz") | ||
|
|
||
| def _prepare_install_body( | ||
| self, | ||
| items: builtins.list["QuadletFileItem"], | ||
| ) -> dict[str, tuple[str, bytes]]: | ||
| """Build a ``files`` dict for :pymethod:`requests.Session.request`. | ||
|
|
||
| Returns a dictionary of ``{field_name: (filename, file_bytes)}`` | ||
| suitable for passing as the ``files`` keyword argument to | ||
| :pymethod:`requests.Session.request`, which encodes them as | ||
| ``multipart/form-data``. | ||
| """ | ||
| result: dict[str, tuple[str, bytes]] = {} | ||
| for item in items: | ||
| if isinstance(item, tuple): | ||
| filename, content = item | ||
| if isinstance(content, bytes): | ||
| result[filename] = (filename, content) | ||
| else: | ||
| result[filename] = (filename, content.encode("utf-8")) | ||
| elif isinstance(item, (str, os.PathLike)): | ||
| fp = pathlib.Path(item) | ||
| if not fp.is_file(): | ||
| raise FileNotFoundError(f"No such file: '{fp}'") | ||
| result[fp.name] = (fp.name, fp.read_bytes()) | ||
| return result | ||
|
|
||
|
|
||
| # Type alias – importable for type annotations in calling code. | ||
| QuadletFileItem = Union[tuple[str, Union[str, bytes]], str, os.PathLike] | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What if it is tupple?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if tuple, it will move through this check and it will be processed inside
_prepare_install_body, which will check for tuple or pathlike and process thefilesarg