Podman API: Difference between revisions

From EDURange
Jump to navigationJump to search
Created page with "<nowiki>##</nowiki> Configuration <nowiki>###</nowiki> Config Configuration class that loads settings from environment variables. - MAX_WORKERS: Thread pool size (default: 10) - DEBUG: Enable debug mode (default: False) - REQUEST_TIMEOUT: Operation timeout in seconds (default: 30) <nowiki>##</nowiki> Custom Exceptions <nowiki>**</nowiki>PodmanAPIError(message, status_code=500)** Custom exception for API errors with HTTP status codes. <nowiki>##</nowiki> Decorato..."
 
No edit summary
Line 1: Line 1:
<nowiki>##</nowiki> Configuration
<span id="configuration"></span>
== Configuration ==


<nowiki>###</nowiki> Config
<span id="config"></span>
=== Config ===


Configuration class that loads settings from environment variables.
Configuration class that loads settings from environment variables. - MAX_WORKERS: Thread pool size (default: 10) - DEBUG: Enable debug mode (default: False) - REQUEST_TIMEOUT: Operation timeout in seconds (default: 30)


- MAX_WORKERS: Thread pool size (default: 10)
<span id="custom-exceptions"></span>
== Custom Exceptions ==


- DEBUG: Enable debug mode (default: False)
'''PodmanAPIError(message, status_code=500)''' Custom exception for API errors with HTTP status codes.


- REQUEST_TIMEOUT: Operation timeout in seconds (default: 30)
<span id="decorators"></span>
== Decorators ==


<nowiki>##</nowiki> Custom Exceptions
'''@handle_errors''' Decorator that catches exceptions and converts them to PodmanAPIError: - Catches asyncio.TimeoutError → 408 Timeout - Catches “not found” errors → 404 Not Found - Catches other exceptions → 500 Internal Server Error


<nowiki>**</nowiki>PodmanAPIError(message, status_code=500)**
'''@validate_json(required_fields=None)''' Decorator that validates JSON request data: - Ensures request contains valid JSON - Checks for required fields - Returns 400 Bad Request if validation fails


Custom exception for API errors with HTTP status codes.
<span id="core-api-class"></span>
=== Core API Class ===


<nowiki>##</nowiki> Decorators
**PodmanAPI.__init__()** Initializes the API with a thread pool executor.


<nowiki>**</nowiki>@handle_errors**
'''PodmanAPI._get_client()''' Returns a new Podman client instance.


Decorator that catches exceptions and converts them to PodmanAPIError:
'''PodmanAPI._run_async(func, timeout=30)''' Executes a function asynchronously in the thread pool with timeout.


- Catches asyncio.TimeoutError → 408 Timeout
'''PodmanAPI._handle_exec_result(result)''' Helper that normalizes exec_run results to (exit_code, output_string).


- Catches "not found" errors → 404 Not Found
<span id="container-management"></span>
== Container Management ==


- Catches other exceptions → 500 Internal Server Error
'''create_container(config)''' Creates and starts a new container. - Input: {image, name, command?, environment?, ports?, volumes?, user?} - Returns: {id, name, status}


<nowiki>**</nowiki>@validate_json(required_fields=None)**
'''start_container(name)''' Starts an existing container. - Input: Container name - Returns: {name, status}


Decorator that validates JSON request data:
'''stop_container(name)''' Stops a running container. - Input: Container name - Returns: {name, status}


- Ensures request contains valid JSON
'''remove_container(name, force=False)''' Removes a container. - Input: Container name, force flag - Returns: {name, removed}


- Checks for required fields
'''list_containers()''' Lists all containers (running and stopped). - Returns: Array of {id, name, status, image}


- Returns 400 Bad Request if validation fails
'''get_container_logs(name, tail=100)''' Retrieves container logs. - Input: Container name, number of lines - Returns: {logs}
 
<nowiki>###</nowiki> Core API Class
 
<nowiki>**</nowiki>PodmanAPI.__init__()**
 
Initializes the API with a thread pool executor.
 
<nowiki>**</nowiki>PodmanAPI._get_client()**
 
Returns a new Podman client instance.
 
<nowiki>**</nowiki>PodmanAPI._run_async(func, timeout=30)**
 
Executes a function asynchronously in the thread pool with timeout.
 
<nowiki>**</nowiki>PodmanAPI._handle_exec_result(result)**
 
Helper that normalizes exec_run results to (exit_code, output_string).
 
<nowiki>##</nowiki> Container Management
 
<nowiki>**</nowiki>create_container(config)**
 
Creates and starts a new container.
 
- Input: {image, name, command?, environment?, ports?, volumes?, user?}
 
- Returns: {id, name, status}
 
<nowiki>**</nowiki>start_container(name)**
 
Starts an existing container.
 
- Input: Container name
 
- Returns: {name, status}
 
<nowiki>**</nowiki>stop_container(name)**
 
Stops a running container.
 
- Input: Container name
 
- Returns: {name, status}
 
<nowiki>**</nowiki>remove_container(name, force=False)**
 
Removes a container.
 
- Input: Container name, force flag
 
- Returns: {name, removed}
 
