### Consume task resource statistics Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/task-monitoring.md Example of initializing a channel and starting the stats emitter to receive and log resource usage. ```go statsCh := make(chan *drivers.TaskResourceUsage, 1) go h.runStatsEmitter(ctx, statsCh, time.Second) select { case stats := <-statsCh: log.Printf("CPU: %.2f%%, Memory: %dMB", stats.ResourceUsage.CpuStats.Percent, stats.ResourceUsage.MemoryStats.Usage / 1024 / 1024) } ``` -------------------------------- ### Start a Podman task Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Initializes and starts a container using the provided task configuration. ```go func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) ``` ```go taskHandle, network, err := driver.StartTask(&drivers.TaskConfig{ ID: "redis-1", Name: "redis", DriverConfig: encodedPodmanConfig, Resources: &drivers.Resources{}, }) ``` -------------------------------- ### ExecStart API Method Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Starts an exec session and returns an output stream. ```go func (c *API) ExecStart(ctx context.Context, execID string) (io.ReadCloser, error) ``` -------------------------------- ### ContainerStart Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Starts a created but stopped container. ```APIDOC ## ContainerStart(ctx context.Context, containerID string) error ### Description Starts a created but stopped container. ### Parameters - **ctx** (context.Context) - Required - Context - **containerID** (string) - Required - Container ID or name ### Returns - **error** - Container not found, already running, start failed ``` -------------------------------- ### Setup Vagrant Environment Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Commands to initialize and access the development virtual machine. ```sh # create the vm vagrant up # ssh into the vm vagrant ssh ``` -------------------------------- ### ExecStart Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Starts an existing exec session and returns the output stream. ```APIDOC ## ExecStart(ctx context.Context, execID string) (io.ReadCloser, error) ### Description Starts the specified exec session and returns a stream for stdout/stderr. ### Parameters - **ctx** (context.Context) - Required - Context - **execID** (string) - Required - Exec session ID ### Returns - **io.ReadCloser** - Output stream (demultiplexed stdout/stderr) - **error** - Exec not found, start failed ``` -------------------------------- ### Start a container Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Starts a container that has been previously created but is currently stopped. ```go func (c *API) ContainerStart(ctx context.Context, containerID string) error ``` -------------------------------- ### StartTask Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Creates and starts a container for the given task configuration. ```APIDOC ## func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) ### Description Creates and starts a container for the given task. It decodes the configuration, resolves the Podman client, pulls the image, and launches monitoring goroutines. ### Parameters - **cfg** (*drivers.TaskConfig) - Required - Task configuration containing driver config, resources, and environment variables. ### Returns - ***drivers.TaskHandle** - Handle for task state serialization. - ***drivers.DriverNetwork** - Network configuration including port mappings and IP allocation. - **error** - Returns error if container creation or startup fails. ``` -------------------------------- ### Configure Command Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Sets the command to execute when the container starts. ```hcl config { command = "some-command" } ``` -------------------------------- ### CPU Shares Proportionality Example Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/resource-limits.md Illustrates how CPU shares are distributed between competing tasks. ```hcl # Task A: 500 MHz, Task B: 1000 MHz # If both competing for CPU: # Task A gets ~1/3, Task B gets ~2/3 of available CPU ``` -------------------------------- ### Execute Tests Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Starts the Podman socket and runs the test suite using gotestsum. ```sh # Start the Podman server systemctl --user start podman.socket # Run the tests CI=1 ./build/bin/gotestsum --junitfile ./build/test/result.xml -- -timeout=15m . ./api ``` -------------------------------- ### Define Image References Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Examples of full registry paths and short names resolved via shortnames.conf. ```text docker.io/library/redis:latest ``` ```text redis:latest # Resolves to docker.io/library/redis:latest myregistry.io/myapp:v1 # Uses full registry ``` -------------------------------- ### Get Default Client Configuration Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Factory function that returns platform-appropriate defaults for the client configuration. ```go func DefaultClientConfig() ClientConfig ``` -------------------------------- ### Create a container Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Creates a container from a specification without starting it. Requires a valid SpecGenerator. ```go func (c *API) ContainerCreate(ctx context.Context, spec *SpecGenerator) (string, error) ``` -------------------------------- ### Rootless Container Setup Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/security-namespaces.md Configures the Podman plugin and job to run in rootless mode using a user-specific socket. ```hcl plugin "nomad-driver-podman" { config { socket_path = "unix:///run/user/1000/podman/podman.sock" } } # In job config { image = "app:latest" userns = "keep-id" # Keep container UID as host UID cap_drop = ["ALL"] } ``` -------------------------------- ### Configure Memory Limits Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/resource-limits.md Examples of memory reservation and swap settings using accepted units like b, k, m, and g. ```hcl memory_reservation = "100m" # 100 megabytes memory_swap = "1g" # 1 gigabyte memory_reservation = "512000k" # 512000 kilobytes ``` -------------------------------- ### ContainerCreate Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Creates a container from a specification without starting it. ```APIDOC ## ContainerCreate(ctx context.Context, spec *SpecGenerator) (string, error) ### Description Creates a container from a specification but does not start it. ### Parameters - **ctx** (context.Context) - Required - Context with timeout - **spec** (*SpecGenerator) - Required - Container specification ### Returns - **string** - Container ID (64-character hex string) - **error** - Image not found, invalid config, disk full, API error ``` -------------------------------- ### CPU Hard Limit Enforcement Example Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/resource-limits.md Combines resource allocation with strict hard limit enforcement. ```hcl resources { cpu = 1000 # 1 CPU hard limit } config { cpu_hard_limit = true # Enforce strictly } ``` -------------------------------- ### Configure Multi-Architecture Image Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Example of constraining a job to a specific architecture and specifying image platform details. ```hcl job "app" { group "service" { constraint { attribute = "${attr.cpu.arch}" value = "amd64" } task "api" { driver = "podman" config { image = "myapp:latest" os = "linux" arch = "amd64" } } } } ``` -------------------------------- ### Configure Development Registry Access Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Development setup using a local registry with force pull enabled and TLS verification disabled. ```hcl config { image = "localhost:5000/myapp:dev" force_pull = true # Always get latest auth { tls_verify = false # Local registry } } ``` -------------------------------- ### Building the Driver from Source Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Steps to clone the repository and build the driver binary using the provided Makefile. ```shell-session git clone git@github.com:hashicorp/nomad-driver-podman cd nomad-driver-podman make dev ``` -------------------------------- ### Initialize API Client Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Constructor for creating a new API client instance with the provided logger and configuration. ```go func NewClient(logger hclog.Logger, config ClientConfig) *API ``` -------------------------------- ### SystemInfo Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Returns detailed system and Podman configuration information. ```APIDOC ## SystemInfo(ctx context.Context) (*SystemInfo, error) ### Description Retrieves host, storage, and runtime information from the Podman service. ### Parameters - **ctx** (context.Context) - Required - Context ### Returns - ***SystemInfo** - Host info, storage, and runtime details - **error** - API error ``` -------------------------------- ### SystemInfo API Method Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Retrieves host, storage, and runtime information from Podman. ```go func (c *API) SystemInfo(ctx context.Context) (*SystemInfo, error) ``` ```go type SystemInfo struct { Host struct { CGroupsVersion string CgroupManager string Security struct { Rootless bool AppArmorEnabled bool SELinuxEnabled bool SECCOMPEnabled bool DefaultCapabilities string } OCIRuntime *struct { Path string } RemoteSocket *struct { Path string } } Plugins struct { Log []string // Log drivers VolumePlugins []string } } ``` -------------------------------- ### Configure Force Pull Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Forces the container to pull the latest image on every start. ```hcl config { force_pull = true } ``` -------------------------------- ### Initialize Podman API Client Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Creates a new API client instance using the provided logger and configuration settings. ```go func NewClient(logger hclog.Logger, config ClientConfig) *API ``` ```go config := api.ClientConfig{ SocketPath: "unix:///run/podman/podman.sock", HttpTimeout: 60 * time.Second, DefaultPodman: true, } client := api.NewClient(logger, config) ``` -------------------------------- ### Verify crun Version Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Ensure a compatible version of the crun OCI runtime is installed. ```console $ crun -V crun version 0.13.227-d38b commit: d38b8c28fc50a14978a27fa6afc69a55bfdd2c11 spec: 1.0.0 +SYSTEMD +SELINUX +APPARMOR +CAP +SECCOMP +EBPF +YAJL ``` -------------------------------- ### Configure Entrypoint and Command Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/configuration.md Overrides default container execution parameters. ```hcl config { entrypoint = ["/bin/bash", "-c"] command = "echo hello" args = ["arg1", "arg2"] working_dir = "/app" } ``` -------------------------------- ### Configure Driver Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Initializes the driver with configuration parsed from the Nomad plugin block. ```go cfg := &base.Config{ PluginConfig: encodedPluginConfig, AgentConfig: &base.AgentConfig{}, } err := driver.SetConfig(cfg) ``` -------------------------------- ### Handle Custom API Errors Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Example of using errors.Is to check for specific container error types. ```go if errors.Is(err, api.ContainerNotFound) { // Container was deleted } ``` -------------------------------- ### Perform image pull with credentials Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/registry-auth.md Demonstrates how to pass authentication options and TLS verification settings to the podman client during task startup. ```go authOpts := &api.ImagePullOptions{ Auth: credentials, // *DockerAuthConfig SkipTLS: !tls_verify, } err := podmanClient.ImagePull(ctx, image, authOpts) ``` -------------------------------- ### Implement Container Exit Monitoring Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/task-monitoring.md Demonstrates spawning the exit watcher and handling the result from the channel. ```go exitCh := make(chan *drivers.ExitResult, 1) go h.runExitWatcher(ctx, exitCh) result := <-exitCh log.Printf("Container exited with code %d", result.ExitCode) ``` -------------------------------- ### Query Journald Logs Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/logging.md Example command to filter journald logs by container name and output as JSON. ```bash journalctl CONTAINER_NAME=app-12345 --output=json | jq '.' ``` -------------------------------- ### Run Nomad Dev Agent with Podman Plugin Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Builds the plugin, configures the Nomad agent, and executes a sample job. ```sh # Build the task driver plugin make dev # Copy the build nomad-driver-plugin executable to examples/plugins/ cp ./build/nomad-driver-podman examples/plugins/ # Start Nomad nomad agent -config=examples/nomad/server.hcl 2>&1 > server.log & # Run the client as sudo sudo nomad agent -config=examples/nomad/client.hcl 2>&1 > client.log & # Run a job nomad job run examples/jobs/redis_ports.nomad # Verify nomad job status redis sudo podman ps ``` -------------------------------- ### Nomad Driver Log Format Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/logging.md Example of the JSON structure used for logs stored by the Nomad driver. ```json { "type": "log", "log": "2024-01-15T10:30:45.123Z stdout: Application started", "timestamp": "2024-01-15T10:30:45.123456789Z" } ``` -------------------------------- ### Configure Plugin-Level Volume Settings Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Enable volume support and set default SELinux labeling behavior for the Podman driver. ```hcl plugin "nomad-driver-podman" { config { volumes { enabled = true # Enable/disable volumes selinuxlabel = "z" # SELinux label } } } ``` -------------------------------- ### Configure Entrypoint Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Overrides the default image entrypoint with a custom list of strings. ```hcl config { entrypoint = [ "/bin/bash", "-c" ] } ``` -------------------------------- ### Initialize Podman Driver Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Creates a new instance of the Podman driver using a provided logger. ```go logger := hclog.New(&hclog.LoggerOptions{}) driver := NewPodmanDriver(logger) ``` -------------------------------- ### Configure Stateful Service with Data Volumes Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/README.md Mounts host directories into the container and sets memory resource constraints. ```hcl config { volumes = [ "/data:/var/lib/myapp" ] memory_reservation = "256m" memory_swap = "1024m" } ``` -------------------------------- ### Initialize monitoring goroutines in Go Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/task-monitoring.md Spawns background processes for exit detection, resource emission, log streaming, and state monitoring after container creation. ```go go h.runExitWatcher(ctx, exitChannel) // Exit detection go h.runStatsEmitter(ctx, statsChannel, interval) // Resource usage go h.runLogStreamer(ctx) // Log forwarding go h.runContainerMonitor() // State monitoring ``` -------------------------------- ### TaskHandle methods Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Methods for monitoring container status, resource usage, and lifecycle events. ```go func (h *TaskHandle) taskStatus() *drivers.TaskStatus ``` ```go func (h *TaskHandle) isRunning() bool ``` ```go func (h *TaskHandle) runExitWatcher(ctx context.Context, exitChannel chan *drivers.ExitResult) ``` ```go func (h *TaskHandle) runStatsEmitter(ctx context.Context, statsChannel chan *drivers.TaskResourceUsage, interval time.Duration) ``` ```go func (h *TaskHandle) runLogStreamer(ctx context.Context) ``` ```go func (h *TaskHandle) runContainerMonitor() ``` -------------------------------- ### Define Client Configuration Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Configuration struct for initializing the API client, including socket path and timeout settings. ```go type ClientConfig struct { SocketPath string // Unix socket path HttpTimeout time.Duration // Request timeout DefaultPodman bool // Mark as default client } ``` -------------------------------- ### Local Development Workflow Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Commands to build the driver, configure the Nomad agent, and deploy a test job. ```bash #!/bin/bash # Start Podman socket (Linux) systemctl --user start podman.socket # Or macOS with Podman Desktop: # Just ensure Podman Machine is running # Build driver cd nomad-driver-podman make dev # Copy to plugins directory mkdir -p /etc/nomad/plugins cp ./build/nomad-driver-podman /etc/nomad/plugins/ # Start Nomad agent with plugin nomad agent -config=dev-agent.hcl 2>&1 | tee nomad.log & # Deploy test job nomad job run examples/jobs/redis_ports.nomad # Watch logs nomad logs redis # Check stats nomad alloc status ``` -------------------------------- ### Create HTTP Client for Unix Sockets Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Initializes an http.Client configured to communicate over a Unix socket, with support for streaming responses. ```go func CreateHttpClient(timeout time.Duration, socketPath string, streaming bool) *http.Client ``` -------------------------------- ### Configure Init Process Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Enables an init process to forward signals and reap zombie processes. ```hcl config { init = true } ``` ```hcl config { init = true init_path = /usr/libexec/podman/catatonit } ``` -------------------------------- ### Initialize Nomad Podman Driver Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/overview.md The factory function serves as the entry point for the Nomad plugin, returning a new driver instance. ```go func factory(log hclog.Logger) interface{} { return NewPodmanDriver(log) } ``` -------------------------------- ### Configure Devices Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Maps host devices into the container with optional permissions. ```hcl config { devices = [ "/dev/net/tun" ] } ``` -------------------------------- ### Configure Credential Helper for Podman Driver Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/registry-auth.md Use an external credential helper like 'pass' to manage registry authentication securely. ```bash # Install credential helper sudo apt-get install pass # Store credential pass insert myregistry.io # Prompted for password # Configure driver cat > /etc/nomad.d/podman.hcl << 'EOF' plugin "nomad-driver-podman" { config { auth { helper = "pass" } } } EOF ``` -------------------------------- ### Configure Custom Network Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/networking.md Attaches the container to a pre-created Podman network. ```hcl config { network_mode = "my-custom-network" } ``` ```bash # Create network once podman network create \ --driver bridge \ --subnet 172.20.0.0/16 \ mynet ``` ```hcl config { network_mode = "mynet" ipv4_address = "172.20.0.5" } ``` -------------------------------- ### Configure Volumes Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Binds host paths to container paths using host_path:container_path:options format. ```hcl config { volumes = [ "/some/host/data:/container/data:ro,noexec" ] } ``` -------------------------------- ### Configure SELinux Options Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Defines a list of process labels for the container to use. ```hcl config { selinux_opts = [ "type:my_container.process" ] } ``` -------------------------------- ### Deploying and Verifying the Redis Job Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Commands to run the Nomad job and verify the container status using Podman. ```sh nomad run redis.nomad ==> Monitoring evaluation "9fc25b88" Evaluation triggered by job "redis" Allocation "60fdc69b" created: node "f6bccd6d", group "redis" Evaluation status changed: "pending" -> "complete" ==> Evaluation "9fc25b88" finished with status "complete" podman ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 6d2d700cbce6 docker.io/library/redis:latest docker-entrypoint... 16 seconds ago Up 16 seconds ago redis-60fdc69b-65cb-8ece-8554-df49321b3462 ``` -------------------------------- ### Configure Added Capabilities Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Passes a list of Linux capabilities to the container. ```hcl config { cap_add = [ "SYS_TIME" ] } ``` -------------------------------- ### Query API Client Configuration Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Methods for retrieving client settings and state information. ```go func (c *API) GetAPIVersion() string func (c *API) IsDefaultClient() bool func (c *API) SetClientAsDefault(d bool) func (c *API) IsCgroupV2() bool func (c *API) GetCgroupMgr() string func (c *API) IsRootless() bool func (c *API) GetSocketPath() string func (c *API) IsAppArmorEnabled() bool ``` -------------------------------- ### Configure Read-Only Root Filesystem Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Mount the root filesystem as read-only to enhance security. Use tmpfs to provide writable paths for temporary files. ```hcl config { readonly_rootfs = true } ``` ```hcl config { readonly_rootfs = true tmpfs = [ "/tmp", "/var/tmp", "/var/cache", "/var/log" ] } ``` -------------------------------- ### Configure Logging Defaults Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/configuration.md Sets the default log driver and specific options passed to Podman. ```hcl plugin "nomad-driver-podman" { config { logging { driver = "nomad" options = { "max-size" = "10m" "max-file" = "3" } } } } ``` -------------------------------- ### Configure Bind Mounts Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Bind mounts allow mapping host directories into the container. Requires volumes.enabled to be true in the plugin configuration. ```hcl config { volumes = [ "/var/data:/data:ro", "/var/logs:/logs:rw", "/tmp:/tmp:shared" ] } ``` ```hcl config { volumes = [ "/var/nomad/allocs/${NOMAD_ALLOC_ID}/data:/data:ro,noexec", "/var/logs:/var/log:rw", ] } ``` -------------------------------- ### Deploy PostgreSQL with Persistent Volumes Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Configures a database service with host volume mounting and environment variables. Ensure the host directory exists before deployment. ```hcl job "postgres" { datacenters = ["dc1"] type = "service" group "database" { network { port "db" { to = 5432 } } task "postgres" { driver = "podman" config { image = "docker://postgres:15-alpine" ports = ["db"] volumes = [ "/var/lib/postgres:/var/lib/postgresql/data" ] env = { POSTGRES_PASSWORD = "secret123" POSTGRES_DB = "myapp" } } resources { cpu = 1000 memory = 2048 } } } } ``` -------------------------------- ### Enable Container Init Process Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Enable an init process to run as PID 1, which is essential for signal forwarding and reaping zombie processes in multi-process containers. ```hcl config { init = true init_path = "/usr/libexec/podman/catatonit" } ``` -------------------------------- ### Configure Simple Docker Hub Image Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Basic configuration for pulling an image from Docker Hub. ```hcl config { image = "nginx:latest" } ``` -------------------------------- ### Database Minimal Privileges Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/security-namespaces.md Configures a database container with specific capabilities and a non-root user. ```hcl config { image = "postgres:latest" cap_drop = ["ALL"] cap_add = ["CHOWN", "SETUID", "SETGID"] security_opt = ["no-new-privileges"] user = "postgres" } ``` -------------------------------- ### Configure Arguments Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Passes a list of arguments to the container command. ```hcl config { args = [ "arg1", "arg2", ] } ``` -------------------------------- ### Define TaskLoggingConfig struct and methods Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Configures per-task logging drivers and options, including a helper method to check for empty configurations. ```go type TaskLoggingConfig struct { Driver string // Log driver (nomad, journald) Options hclcompat.MapStrStr // Driver options } ``` ```go func (l *TaskLoggingConfig) Empty() bool ``` -------------------------------- ### Define TaskAuthConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Defines registry authentication credentials and TLS verification settings. ```go type TaskAuthConfig struct { Username string // Registry username Password string // Registry password or token TLSVerify bool // Verify TLS certificates } ``` -------------------------------- ### Configure Resource Limits for High-Performance Apps Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/README.md Sets CPU, memory, ulimit, and sysctl parameters to optimize performance and resource isolation. ```hcl config { cpu_hard_limit = true memory_swappiness = 10 # Minimize swap ulimit = { "nofile" = "65536:65536" } sysctl = { "net.core.somaxconn" = "32768" } } ``` -------------------------------- ### Retrieve Plugin Metadata Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Fetches plugin information including name and type. ```go info, _ := driver.PluginInfo() // info.Name == "podman" // info.Type == base.PluginTypeDriver ``` -------------------------------- ### Configure Storage Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/configuration.md Configures bind mounts, temporary filesystems, and device access. ```hcl config { volumes = [ "/var/run/secret:/secret:ro", "/data:/data:rw" ] tmpfs = ["/tmp"] devices = ["/dev/fuse", "/dev/net/tun"] shm_size = "512m" } ``` -------------------------------- ### Define VolumeConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Defines volume handling configuration. ```go type VolumeConfig struct { Enabled bool // Enable bind mounts SelinuxLabel string // SELinux label } ``` -------------------------------- ### Define PluginSocketConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Defines a Podman socket configuration. ```go type PluginSocketConfig struct { Name string // Socket identifier SocketPath string // Unix socket path } ``` -------------------------------- ### General Purpose Web App Resource Configuration Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/resource-limits.md Basic resource allocation for a standard web application. ```hcl resources { cpu = 500 # 500 MHz memory = 512 # 512 MB } config { memory_reservation = "256m" } ``` -------------------------------- ### Enable read-only root filesystem Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Mounts the container root filesystem as read-only. ```hcl config { readonly_rootfs = true } ``` -------------------------------- ### Configure Registry Auth File Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/registry-auth.md Specify a path to a JSON authentication file in the plugin configuration. ```hcl plugin "nomad-driver-podman" { config { auth { config = "/etc/podman/auth.json" } } } ``` ```json { "auths": { "docker.io": { "username": "user", "password": "token", "auth": "dXNlcjp0b2tlbg==" } } } ``` -------------------------------- ### ExecTask(taskID string, cmd []string, timeout time.Duration) Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Executes a command within a running container. ```APIDOC ## ExecTask ### Description Executes a command in a running container. ### Parameters - **taskID** (string) - Task identifier - **cmd** ([]string) - Command and arguments - **timeout** (time.Duration) - Execution timeout ### Returns - **ExitCode** (int) - Command exit code - **Stdout** (string) - Command stdout - **Stderr** (string) - Command stderr ``` -------------------------------- ### Configure Volume Bind Mounts Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/configuration.md Enables or disables host path bind mounts and sets the SELinux label for directories. ```hcl plugin "nomad-driver-podman" { config { volumes { enabled = true selinuxlabel = "z" } } } ``` -------------------------------- ### Bind Allocation Directories in Task Configuration Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Use environment variables to map allocation-specific directories into the container filesystem. ```hcl config { volumes = [ "${NOMAD_ALLOC_DIR}/data:/data", "${NOMAD_SECRETS_DIR}:/secrets:ro" ] } ``` -------------------------------- ### Run Container Monitor Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/task-monitoring.md Monitors container state and resource usage in a dedicated goroutine. ```go func (h *TaskHandle) runContainerMonitor() ``` ```go h.stateLock.Lock() h.procState = drivers.TaskStateExited h.completedAt = time.Now() h.exitResult.ExitCode = exitCode h.stateLock.Unlock() ``` -------------------------------- ### NewClient Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Creates a new Podman API client instance using the provided logger and configuration. ```APIDOC ## func NewClient(logger hclog.Logger, config ClientConfig) *API ### Description Initializes a new Podman API client with the specified socket configuration and logger. ### Parameters - **logger** (hclog.Logger) - Required - The logger instance for the client. - **config** (ClientConfig) - Required - The configuration settings for the client. ``` -------------------------------- ### Calculate CPU statistics Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/task-monitoring.md Normalizes raw Podman container stats against host compute using the CPUTracker utility. ```text totalPercent = CPUTracker.Percent(TotalUsage) systemMode = SystemCPUTracker.Percent(UsageInKernelmode) userMode = UserCPUTracker.Percent(UsageInUsermode) totalTicks = SystemCPUTracker.TicksConsumed(totalPercent) ``` -------------------------------- ### Fix Permission Denied on Bind Mount Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Adjust host directory ownership and permissions to allow container access. ```bash # Make writable by container user sudo chown 1000:1000 /host/path sudo chmod u+w /host/path # Or use SELinux z label (if configured) ``` -------------------------------- ### Connect to a custom network with a static IP Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/networking.md Assigns a task to a pre-existing Podman network and specifies a static IPv4 address. ```hcl # Create network: # podman network create --subnet 172.30.0.0/16 worknet group "db" { task "database" { driver = "podman" config { image = "postgres:latest" network_mode = "worknet" ipv4_address = "172.30.0.10" } } } ``` -------------------------------- ### Define PluginAuthConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Defines registry authentication settings for the plugin. ```go type PluginAuthConfig struct { FileConfig string // Path to auth config file Helper string // Credential helper command } ``` -------------------------------- ### Configure Application Data Persistence Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Mounts a host directory to a container path for persistent database storage. ```hcl group "database" { task "postgres" { driver = "podman" config { image = "postgres:latest" volumes = [ "/data/postgres:/var/lib/postgresql/data" ] } } } ``` -------------------------------- ### Configure Archive from HTTP Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Pulling an OCI archive directly from an HTTP source. ```hcl config { image = "oci-archive:https://artifacts.example.com/builds/app-latest.tar" image_pull_timeout = "10m" } ``` -------------------------------- ### Configure container capabilities Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/security-namespaces.md Drop all Linux capabilities and add only those required by the application to minimize the attack surface. ```hcl cap_drop = ["ALL"] cap_add = ["NET_BIND_SERVICE"] # Only what's needed ``` -------------------------------- ### Verify Podman Connectivity Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Commands to test socket accessibility and inspect container states. ```bash # Check if Podman socket is accessible curl -v --unix-socket /run/podman/podman.sock http://localhost/_ping # List containers podman ps -a # Inspect specific container podman inspect ``` -------------------------------- ### Configure Sysctl Parameters Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/README.md Set kernel parameters supported by Podman for the container. ```hcl sysctl = { "net.core.somaxconn" = "32768" "fs.file-max" = "2097152" } ``` -------------------------------- ### ExecCreate API Method Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Creates an exec session for command execution in a running container. ```go func (c *API) ExecCreate(ctx context.Context, containerID string, opts *ExecOptions) (string, error) ``` ```go type ExecOptions struct { Cmd []string // Command and arguments Env []string // Environment variables WorkingDir string // Working directory User string // User/UID AttachStdin bool // Attach stdin AttachStdout bool // Attach stdout AttachStderr bool // Attach stderr Tty bool // Allocate TTY } ``` -------------------------------- ### Ping API Method Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Verifies Podman availability and returns the API version. ```go func (c *API) Ping(ctx context.Context) (string, error) ``` -------------------------------- ### Configure Container Tuning Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/configuration.md Set container metadata labels and kernel parameters using sysctl. ```hcl config { labels = [ { "app" = "myapp" "version" = "1.0" } ] sysctl = { "net.core.somaxconn" = "16384" } } ``` -------------------------------- ### Enable read-only root filesystem Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/security-namespaces.md Mount the root filesystem as read-only and provide a tmpfs mount for temporary files. ```hcl readonly_rootfs = true tmpfs = ["/tmp"] ``` -------------------------------- ### Monitor Container Resources in Go Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Fetches CPU and memory usage statistics for a running container. Requires the container to be in a running state to return valid data. ```go func (c *API) ContainerStats(ctx context.Context, containerID string) (Stats, error) ``` ```go type Stats struct { CPUStats struct { CPUUsage struct { TotalUsage uint64 UsageInKernelmode uint64 UsageInUsermode uint64 } } MemoryStats struct { Usage uint64 // Current memory usage MaxUsage uint64 // Peak memory usage } } ``` ```go stats, err := client.ContainerStats(ctx, containerID) if err == nil { cpuPercent := float64(stats.CPUStats.CPUUsage.TotalUsage) / 1e9 memMB := stats.MemoryStats.Usage / 1024 / 1024 } ``` -------------------------------- ### Execute Commands in Containers Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Accessing running containers via Nomad allocation or directly through Podman. ```bash # Via Nomad nomad alloc exec /bin/bash # Or direct Podman podman exec -it /bin/bash ``` -------------------------------- ### Configure Multi-Architecture Image Pull Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Use platform configuration to force specific architecture pulls and enforce node constraints. ```hcl job "universal-app" { group "service" { # On AMD64 node task "api" { driver = "podman" config { image = "myapp:latest" os = "linux" arch = "amd64" } } } # Nomad constraint can enforce architecture constraint { attribute = "${attr.cpu.arch}" value = "amd64" } } ``` -------------------------------- ### NewPodmanDriver Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Creates and returns a new Podman driver instance. ```APIDOC ## NewPodmanDriver(logger hclog.Logger) ### Description Creates and returns a new Podman driver instance. ### Parameters - **logger** (hclog.Logger) - Required - Logger instance for driver logs ### Returns - **drivers.DriverPlugin** - Driver instance ready for plugin initialization ``` -------------------------------- ### Execute HTTP Requests Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Methods for performing HTTP operations against the Podman socket. ```go func (c *API) Get(ctx context.Context, path string) (*http.Response, error) func (c *API) GetStream(ctx context.Context, path string) (*http.Response, error) func (c *API) Post(ctx context.Context, path string, body io.Reader) (*http.Response, error) func (c *API) Do(req *http.Request, streaming bool) (*http.Response, error) ``` -------------------------------- ### Configure User Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Specifies the user or UID to run the container command as. ```hcl user = nobody config { } ``` -------------------------------- ### Configure Credential Helper Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/registry-auth.md Use an external credential helper to retrieve registry authentication details. ```hcl plugin "nomad-driver-podman" { config { auth { helper = "pass" } } } ``` ```bash echo "registry.io" | podman-credential-pass get ``` ```json { "username": "user", "password": "token" } ``` -------------------------------- ### Configure platform architecture and OS Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Overrides the default architecture and operating system for image pulling. ```hcl config { image = "docker.io/nginx:latest" os = "linux" arch = "amd64" } ``` -------------------------------- ### Define NetworkingConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Defines networking defaults for the plugin. ```go type NetworkingConfig struct { DefaultRootlessMode string // Override rootless network mode } ``` -------------------------------- ### Configuring structured logging with labels Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/logging.md HCL configuration to include task labels in journald log entries. ```hcl job "service" { group "app" { task "worker" { driver = "podman" config { image = "worker:latest" logging { driver = "journald" options = { "tag" = "worker" "labels" = "service,version,env" } } labels = [ { "service" = "myservice" "version" = "v1.2.3" "env" = "production" } ] } } } } ``` -------------------------------- ### Log PluginConfig warnings Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Emits warnings about problematic configurations. ```go func (c *PluginConfig) LogWarnings(logger hclog.Logger) ``` -------------------------------- ### Select Socket in Job Specification Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Demonstrates how to target specific configured sockets within a task configuration. ```hcl job "unprivileged" { group "service" { task "app" { driver = "podman" config { image = "myapp:latest" socket = "rootless" # Use rootless socket } } } } ``` ```hcl job "privileged" { group "service" { task "app" { driver = "podman" config { image = "myapp:latest" socket = "rootful" # Use rootful socket privileged = true } } } } ``` -------------------------------- ### Configure Registry Credentials Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Authentication settings at the task level or plugin level. ```hcl config { image = "myregistry.io/myapp:latest" auth { username = "user" password = "password" tls_verify = true } } ``` ```hcl plugin "nomad-driver-podman" { config { auth { config = "/etc/podman/auth.json" helper = "pass" } } } ``` -------------------------------- ### Define PluginConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Represents the primary configuration for the Podman driver plugin. ```go type PluginConfig struct { Auth PluginAuthConfig // Registry auth config Volumes VolumeConfig // Volume settings GC GCConfig // Garbage collection RecoverStopped bool // Restart stopped containers DisableLogCollection bool // Disable Nomad log collection Socket []PluginSocketConfig // Multiple socket definitions SocketPath string // Single socket path ClientHttpTimeout string // HTTP timeout duration ExtraLabels []string // Metadata labels to apply DNSServers []string // Global DNS servers Logging LoggingConfig // Default logging config Networking NetworkingConfig // Networking defaults } ``` -------------------------------- ### Define LoggingConfig struct Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/types.md Defines logging defaults for the plugin. ```go type LoggingConfig struct { Driver string // Log driver Options map[string]string // Driver options } ``` -------------------------------- ### Configure pasta Networking Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/networking.md Enables improved user-space networking for rootless containers, the default for Podman 5.0+. ```hcl config { network_mode = "pasta" } ``` -------------------------------- ### Configure plugin-level SELinux volume labeling Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/security-namespaces.md Sets automatic SELinux labeling for all container mounts at the plugin level. ```hcl plugin "nomad-driver-podman" { config { volumes { selinuxlabel = "z" # Shared label } } } ``` -------------------------------- ### Configure Registry Authentication via JSON File Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/registry-auth.md Reference an external JSON file containing registry credentials within the plugin configuration. ```hcl plugin "nomad-driver-podman" { config { auth { config = "/etc/nomad/docker-auth.json" } } } ``` ```json { "auths": { "myregistry.io": { "username": "user", "password": "pass" }, "docker.io": { "auth": "dXNlcjpwYXNz" } } } ``` -------------------------------- ### Configure Temporary Filesystems Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/container-volumes.md Tmpfs mounts provide in-memory storage for ephemeral data. Options like size and permissions can be specified per path. ```hcl config { tmpfs = [ "/tmp", "/var:size=500m" ] } ``` ```hcl config { tmpfs = [ "/tmp:size=1g", "/var/cache:noexec,nosuid", ] } ``` -------------------------------- ### Execute and monitor the performance test Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Commands to deploy the job to the Nomad cluster and observe real-time allocation statistics. ```bash nomad job run perf-test.nomad watch nomad alloc stats ``` -------------------------------- ### Authenticate with Private Registry Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Demonstrates methods for providing registry credentials via Nomad variables or an external configuration file. ```hcl variables { registry_url = "myregistry.io:5000" registry_user = "ci-user" registry_password = sensitive("...") } job "private-app" { group "service" { task "app" { driver = "podman" config { image = "${var.registry_url}/myapp:latest" auth { username = var.registry_user password = var.registry_password tls_verify = true } } } } } ``` ```hcl plugin "nomad-driver-podman" { config { auth { config = "/etc/nomad/docker-config.json" } } } # /etc/nomad/docker-config.json: # { # "auths": { # "myregistry.io:5000": { # "username": "ci-user", # "password": "secret" # } # } # } ``` -------------------------------- ### Specify Target Operating System Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Sets the target operating system for the container image. ```hcl config { image = "myapp:latest" os = "linux" } ``` -------------------------------- ### ImagePullOptions Configuration Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Configuration struct for image pull operations, including authentication and platform specifications. ```go type ImagePullOptions struct { Auth *types.DockerAuthConfig // Registry credentials SkipTLS bool // Disable TLS verification OS string // Target OS Arch string // Target architecture Variant string // Target variant } ``` -------------------------------- ### PluginInfo Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/driver-interface.md Returns plugin metadata including type, API version, version, and name. ```APIDOC ## PluginInfo() ### Description Returns plugin metadata including type, API version, version, and name. ### Returns - **base.PluginInfoResponse** - Contains plugin name "podman", type PluginTypeDriver, API version 010, and semantic version - **error** - Always nil ``` -------------------------------- ### Run Nomad Job and View Logs Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Commands to execute a job file and retrieve logs for a specific allocation. ```bash nomad job run redis.nomad nomad logs redis ``` -------------------------------- ### ExecInspect API Method Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/api-client.md Retrieves the status and exit code of an exec session. ```go func (c *API) ExecInspect(ctx context.Context, execID string) (ExecInspectData, error) ``` -------------------------------- ### Configure Logging Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Sets the logging driver for the container. ```hcl config { logging = { driver = "nomad" } } ``` ```hcl config { logging = { driver = "journald" options = { "tag" = "redis" } } } ``` -------------------------------- ### Configure Registry Authentication Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Provides static credentials for private registry access. ```hcl config { image = "your.registry.tld/some/image" auth { username = "someuser" password = "sup3rs3creT" tls_verify = true } } ``` -------------------------------- ### Monitor Resource Usage Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/usage-examples.md Commands to retrieve performance statistics for tasks and containers. ```bash # Task stats nomad alloc stats # Podman stats podman stats --no-stream ``` -------------------------------- ### Configure Secure Container Settings Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/README.md Applies security hardening options to a container, including dropping capabilities and enabling a read-only root filesystem. ```hcl config { security_opt = ["no-new-privileges"] cap_drop = ["ALL"] cap_add = ["NET_BIND_SERVICE"] readonly_rootfs = true tmpfs = ["/tmp"] } ``` -------------------------------- ### Configure Sysctl Settings Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Sets a key-value map of sysctl configurations for the container. ```hcl config { sysctl = { "net.core.somaxconn" = "16384" } } ``` -------------------------------- ### Set Security Options Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/security-namespaces.md Apply security-related container options such as privilege escalation prevention or SELinux labels. ```hcl config { security_opt = [ "no-new-privileges", "apparmor=docker-default" ] } ``` ```hcl config { security_opt = [ "no-new-privileges", "apparmor=docker-default", "label=type:container_t" ] } ``` -------------------------------- ### Configure Registry Authentication Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/configuration.md Sets the path to a credentials file for container registry access. ```hcl plugin "nomad-driver-podman" { config { auth { config = "/etc/podman/auth.json" } } } ``` -------------------------------- ### Configure GRUB for cgroups v2 Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/README.md Update the GRUB command line to enable memory accounting and unified cgroup hierarchy. ```sh GRUB_CMDLINE_LINUX_DEFAULT="quiet cgroup_enable=memory swapaccount=1 systemd.unified_cgroup_hierarchy=1" ``` -------------------------------- ### Configure Docker Archive Images Source: https://github.com/hashicorp/nomad-driver-podman/blob/main/_autodocs/image-management.md Loading images from local Docker tarball archives. ```hcl config { image = "docker-archive:///var/images/myapp.tar" } ```