Documentation
¶
Overview ¶
Package types defines the core data structures used throughout Warren.
This package contains all fundamental types that represent Warren's domain model, including clusters, nodes, services, tasks, secrets, volumes, and ingress resources. These types are used by all other packages for state management, API communication, and orchestration logic.
Architecture ¶
The types package is the foundation of Warren's data model. It defines:
- Cluster topology (managers, workers)
- Service specifications and deployment strategies
- Task execution state and lifecycle
- Resource management (CPU, memory, disk)
- Security primitives (secrets, certificates)
- Storage primitives (volumes, mounts)
- Networking primitives (ports, ingress, DNS)
- Health check configurations
All types are designed to be:
- Serializable (JSON, Protocol Buffers)
- Immutable where possible (use pointers for updates)
- Self-documenting (clear field names and comments)
- Validated (constants for enums, validation helpers)
Core Types ¶
The main types in this package are:
Cluster Topology:
- Cluster: Represents the entire Warren cluster
- Node: Manager or worker node with resources and status
- NodeRole: Manager or worker role
- NodeStatus: Ready, down, draining, unknown
Service Management:
- Service: User-defined containerized workload
- ServiceMode: Replicated (N replicas) or global (one per node)
- DeployStrategy: Rolling, blue-green, or canary updates
- UpdateConfig: Update parallelism, delay, failure actions
Task Execution:
- Task: Single instance of a service (container)
- TaskState: Pending, assigned, running, failed, etc.
- TaskStatus: Current state with timestamps and error details
Security:
- Secret: Encrypted data (passwords, certificates, etc.)
- SecretType: Opaque, TLS, certificate authority
- Certificate: TLS certificate with domain and auto-renewal
Storage:
- Volume: Persistent storage volume
- VolumeDriver: Local, NFS, etc.
- VolumeMount: Mount point in a container
Networking:
- PortMapping: Container port to host/cluster port mapping
- PublishMode: Host (node-local) or ingress (cluster-wide)
- Ingress: HTTP/HTTPS routing rules with TLS
- IngressRule: Host-based and path-based routing
Health & Resources:
- HealthCheck: HTTP, TCP, or exec health probes
- ResourceRequirements: CPU and memory limits/reservations
- RestartPolicy: Always, on-failure, never
Usage ¶
Creating a Service:
service := &types.Service{
ID: uuid.New().String(),
Name: "nginx",
Image: "nginx:latest",
Replicas: 3,
Mode: types.ServiceModeReplicated,
Ports: []*types.PortMapping{
{
ContainerPort: 80,
HostPort: 8080,
Protocol: "tcp",
PublishMode: types.PublishModeHost,
},
},
HealthCheck: &types.HealthCheck{
Type: types.HealthCheckTypeHTTP,
Endpoint: "http://localhost:80/",
Interval: 30 * time.Second,
Timeout: 5 * time.Second,
Retries: 3,
},
Resources: &types.ResourceRequirements{
Limits: &types.ResourceSpec{
CPUShares: 1024,
MemoryBytes: 512 * 1024 * 1024, // 512MB
},
},
}
Creating a Task from a Service:
task := &types.Task{
ID: uuid.New().String(),
ServiceID: service.ID,
ServiceName: service.Name,
NodeID: "", // Assigned by scheduler
Image: service.Image,
Env: service.Env,
Ports: service.Ports,
State: types.TaskStatePending,
DesiredState: types.TaskStateRunning,
CreatedAt: time.Now(),
}
Creating a Secret:
secret := &types.Secret{
ID: uuid.New().String(),
Name: "db-password",
Type: types.SecretTypeOpaque,
Data: []byte("super-secret-password"),
CreatedAt: time.Now(),
}
Creating an Ingress:
ingress := &types.Ingress{
ID: uuid.New().String(),
Name: "my-ingress",
Rules: []*types.IngressRule{
{
Host: "api.example.com",
Paths: []*types.IngressPath{
{
Path: "/",
PathType: types.PathTypePrefix,
ServiceName: "api-service",
ServicePort: 80,
},
},
},
},
TLS: &types.IngressTLS{
Domains: []string{"api.example.com"},
AutoIssue: true,
ACMEEmail: "admin@example.com",
},
}
State Machine ¶
Tasks follow a state machine:
Pending → Assigned → Preparing → Starting → Running → Shutdown → Complete
↓ ↓ ↓ ↓
Failed Failed Failed Failed
Valid state transitions:
- Pending → Assigned (scheduler assigns to node)
- Assigned → Preparing (worker accepts task)
- Preparing → Starting (secrets/volumes mounted)
- Starting → Running (container started)
- Running → Shutdown (graceful stop requested)
- Shutdown → Complete (container stopped cleanly)
- Any → Failed (error occurred)
- Failed → Pending (retry via reconciler)
Design Patterns ¶
Enumeration Pattern:
All enums use typed string constants for safety and clarity:
type TaskState string
const (
TaskStatePending TaskState = "pending"
TaskStateRunning TaskState = "running"
)
Resource Pattern:
Resources follow a limit/reservation pattern: - Limits: Hard caps (task killed if exceeded) - Reservations: Guaranteed allocation (used for scheduling)
Optional Fields:
Optional configurations use pointers: - *HealthCheck: nil = no health checks - *UpdateConfig: nil = use defaults - *IngressTLS: nil = HTTP only
Integration Points ¶
This package integrates with:
- pkg/storage: Persists all types to BoltDB
- pkg/api: Converts to/from Protocol Buffer messages
- pkg/manager: Orchestrates service and task lifecycle
- pkg/scheduler: Uses resources for placement decisions
- pkg/reconciler: Monitors task state transitions
- pkg/worker: Executes tasks based on specifications
- pkg/security: Encrypts secrets and manages certificates
- pkg/volume: Mounts volumes according to specifications
- pkg/health: Performs health checks per configuration
- pkg/ingress: Routes traffic based on ingress rules
Validation ¶
Key validation rules:
Services:
- Name must be unique within cluster
- Replicas must be > 0 for replicated mode
- Image must be a valid container image reference
- Port mappings must have unique HostPort per node
Tasks:
- Must have valid ServiceID reference
- NodeID required when state >= Assigned
- ContainerID required when state >= Running
Secrets:
- Name must be unique within cluster
- Data must be non-empty
- Type must be valid SecretType
Volumes:
- Name must be unique within cluster
- Driver must be supported (local, etc.)
Ingress:
- Rules must have unique Host + Path combinations
- ServiceName must reference existing service
- TLS domains must match rule hosts
Thread Safety ¶
All types in this package are designed to be:
- Read-safe: Can be read concurrently from multiple goroutines
- Write-unsafe: Mutations must be synchronized by callers
- Immutable-preferred: Use new instances for updates where possible
The storage layer (pkg/storage) handles all synchronization for persisted state. In-memory caches must implement their own locking.
Performance Considerations ¶
Memory Layout:
- Small types (Node, Task) use value receivers where possible
- Large types (Service, Ingress) use pointer receivers
- Slices and maps are nil-checked before access
Serialization:
- All types are JSON-serializable for storage
- Protocol Buffer conversions in pkg/api for network efficiency
- BoltDB stores types as JSON (human-readable, debuggable)
See Also ¶
- pkg/storage for persistence layer
- pkg/api for Protocol Buffer definitions
- pkg/manager for orchestration logic
- specs/tech.md for data model design rationale
- .agent/System/database-schema.md for storage schema
Index ¶
- Constants
- type AccessControl
- type Cluster
- type Container
- type ContainerState
- type DeployStrategy
- type DeploymentState
- type Event
- type HeaderManipulation
- type HealthCheck
- type HealthCheckType
- type HealthStatus
- type Ingress
- type IngressBackend
- type IngressPath
- type IngressRule
- type IngressTLS
- type Network
- type NetworkConfig
- type Node
- type NodeResources
- type NodeRole
- type NodeStatus
- type PathRewrite
- type PathType
- type PortMapping
- type PublishMode
- type RateLimit
- type ResourceRequirements
- type RestartCondition
- type RestartPolicy
- type Secret
- type Service
- type ServiceManager
- type ServiceMode
- type TLSCertificate
- type UpdateConfig
- type Volume
- type VolumeMount
Constants ¶
const ( LabelDeploymentVersion = "warren.deployment.version" LabelDeploymentState = "warren.deployment.state" LabelDeploymentStrategy = "warren.deployment.strategy" LabelOriginalService = "warren.deployment.original-service" )
Deployment version label keys
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AccessControl ¶
type AccessControl struct {
AllowedIPs []string // IP whitelist (CIDR notation, e.g., "192.168.1.0/24")
DeniedIPs []string // IP blacklist (CIDR notation)
}
AccessControl defines IP-based access control
type Cluster ¶
type Cluster struct {
ID string
CreatedAt time.Time
Managers []*Node
Workers []*Node
NetworkConfig *NetworkConfig
}
Cluster represents the entire Warren cluster
type Container ¶ added in v1.1.1
type Container struct {
ID string
ServiceID string
ServiceName string
NodeID string
ContainerID string // Runtime container ID (containerd)
DesiredState ContainerState
ActualState ContainerState
Image string
Env []string
Ports []*PortMapping
Mounts []*VolumeMount
Secrets []string // Secret names to mount
HealthCheck *HealthCheck
HealthStatus *HealthStatus // Current health check status
RestartPolicy *RestartPolicy
Resources *ResourceRequirements
StopTimeout int // Seconds to wait before force-killing (default: 10)
CreatedAt time.Time
StartedAt time.Time
FinishedAt time.Time
ExitCode int
Error string
}
Container represents a single running container instance of a service
type ContainerState ¶ added in v1.1.1
type ContainerState string
ContainerState represents the state of a container
const ( ContainerStatePending ContainerState = "pending" ContainerStateRunning ContainerState = "running" ContainerStateFailed ContainerState = "failed" ContainerStateComplete ContainerState = "complete" ContainerStateShutdown ContainerState = "shutdown" )
type DeployStrategy ¶
type DeployStrategy string
DeployStrategy defines how updates are deployed
const ( DeployStrategyRolling DeployStrategy = "rolling" DeployStrategyBlueGreen DeployStrategy = "blue-green" DeployStrategyCanary DeployStrategy = "canary" )
type DeploymentState ¶ added in v1.3.0
type DeploymentState string
DeploymentState represents the state of a deployment version
const ( DeploymentStateActive DeploymentState = "active" // Currently serving traffic DeploymentStateStandby DeploymentState = "standby" // Ready but not serving (blue in blue-green) DeploymentStateCanary DeploymentState = "canary" // Canary version receiving partial traffic DeploymentStateRolling DeploymentState = "rolling" // Rolling update in progress DeploymentStateFailed DeploymentState = "failed" // Deployment failed DeploymentStateRolledBack DeploymentState = "rolled-back" // Deployment was rolled back )
type Event ¶
type Event struct {
Type string
Timestamp time.Time
NodeID string
ServiceID string
ContainerID string
Message string
Data map[string]string
}
Event represents a cluster event (for streaming API)
type HeaderManipulation ¶
type HeaderManipulation struct {
Add map[string]string // Headers to add (e.g., {"X-Custom": "value"})
Set map[string]string // Headers to set/overwrite (e.g., {"X-Frame-Options": "DENY"})
Remove []string // Headers to remove (e.g., ["X-Powered-By"])
}
HeaderManipulation defines header modification rules
type HealthCheck ¶
type HealthCheck struct {
Type HealthCheckType // "http", "tcp", "exec"
Endpoint string // URL or address
Command []string // For exec type
Interval time.Duration
Timeout time.Duration
Retries int
}
HealthCheck defines container health checking
type HealthCheckType ¶
type HealthCheckType string
HealthCheckType defines the type of health check
const ( HealthCheckHTTP HealthCheckType = "http" HealthCheckTCP HealthCheckType = "tcp" HealthCheckExec HealthCheckType = "exec" )
type HealthStatus ¶
type HealthStatus struct {
Healthy bool
Message string
CheckedAt time.Time
ConsecutiveFailures int
ConsecutiveSuccesses int
}
HealthStatus tracks the current health state of a container
type Ingress ¶
type Ingress struct {
ID string
Name string
Rules []*IngressRule
TLS *IngressTLS
Labels map[string]string
CreatedAt time.Time
UpdatedAt time.Time
}
Ingress represents HTTP/HTTPS routing rules for external access
type IngressBackend ¶
type IngressBackend struct {
ServiceName string // Service to route to
Port int // Service port to connect to
}
IngressBackend defines the backend service for routing
type IngressPath ¶
type IngressPath struct {
Path string // Path to match (e.g., "/api", "/web")
PathType PathType // "Prefix" or "Exact"
Backend *IngressBackend // Backend service to route to
Rewrite *PathRewrite // Path rewriting configuration (M7.3)
Headers *HeaderManipulation // Header manipulation (M7.3)
RateLimit *RateLimit // Rate limiting configuration (M7.3)
AccessControl *AccessControl // Access control rules (M7.3)
}
IngressPath defines a path-based routing rule
type IngressRule ¶
type IngressRule struct {
Host string // Hostname to match (e.g., "api.example.com", "*.example.com")
Paths []*IngressPath // Path-based routing rules
}
IngressRule defines routing rules for an ingress
type IngressTLS ¶
type IngressTLS struct {
Enabled bool // Enable HTTPS
SecretName string // Secret containing TLS cert/key (PEM format)
Hosts []string // Hosts covered by this TLS config
AutoTLS bool // Enable Let's Encrypt automatic certificates (M7.3)
Email string // Email for Let's Encrypt notifications (M7.3)
}
IngressTLS defines TLS configuration for HTTPS
type Network ¶
type Network struct {
ID string
Name string
Subnet string // CIDR (e.g., "10.0.1.0/24")
Gateway string
Driver string // "wireguard"
}
Network represents an overlay network
type NetworkConfig ¶
type NetworkConfig struct {
ClusterSubnet string // Overall cluster subnet (e.g., "10.0.0.0/16")
ServiceSubnet string // Subnet for service VIPs (e.g., "10.0.1.0/24")
NodeIPs map[string]net.IP // Node ID -> Overlay IP mapping
}
NetworkConfig represents cluster-wide network configuration
type Node ¶
type Node struct {
ID string
Role NodeRole
Address string // Host IP address
OverlayIP net.IP // WireGuard overlay IP
Hostname string
Labels map[string]string
Resources *NodeResources
Status NodeStatus
LastHeartbeat time.Time
CreatedAt time.Time
}
Node represents a manager or worker node in the cluster
type NodeResources ¶
type NodeResources struct {
// Total capacity
CPUCores int
MemoryBytes int64
DiskBytes int64
// Currently allocated (reserved by containers)
CPUAllocated float64
MemoryAllocated int64
DiskAllocated int64
}
NodeResources tracks resource capacity and allocation
type NodeStatus ¶
type NodeStatus string
NodeStatus represents the current state of a node
const ( NodeStatusReady NodeStatus = "ready" NodeStatusDown NodeStatus = "down" NodeStatusDraining NodeStatus = "draining" NodeStatusUnknown NodeStatus = "unknown" )
type PathRewrite ¶
type PathRewrite struct {
StripPrefix string // Strip this prefix from the path (e.g., "/api/v1" → "/")
ReplacePath string // Replace entire path with this (takes precedence over StripPrefix)
}
PathRewrite defines path rewriting rules
type PortMapping ¶
type PortMapping struct {
Name string
ContainerPort int // Port inside container (target port)
HostPort int // Port on host/cluster (published port)
Protocol string // "tcp" or "udp"
PublishMode PublishMode // "host" or "ingress"
}
PortMapping defines port exposure
type PublishMode ¶
type PublishMode string
PublishMode defines how a port is published
const ( // PublishModeHost publishes port only on the node running the container PublishModeHost PublishMode = "host" // PublishModeIngress publishes port on all nodes with routing mesh PublishModeIngress PublishMode = "ingress" )
type RateLimit ¶
type RateLimit struct {
RequestsPerSecond float64 // Requests allowed per second
Burst int // Burst capacity (token bucket size)
}
RateLimit defines rate limiting configuration
type ResourceRequirements ¶
type ResourceRequirements struct {
// Limits (maximum allowed)
CPULimit float64 // Cores (e.g., 0.5 = 50% of one core)
MemoryLimit int64 // Bytes
// Reservations (guaranteed minimum)
CPUReservation float64
MemoryReservation int64
}
ResourceRequirements defines resource limits and reservations
type RestartCondition ¶
type RestartCondition string
RestartCondition defines when to restart
const ( RestartNever RestartCondition = "never" RestartOnFailure RestartCondition = "on-failure" RestartAlways RestartCondition = "always" )
type RestartPolicy ¶
type RestartPolicy struct {
Condition RestartCondition
MaxAttempts int
Delay time.Duration
}
RestartPolicy defines container restart behavior
type Secret ¶
type Secret struct {
ID string
Name string
Data []byte // Encrypted with AES-256-GCM
CreatedAt time.Time
UpdatedAt time.Time
}
Secret represents encrypted sensitive data
type Service ¶
type Service struct {
ID string
Name string
Image string
Replicas int
Mode ServiceMode
DeployStrategy DeployStrategy
UpdateConfig *UpdateConfig
Env []string
Ports []*PortMapping
Networks []string
Secrets []string
Volumes []*VolumeMount
Labels map[string]string
HealthCheck *HealthCheck
RestartPolicy *RestartPolicy
Resources *ResourceRequirements
StopTimeout int // Seconds to wait before force-killing containers (default: 10)
CreatedAt time.Time
UpdatedAt time.Time
}
Service represents a user-defined workload
type ServiceManager ¶ added in v1.3.0
type ServiceManager interface {
GetService(id string) (*Service, error)
ListServices() ([]*Service, error)
CreateService(service *Service) error
UpdateService(service *Service) error
DeleteService(id string) error
ListContainersByService(serviceID string) ([]*Container, error)
UpdateContainer(container *Container) error
}
ServiceManager defines the interface for service management operations This interface is used to break the import cycle between deploy and manager packages
type ServiceMode ¶
type ServiceMode string
ServiceMode defines how a service is scheduled
const ( ServiceModeReplicated ServiceMode = "replicated" // N replicas ServiceModeGlobal ServiceMode = "global" // One per node )
type TLSCertificate ¶
type TLSCertificate struct {
ID string // Unique identifier
Name string // Certificate name (e.g., "example-com-cert")
Hosts []string // Hostnames covered by this cert (e.g., ["example.com", "*.example.com"])
CertPEM []byte // Certificate in PEM format
KeyPEM []byte // Private key in PEM format (encrypted in storage)
Issuer string // Certificate issuer (e.g., "Let's Encrypt", "self-signed", "manual")
NotBefore time.Time // Certificate valid from
NotAfter time.Time // Certificate valid until
AutoRenew bool // Enable automatic renewal (M7.3)
Labels map[string]string // Labels for organization
CreatedAt time.Time
UpdatedAt time.Time
}
TLSCertificate represents a TLS certificate for ingress
type UpdateConfig ¶
type UpdateConfig struct {
Parallelism int // How many containers to update simultaneously
Delay time.Duration // Delay between batches
FailureAction string // "pause", "rollback", "continue"
MaxSurge int // Max extra containers during update (default: 1)
HealthCheckGracePeriod time.Duration // Wait time for health checks (default: 30s)
CanaryWeight int // 0-100 (current canary traffic weight)
CanarySteps []int // Promotion steps, e.g., [10, 25, 50, 100]
CanaryStabilityWindow time.Duration // Wait time between canary steps (default: 5m)
BlueGreenGracePeriod time.Duration // Time to keep blue version after switch (default: 5m)
AutoRollbackEnabled bool // Enable automatic rollback on failures
FailureThresholdPercent int // Error rate % to trigger rollback (default: 10)
}
UpdateConfig controls how service updates are performed
type Volume ¶
type Volume struct {
ID string
Name string
Driver string // "local", "nfs", etc.
NodeID string // Node affinity (for local volumes)
MountPath string // Host mount path
Options map[string]string // Driver-specific options
CreatedAt time.Time
}
Volume represents persistent storage
type VolumeMount ¶
type VolumeMount struct {
Source string // Volume name
Target string // Container path
ReadOnly bool
}
VolumeMount defines a volume mount point