workload

package module
v0.1.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 8 Imported by: 0

README

workload

Provider-based workload manager for deploying and managing containerized workloads across Docker and Kubernetes runtimes.

Install

go get github.com/kbukum/gokit/workload@latest

Quick Start

Docker
import (
    "github.com/kbukum/gokit/workload"
    "github.com/kbukum/gokit/workload/docker"
)

mgr, _ := docker.NewManager(&docker.Config{Host: "unix:///var/run/docker.sock"}, nil, log)
result, _ := mgr.Deploy(ctx, workload.DeployRequest{
    Name:  "my-app",
    Image: "nginx:latest",
    Ports: []workload.PortMapping{{Container: 80, Host: 8080}},
})
Kubernetes
import (
    "github.com/kbukum/gokit/workload"
    "github.com/kbukum/gokit/workload/kubernetes"
)

mgr, _ := kubernetes.NewManager(&kubernetes.Config{Namespace: "default"}, nil, log)
result, _ := mgr.Deploy(ctx, workload.DeployRequest{
    Name:  "my-job",
    Image: "busybox:latest",
    Command: []string{"echo", "hello"},
})
As a Component
comp := workload.NewComponent(workload.Config{Provider: "docker"}, dockerCfg, log)
comp.Start(ctx)
defer comp.Stop(ctx)

mgr := comp.Manager()

Key Types & Functions

workload
Symbol Description
Manager Interface — Deploy, Stop, Remove, Restart, Status, Wait, Logs, List, HealthCheck
ExecProvider Optional — Exec(ctx, id, cmd) for running commands in workloads
StatsProvider Optional — Stats(ctx, id) for CPU/memory/network metrics
LogStreamer Optional — StreamLogs(ctx, id, opts) for real-time log streaming
EventWatcher Optional — WatchEvents(ctx, filter) for lifecycle events
NewComponent(cfg, providerCfg, log) Create lifecycle-managed component
DeployRequest Name, Image, Command, Environment, Resources, Ports, Volumes
WorkloadStatus ID, Status, Running, Healthy, ExitCode, Restarts
ParseMemory(s) Parse memory strings ("512m", "1g") to bytes
ParseCPU(s) Parse CPU strings ("0.5", "500m") to nanocores
workload/docker
Symbol Description
NewManager(cfg, labels, log) Create Docker manager (implements all optional interfaces)
Config Host, APIVersion, TLS, Network, Registry, Platform
workload/kubernetes
Symbol Description
NewManager(cfg, labels, log) Create Kubernetes manager (Pod/Job support)
Config Kubeconfig, Context, Namespace, ServiceAccount, WorkloadType, ImagePullPolicy

← Back to main gokit README

Documentation

Overview

Package workload provides a provider-based workload manager for deploying and managing containerized workloads across multiple runtimes.

It follows gokit's component pattern with lifecycle management and supports pluggable backends for different container orchestration platforms.

Backends

  • workload/docker: Docker container management via Docker API
  • workload/kubernetes: Kubernetes pod management via client-go

Operations

The workload manager supports full lifecycle operations:

  • Deploy: Create and start workloads
  • Stop/Remove: Graceful shutdown and cleanup
  • Logs: Stream container/pod logs
  • Exec: Execute commands inside running workloads
  • Events: Monitor workload state changes

Package workload provides a provider-based workload manager for deploying and managing workloads across different runtimes (Docker, Kubernetes, etc.).

Index

Constants

View Source
const (
	StatusCreated    = "created"
	StatusRunning    = "running"
	StatusStopped    = "stopped"
	StatusCompleted  = "completed"
	StatusError      = "error"
	StatusRestarting = "restarting"
	StatusUnknown    = "unknown"
	StatusNotFound   = "not_found"
)

Status constants for workload state.

View Source
const (
	ProviderDocker     = "docker"
	ProviderKubernetes = "kubernetes"
)

Provider constants for well-known workload runtimes.

View Source
const (
	DefaultProvider = ProviderDocker
)

Variables

This section is empty.

Functions

func FormatCPU

func FormatCPU(nanocores int64) string

FormatCPU converts nanocores to a human-readable string.

func FormatMemory

func FormatMemory(bytes int64) string

FormatMemory converts bytes to a human-readable string.

func ParseCPU

func ParseCPU(s string) (int64, error)