<nowiki>**</nowiki>list_containers()**
 
Lists all containers (running and stopped).
 
- Returns: Array of {id, name, status, image}
 
<nowiki>**</nowiki>get_container_logs(name, tail=100)**
 
Retrieves container logs.
 
- Input: Container name, number of lines
 
- Returns: {logs}


Host Operations
Host Operations


<nowiki>**</nowiki>add_user(container_name, user_config)**
'''add_user(container_name, user_config)''' Creates a user inside a container. - Input: Container name, {username, password?, shell?} - Returns: {username, created}
 
Creates a user inside a container.
 
- Input: Container name, {username, password?, shell?}
 
- Returns: {username, created}
 
<nowiki>**</nowiki>add_file(container_name, file_config)**
 
Creates a file inside a container.
 
- Input: Container name, {dest_path, content}
 
- Returns: {dest_path, size}
 
<nowiki>**</nowiki>execute_command(container_name, command, user=None)**
 
Executes a command inside a container.
 
- Input: Container name, command string, optional user
 
- Returns: {exit_code, output, success}
 
<nowiki>**</nowiki>shutdown()**
 
Gracefully shuts down the thread pool executor.
 
<nowiki>##</nowiki> Error Handlers
 
<nowiki>**</nowiki>handle_podman_error(error)**
 
Flask error handler for PodmanAPIError exceptions.
 
- Returns structured JSON error response with timestamp
 
<nowiki>**</nowiki>handle_internal_error(error)**
 
Flask error handler for 500 Internal Server Error.
 
- Logs error and returns generic error response
 
<nowiki>##</nowiki> API Routes
 
<nowiki>**</nowiki>POST /api/v1/containers**


Creates a new container. Requires image and name fields.
'''add_file(container_name, file_config)''' Creates a file inside a container. - Input: Container name, {dest_path, content} - Returns: {dest_path, size}


<nowiki>**</nowiki>POST /api/v1/containers/<name>/start**
'''execute_command(container_name, command, user=None)''' Executes a command inside a container. - Input: Container name, command string, optional user - Returns: {exit_code, output, success}


Starts the specified container.
'''shutdown()''' Gracefully shuts down the thread pool executor.


<nowiki>**</nowiki>POST /api/v1/containers/<name>/stop**
<span id="error-handlers"></span>
== Error Handlers ==


Stops the specified container.
'''handle_podman_error(error)''' Flask error handler for PodmanAPIError exceptions. - Returns structured JSON error response with timestamp


<nowiki>**</nowiki>DELETE /api/v1/containers/<name>?force=bool**
'''handle_internal_error(error)''' Flask error handler for 500 Internal Server Error. - Logs error and returns generic error response


Removes the specified container. Optional force parameter.
<span id="api-routes"></span>
== API Routes ==


<nowiki>**</nowiki>GET /api/v1/containers**
'''POST /api/v1/containers''' Creates a new container. Requires image and name fields.


Lists all containers.
'''POST /api/v1/containers/<name>/start''' Starts the specified container.


<nowiki>**</nowiki>GET /api/v1/containers/<name>/logs?tail=int**
'''POST /api/v1/containers/<name>/stop''' Stops the specified container.


Gets container logs. Optional tail parameter (default: 100).
'''DELETE /api/v1/containers/<name>?force=bool''' Removes the specified container. Optional force parameter.


<nowiki>**</nowiki>POST /api/v1/containers/<name>/users**
'''GET /api/v1/containers''' Lists all containers.


Adds a user to the container. Requires username field.
'''GET /api/v1/containers/<name>/logs?tail=int''' Gets container logs. Optional tail parameter (default: 100).


<nowiki>**</nowiki>POST /api/v1/containers/<name>/files**
'''POST /api/v1/containers/<name>/users''' Adds a user to the container. Requires username field.


Adds a file to the container. Requires dest_path and content fields.
'''POST /api/v1/containers/<name>/files''' Adds a file to the container. Requires dest_path and content fields.


<nowiki>**</nowiki>POST /api/v1/containers/<name>/exec**
'''POST /api/v1/containers/<name>/exec''' Executes a command in the container. Requires command field.


Executes a command in the container. Requires command field.
'''GET /api/v1/health''' Health check endpoint. Returns Podman connection status.


<nowiki>**</nowiki>GET /api/v1/health**
'''GET /api/v1/metrics''' Returns API metrics including uptime and thread pool status.


Health check endpoint. Returns Podman connection status.
<span id="signal-handlers"></span>
== Signal Handlers ==


<nowiki>**</nowiki>GET /api/v1/metrics**
'''shutdown_handler(sig, frame)''' Handles SIGINT and SIGTERM signals for graceful shutdown. - Logs signal details including source file and line number - Shuts down thread pool and exits cleanly


Returns API metrics including uptime and thread pool status.
<span id="response-format"></span>
 
== Response Format ==
<nowiki>##</nowiki> Signal Handlers
 
<nowiki>**</nowiki>shutdown_handler(sig, frame)**
 
Handles SIGINT and SIGTERM signals for graceful shutdown.
 
- Logs signal details including source file and line number
 
