ctrlplane

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

Ctrl Plane

A composable Go library for deploying and managing SaaS instances at scale.

Ctrl Plane handles instance lifecycle, zero-downtime deployments, health monitoring, secret management, traffic routing, and multi-tenant isolation. You bring a cloud provider and an auth system. Ctrl Plane wires everything together.

Overview

Ctrl Plane is a library, not a framework. You import Go packages, configure them with functional options, and embed them into your own application. It runs standalone or as a Forge extension.

cp, err := app.New(
    app.WithStore(postgresStore),
    app.WithProvider("k8s", kubernetesProvider),
    app.WithAuth(myAuthProvider),
)

cp.Start(ctx)
http.ListenAndServe(":8080", api.New(cp).Handler())

What it does:

  • Provisions and manages tenant instances across any cloud provider (Docker, Kubernetes, AWS ECS, Fly.io, etc.)
  • Deploys with rolling, blue-green, canary, or recreate strategies
  • Runs HTTP, TCP, gRPC, and command-based health checks
  • Manages custom domains, TLS certificates, and traffic routing
  • Stores secrets with pluggable vault backends
  • Publishes lifecycle events and delivers webhooks
  • Collects metrics, logs, traces, and resource snapshots
  • Enforces tenant quotas and records audit trails

Install

go get github.com/xraph/ctrlplane@latest

Requires Go 1.22 or later.

Quick start

A minimal server with an in-memory store and Docker provider:

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"

    "github.com/xraph/ctrlplane/api"
    "github.com/xraph/ctrlplane/app"
    "github.com/xraph/ctrlplane/auth"
    "github.com/xraph/ctrlplane/provider/docker"
    "github.com/xraph/ctrlplane/store/memory"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()

    memStore := memory.New()
    dockerProv, err := docker.New(docker.Config{
        Host: "unix:///var/run/docker.sock",
    })
    if err != nil {
        log.Fatal(err)
    }

    cp, err := app.New(
        app.WithStore(memStore),
        app.WithAuth(auth.NewNoopProvider()),
        app.WithProvider("docker", dockerProv),
        app.WithDefaultProvider("docker"),
    )
    if err != nil {
        log.Fatal(err)
    }

    if err := cp.Start(ctx); err != nil {
        log.Fatal(err)
    }
    defer cp.Stop(context.Background())

    srv := &http.Server{
        Addr:              ":8080",
        Handler:           api.New(cp).Handler(),
        ReadHeaderTimeout: 10 * time.Second,
    }

    go func() {
        <-ctx.Done()
        srv.Shutdown(context.Background())
    }()

    log.Println("ctrlplane listening on :8080")
    if err := srv.ListenAndServe(); err != http.ErrServerClosed {
        log.Fatal(err)
    }
}

Create a tenant:

curl -X POST http://localhost:8080/v1/admin/tenants \
  -H "Content-Type: application/json" \
  -d '{"name": "Acme Corp", "slug": "acme", "plan": "pro"}'

Create an instance:

curl -X POST http://localhost:8080/v1/instances \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "ten_...",
    "name": "web-app",
    "image": "nginx:alpine",
    "provider_name": "docker",
    "resources": {"cpu_millis": 500, "memory_mb": 256},
    "ports": [{"container_port": 80, "protocol": "tcp"}]
  }'

Package structure

ctrlplane.go          Root package (Entity, Config, sentinel errors)
id/                      TypeID-based identifiers (prefix-qualified, UUIDv7)
auth/                    Authentication and authorization interface
instance/                Instance lifecycle management
deploy/                  Deployments, releases, and strategies
health/                  Health checks (HTTP, TCP, gRPC, command)
network/                 Domains, routes, TLS certificates
secrets/                 Secret management with pluggable vault
telemetry/               Metrics, logs, traces, resource snapshots
admin/                   Tenant management, quotas, audit
event/                   Event bus and webhooks
worker/                  Background task scheduler
provider/                Cloud provider abstraction
  docker/                Docker provider (implemented)
  kubernetes/            Kubernetes (interface defined)
  aws/, gcp/, azure/     Cloud providers (interface defined)
  nomad/, fly/           Additional providers (interface defined)
store/                   Persistence layer
  memory/                In-memory (tests and development)
  sqlite/                SQLite (standalone deployments)
  postgres/              PostgreSQL (production)
api/                     HTTP handlers and middleware
app/                     Root orchestrator (wires everything together)
extension/               Forge extension adapter
cmd/ctrlplane/        Reference binary

Key interfaces

Every subsystem is defined by Go interfaces. Swap out any piece with your own implementation.

Interface Package Purpose
provider.Provider provider/ Cloud orchestrator abstraction
instance.Service instance/ Instance CRUD and lifecycle
deploy.Service deploy/ Deployment orchestration
deploy.Strategy deploy/ Pluggable deployment strategy
health.Checker health/ Health check implementation
network.Router network/ Traffic routing abstraction
secrets.Vault secrets/ Backend secret storage
telemetry.Collector telemetry/ Custom telemetry source
event.Bus event/ Event publish/subscribe
auth.Provider auth/ Authentication and authorization
store.Store store/ Aggregate persistence

Forge extension

Mount Ctrl Plane into a Forge application:

app := forge.New()
app.Use(cpext.New(
    cpext.WithProvider("k8s", kubernetesProvider),
    cpext.WithAuthProvider(authsomeAdapter),
))
app.Run()

Documentation

Full documentation is available in the docs/ directory and covers architecture, core concepts, every subsystem, guides for writing custom providers and deployment strategies, and the complete HTTP API reference.

Development

go build ./...
go test ./...
golangci-lint run ./...
goimports -w -local github.com/xraph/ctrlplane .

License

See LICENSE for details.

Documentation

Overview

Package ctrlplane provides a composable control plane library for deploying and managing SaaS instances at scale. It offers a unified API for provisioning, deployment, health monitoring, and lifecycle management across multiple cloud providers and orchestrators.

CtrlPlane is designed as a library-first package that can be used standalone or mounted into a Forge application as an extension.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound indicates the requested resource does not exist.
	ErrNotFound = errors.New("ctrlplane: resource not found")

	// ErrAlreadyExists indicates a resource with the same identity already exists.
	ErrAlreadyExists = errors.New("ctrlplane: resource already exists")

	// ErrInvalidState indicates an invalid state transition was attempted.
	ErrInvalidState = errors.New("ctrlplane: invalid state transition")

	// ErrProviderNotFound indicates the named provider is not registered.
	ErrProviderNotFound = errors.New("ctrlplane: provider not registered")

	// ErrUnauthorized indicates the request lacks valid authentication credentials.
	ErrUnauthorized = errors.New("ctrlplane: unauthorized")

	// ErrForbidden indicates the authenticated identity lacks permission.
	ErrForbidden = errors.New("ctrlplane: forbidden")

	// ErrQuotaExceeded indicates the tenant has exceeded their resource quota.
	ErrQuotaExceeded = errors.New("ctrlplane: quota exceeded")

	// ErrProviderUnavail indicates the provider is temporarily unavailable.
	ErrProviderUnavail = errors.New("ctrlplane: provider unavailable")

	// ErrDeploymentFailed indicates a deployment operation failed.
	ErrDeploymentFailed = errors.New("ctrlplane: deployment failed")

	// ErrHealthCheckFailed indicates a health check did not pass.
	ErrHealthCheckFailed = errors.New("ctrlplane: health check failed")

	// ErrRollbackFailed indicates a rollback operation failed.
	ErrRollbackFailed = errors.New("ctrlplane: rollback failed")

	// ErrInvalidConfig indicates the provided configuration is invalid.
	ErrInvalidConfig = errors.New("ctrlplane: invalid configuration")
)

Sentinel errors returned by ctrlplane operations. Use errors.Is to check for these values.

Functions

This section is empty.

Types

type Config

type Config struct {
	// DatabaseURL is the database connection string.
	DatabaseURL string `env:"CP_DATABASE_URL" json:"database_url"`

	// DefaultProvider is the provider name used when none is specified.
	DefaultProvider string `env:"CP_DEFAULT_PROVIDER" json:"default_provider"`

	// HealthInterval is the default health check interval for all instances.
	HealthInterval time.Duration `default:"30s" env:"CP_HEALTH_INTERVAL" json:"health_interval"`

	// TelemetryFlushInterval is how often telemetry data is flushed.
	TelemetryFlushInterval time.Duration `default:"10s" env:"CP_TELEMETRY_FLUSH" json:"telemetry_flush_interval"`

	// MaxInstancesPerTenant is the default quota for instances per tenant.
	// A value of 0 means unlimited.
	MaxInstancesPerTenant int `default:"0" env:"CP_MAX_INSTANCES" json:"max_instances_per_tenant"`

	// AuditEnabled controls whether audit logging is active.
	AuditEnabled bool `default:"true" env:"CP_AUDIT_ENABLED" json:"audit_enabled"`
}

Config holds global configuration for the CtrlPlane.

type Entity

type Entity struct {
	ID        id.ID     `db:"id"         json:"id"`
	CreatedAt time.Time `db:"created_at" json:"created_at"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

Entity is the base type embedded by all ctrlplane domain objects. It provides a unique identifier and creation/update timestamps.

func NewEntity

func NewEntity(prefix id.Prefix) Entity

NewEntity creates an Entity with a fresh ID and UTC timestamps. The prefix determines the entity type encoded in the ID.

Directories

Path Synopsis
Package admin provides system-level and tenant-level management for the ctrlplane.
Package admin provides system-level and tenant-level management for the ctrlplane.
Package api provides Forge-style HTTP handlers and middleware for the ctrlplane REST API.
Package api provides Forge-style HTTP handlers and middleware for the ctrlplane REST API.
Package app provides the CtrlPlane root orchestrator that wires all subsystems together.
Package app provides the CtrlPlane root orchestrator that wires all subsystems together.
Package auth provides the authentication and authorization abstraction for the control plane.
Package auth provides the authentication and authorization abstraction for the control plane.
cmd
controlplane command
Package deploy defines the deployment and release domain entities, the deployment service interface, strategy abstraction, and persistence store for tracking deployments and immutable release snapshots.
Package deploy defines the deployment and release domain entities, the deployment service interface, strategy abstraction, and persistence store for tracking deployments and immutable release snapshots.
strategies
Package strategies provides built-in deployment strategy implementations.
Package strategies provides built-in deployment strategy implementations.
Package event provides the event bus abstraction for lifecycle hooks and asynchronous communication between ctrlplane subsystems.
Package event provides the event bus abstraction for lifecycle hooks and asynchronous communication between ctrlplane subsystems.
examples
saas-platform command
Package main demonstrates a complete SaaS management platform built with Ctrl Plane and Forge.
Package main demonstrates a complete SaaS management platform built with Ctrl Plane and Forge.
Package extension provides a Forge extension adapter for the ctrlplane.
Package extension provides a Forge extension adapter for the ctrlplane.
Package health defines the health checking subsystem including check configuration, result tracking, aggregate instance health, and the pluggable Checker interface for custom check types.
Package health defines the health checking subsystem including check configuration, result tracking, aggregate instance health, and the pluggable Checker interface for custom check types.
Package id provides the primary identifier type for all ctrlplane entities.
Package id provides the primary identifier type for all ctrlplane entities.
Package instance defines the Instance domain entity, lifecycle management service interface, persistence store interface, and state machine for instance state transitions.
Package instance defines the Instance domain entity, lifecycle management service interface, persistence store interface, and state machine for instance state transitions.
Package network manages routing, custom domains, TLS certificates, and service discovery for ctrlplane instances.
Package network manages routing, custom domains, TLS certificates, and service discovery for ctrlplane instances.
Package provider defines the unified interface for infrastructure operations.
Package provider defines the unified interface for infrastructure operations.
docker
Package docker implements a Docker-based infrastructure provider for the ctrlplane.
Package docker implements a Docker-based infrastructure provider for the ctrlplane.
Package secrets manages encrypted secrets for ctrlplane instances.
Package secrets manages encrypted secrets for ctrlplane instances.
Package store defines the aggregate persistence interface that composes all domain-specific store interfaces.
Package store defines the aggregate persistence interface that composes all domain-specific store interfaces.
badger
Package badger provides a Badger DB implementation of the store.Store interface.
Package badger provides a Badger DB implementation of the store.Store interface.
bun
Package bun provides a Bun ORM implementation of the store.Store interface.
Package bun provides a Bun ORM implementation of the store.Store interface.
memory
Package memory provides an in-memory implementation of the store.Store interface.
Package memory provides an in-memory implementation of the store.Store interface.
mongo
Package mongo provides a MongoDB implementation of the store.Store interface.
Package mongo provides a MongoDB implementation of the store.Store interface.
postgres
Package postgres implements the ctrlplane store interface using PostgreSQL.
Package postgres implements the ctrlplane store interface using PostgreSQL.
sqlite
Package sqlite implements the ctrlplane store interface using SQLite.
Package sqlite implements the ctrlplane store interface using SQLite.
Package telemetry defines the telemetry subsystem for metrics, logs, traces, and resource snapshots.
Package telemetry defines the telemetry subsystem for metrics, logs, traces, and resource snapshots.
Package worker provides background task scheduling for the control plane.
Package worker provides background task scheduling for the control plane.

Jump to

Keyboard shortcuts

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