ParseCPU converts human-readable CPU strings to nanocores. Supported formats: "0.5" (cores), "500m" (millicores), "1" (1 core).

func ParseMemory

func ParseMemory(s string) (int64, error)

ParseMemory converts human-readable memory strings to bytes. Supported suffixes: k/ki (KiB), m/mi (MiB), g/gi (GiB), t/ti (TiB). Without suffix, the value is treated as bytes.

func RegisterFactory

func RegisterFactory(name string, f ManagerFactory)

RegisterFactory registers a workload provider factory.

Types

type Component

type Component struct {
	// contains filtered or unexported fields
}

Component wraps Manager and implements component.Component for lifecycle management.

func NewComponent

func NewComponent(cfg Config, providerCfg any, log *logger.Logger) *Component

NewComponent creates a workload component for use with the component registry.

func (*Component) Describe

func (c *Component) Describe() component.Description

func (*Component) Health

func (c *Component) Health(ctx context.Context) component.Health

func (*Component) Manager

func (c *Component) Manager() Manager

Manager returns the underlying Manager, or nil if not started.

func (*Component) Name

func (c *Component) Name() string

func (*Component) Start

func (c *Component) Start(_ context.Context) error

func (*Component) Stop

func (c *Component) Stop(_ context.Context) error

type Config

type Config struct {
	Provider      string            `mapstructure:"provider" json:"provider"`
	Enabled       bool              `mapstructure:"enabled" json:"enabled"`
	DefaultLabels map[string]string `mapstructure:"default_labels" json:"default_labels"`
}

Config holds provider-agnostic workload configuration.

func (*Config) ApplyDefaults

func (c *Config) ApplyDefaults()

ApplyDefaults fills in zero-valued fields.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks that the core configuration is valid.

type DeployRequest

type DeployRequest struct {
	Name           string            // Human-readable identifier (container name, pod name)
	Image          string            // Container image reference
	Command        []string          // Override entrypoint/command
	Args           []string          // Arguments passed to the command
	Environment    map[string]string // Environment variables
	Labels         map[string]string // Key-value pairs for filtering and grouping
	Annotations    map[string]string // Metadata annotations (K8s)
	WorkDir        string            // Working directory inside workload
	Resources      *ResourceConfig   // CPU/memory constraints
	Network        *NetworkConfig    // Network configuration
	Volumes        []VolumeMount     // Mount points
	Ports          []PortMapping     // Port mappings
	RestartPolicy  string            // "no", "always", "on-failure", "unless-stopped"
	AutoRemove     bool              // Remove after exit (Docker)
	Replicas       int               // Number of replicas (K8s, 0 = default 1)
	Timeout        time.Duration     // Maximum run time (0 = no limit)
	Platform       string            // Target platform (e.g. "linux/amd64")
	Namespace      string            // Namespace (K8s, empty = default)
	ServiceAccount string            // Service account (K8s)
	Metadata       map[string]any    // Provider-specific extras
}

DeployRequest describes a workload to deploy.

type DeployResult

type DeployResult struct {
	ID     string // Container ID (Docker) or Pod/Job name (K8s)
	Name   string
	Status string
}

DeployResult is returned after a successful deployment.

type EventWatcher

type EventWatcher interface {
	WatchEvents(ctx context.Context, filter ListFilter) (<-chan WorkloadEvent, error)
}

EventWatcher is optionally implemented by providers that support watching workload lifecycle events.

type ExecProvider

type ExecProvider interface {
	Exec(ctx context.Context, id string, cmd []string) (*ExecResult, error)
}

ExecProvider is optionally implemented by providers that support executing commands inside running workloads.

type ExecResult

type ExecResult struct {
	ExitCode int
	Stdout   string
	Stderr   string
}

ExecResult is returned from ExecProvider.Exec.

type ListFilter

type ListFilter struct {
	Labels    map[string]string // Match ALL labels (AND)
	Name      string            // Name prefix/pattern
	Status    string            // Filter by status
	Namespace string            // K8s namespace (empty = all)
}

ListFilter filters workloads in List operations.

type LogOptions

type LogOptions struct {
	Tail   int           // Last N lines (0 = all)
	Since  time.Duration // Logs from this duration ago
	Follow bool          // Stream mode (for LogStreamer)
}

LogOptions controls log retrieval behavior.