- Shuts down thread pool and exits cleanly
 
<nowiki>##</nowiki> Response Format


Successful requests will look like this:
Successful requests will look like this:


```
<pre>{
 
  &quot;success&quot;: true,
{
  &quot;container|user|file|execution&quot;: { ... },
 
  &quot;timestamp&quot;: &quot;ISO-8601-timestamp&quot;
  "success": true,
}</pre>
 
  "container|user|file|execution": { ... },
 
  "timestamp": "ISO-8601-timestamp"
 
}
 
```
 
Errors will look like this:
Errors will look like this:


```
<pre>{
 
  &quot;success&quot;: false,
{
  &quot;error&quot;: {
 
    &quot;message&quot;: &quot;Error description&quot;,
  "success": false,
    &quot;code&quot;: 400,
 
    &quot;type&quot;: &quot;ErrorType&quot;
  "error": {
  },
 
  &quot;timestamp&quot;: &quot;ISO-8601-timestamp&quot;
    "message": "Error description",
}</pre>
 
    "code": 400,
 
    "type": "ErrorType"
 
  },
 
  "timestamp": "ISO-8601-timestamp"
 
}
 
```

Revision as of 13:28, 19 July 2025

Configuration

Config

Configuration class that loads settings from environment variables. - MAX_WORKERS: Thread pool size (default: 10) - DEBUG: Enable debug mode (default: False) - REQUEST_TIMEOUT: Operation timeout in seconds (default: 30)

Custom Exceptions

PodmanAPIError(message, status_code=500) Custom exception for API errors with HTTP status codes.

Decorators

@handle_errors Decorator that catches exceptions and converts them to PodmanAPIError: - Catches asyncio.TimeoutError → 408 Timeout - Catches “not found” errors → 404 Not Found - Catches other exceptions → 500 Internal Server Error

@validate_json(required_fields=None) Decorator that validates JSON request data: - Ensures request contains valid JSON - Checks for required fields - Returns 400 Bad Request if validation fails

Core API Class

    • PodmanAPI.__init__()** Initializes the API with a thread pool executor.

PodmanAPI._get_client() Returns a new Podman client instance.

PodmanAPI._run_async(func, timeout=30) Executes a function asynchronously in the thread pool with timeout.

PodmanAPI._handle_exec_result(result) Helper that normalizes exec_run results to (exit_code, output_string).

Container Management

create_container(config) Creates and starts a new container. - Input: {image, name, command?, environment?, ports?, volumes?, user?} - Returns: {id, name, status}

start_container(name) Starts an existing container. - Input: Container name - Returns: {name, status}

stop_container(name) Stops a running container. - Input: Container name - Returns: {name, status}

remove_container(name, force=False) Removes a container. - Input: Container name, force flag - Returns: {name, removed}

list_containers() Lists all containers (running and stopped). - Returns: Array of {id, name, status, image}

get_container_logs(name, tail=100) Retrieves container logs. - Input: Container name, number of lines - Returns: {logs}

Host Operations

add_user(container_name, user_config) Creates a user inside a container. - Input: Container name, {username, password?, shell?} - Returns: {username, created}

add_file(container_name, file_config) Creates a file inside a container. - Input: Container name, {dest_path, content} - Returns: {dest_path, size}

execute_command(container_name, command, user=None) Executes a command inside a container. - Input: Container name, command string, optional user - Returns: {exit_code, output, success}

shutdown() Gracefully shuts down the thread pool executor.

Error Handlers

handle_podman_error(error) Flask error handler for PodmanAPIError exceptions. - Returns structured JSON error response with timestamp

handle_internal_error(error) Flask error handler for 500 Internal Server Error. - Logs error and returns generic error response

API Routes

POST /api/v1/containers Creates a new container. Requires image and name fields.

POST /api/v1/containers/<name>/start Starts the specified container.

POST /api/v1/containers/<name>/stop Stops the specified container.

DELETE /api/v1/containers/<name>?force=bool Removes the specified container. Optional force parameter.

GET /api/v1/containers Lists all containers.

GET /api/v1/containers/<name>/logs?tail=int Gets container logs. Optional tail parameter (default: 100).

POST /api/v1/containers/<name>/users Adds a user to the container. Requires username field.

POST /api/v1/containers/<name>/files Adds a file to the container. Requires dest_path and content fields.

POST /api/v1/containers/<name>/exec Executes a command in the container. Requires command field.

GET /api/v1/health Health check endpoint. Returns Podman connection status.

GET /api/v1/metrics Returns API metrics including uptime and thread pool status.

Signal Handlers

shutdown_handler(sig, frame) Handles SIGINT and SIGTERM signals for graceful shutdown. - Logs signal details including source file and line number - Shuts down thread pool and exits cleanly

Response Format

Successful requests will look like this:

{
  "success": true,
  "container|user|file|execution": { ... },
  "timestamp": "ISO-8601-timestamp"
}

Errors will look like this:

{
  "success": false,
  "error": {
    "message": "Error description",
    "code": 400,
    "type": "ErrorType"
  },
  "timestamp": "ISO-8601-timestamp"
}