type LogStreamer

type LogStreamer interface {
	StreamLogs(ctx context.Context, id string, opts LogOptions) (io.ReadCloser, error)
}

LogStreamer is optionally implemented by providers that support streaming logs in real-time.

type Manager

type Manager interface {
	// Deploy creates and starts a workload.
	Deploy(ctx context.Context, req DeployRequest) (*DeployResult, error)

	// Stop gracefully stops a running workload.
	Stop(ctx context.Context, id string) error

	// Remove removes a stopped workload and cleans up resources.
	Remove(ctx context.Context, id string) error

	// Restart stops and restarts a workload.
	Restart(ctx context.Context, id string) error

	// Status returns the current status of a workload.
	Status(ctx context.Context, id string) (*WorkloadStatus, error)

	// Wait blocks until the workload exits, returning the exit status.
	Wait(ctx context.Context, id string) (*WaitResult, error)

	// Logs returns log output from a workload.
	Logs(ctx context.Context, id string, opts LogOptions) ([]string, error)

	// List returns workloads matching the given filter.
	List(ctx context.Context, filter ListFilter) ([]WorkloadInfo, error)

	// HealthCheck verifies the provider runtime is available.
	HealthCheck(ctx context.Context) error
}

Manager manages workload lifecycle operations. All providers must implement this core interface.

func New

func New(cfg Config, providerCfg any, log *logger.Logger) (Manager, error)

New creates a Manager for the configured provider.

type ManagerFactory

type ManagerFactory func(cfg Config, providerCfg any, log *logger.Logger) (Manager, error)

ManagerFactory creates a Manager implementation from core config and provider-specific config.

type NetworkConfig

type NetworkConfig struct {
	Mode  string            // Network name, "host", "bridge", "none"
	DNS   []string          // Custom DNS servers
	Hosts map[string]string // Extra /etc/hosts entries
}

NetworkConfig defines workload networking.

type PortMapping

type PortMapping struct {
	Host      int
	Container int
	Protocol  string // "tcp" (default), "udp"
}

PortMapping maps a workload port to a host port.

type ResourceConfig

type ResourceConfig struct {
	CPULimit      string // "0.5", "1", "500m"
	CPURequest    string // Min CPU (K8s)
	MemoryLimit   string // "512m", "1g"
	MemoryRequest string // Min memory (K8s)
}

ResourceConfig defines compute resource constraints.

type StatsProvider

type StatsProvider interface {
	Stats(ctx context.Context, id string) (*WorkloadStats, error)
}

StatsProvider is optionally implemented by providers that support real-time resource usage statistics.

type VolumeMount

type VolumeMount struct {
	Source   string // Host path (Docker) or PVC/ConfigMap name (K8s)
	Target   string // Mount path inside workload
	ReadOnly bool
	Type     string // "bind", "volume", "configmap", "secret", "pvc" (empty = "bind")
}

VolumeMount defines a storage mount.

type WaitResult

type WaitResult struct {
	StatusCode int64
	Error      string
}

WaitResult is returned when a workload exits.

type WorkloadEvent

type WorkloadEvent struct {
	ID        string
	Name      string
	Event     string // "start", "stop", "die", "health_status", "oom", "restart"
	Timestamp time.Time
	Message   string
}

WorkloadEvent represents a lifecycle event.

type WorkloadInfo

type WorkloadInfo struct {
	ID        string
	Name      string
	Image     string
	Status    string
	Labels    map[string]string
	Created   time.Time
	Namespace string // K8s namespace
}

WorkloadInfo contains summary information for list operations.

type WorkloadStats

type WorkloadStats struct {
	CPUPercent     float64
	MemoryUsage    int64
	MemoryLimit    int64
	NetworkRxBytes int64
	NetworkTxBytes int64
	DiskReadBytes  int64
	DiskWriteBytes int64
	PIDs           int
}

WorkloadStats contains resource usage statistics.

type WorkloadStatus

type WorkloadStatus struct {
	ID        string
	Name      string
	Image     string
	Status    string
	Running   bool
	Healthy   bool
	Ready     bool // All readiness checks pass (K8s)
	StartedAt time.Time
	StoppedAt time.Time
	ExitCode  int
	Message   string
	Restarts  int // Restart count (K8s)
}

WorkloadStatus represents the current state of a workload.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL