proxy

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Pinned by version and multi-platform OCI digest. Update deliberately after
	// reviewing Caddy release notes and the official-image manifest.
	CaddyImage         = "docker.io/library/caddy:2.11.4-alpine@sha256:5f5c8640aae01df9654968d946d8f1a56c497f1dd5c5cda4cf95ab7c14d58648"
	CaddyContainerName = "azud-proxy"
	CaddyAdminPort     = 2019
	CaddyHTTPPort      = 80
	CaddyHTTPSPort     = 443

	// CaddyConfigFileName is the name of the Caddy config file.
	CaddyConfigFileName = "caddy-config.json"

	// CaddyLockFileName is the name of the Caddy lock file.
	CaddyLockFileName = "caddy.lock"

	CaddyLockTimeout = 120 * time.Second
)

Variables

This section is empty.

Functions

func CaddyConfigDir

func CaddyConfigDir(user string) string

CaddyConfigDir returns the Caddy config directory for the given user.

func CaddyConfigFile

func CaddyConfigFile(user string) string

CaddyConfigFile returns the path to the Caddy config file for the given user.

func CaddyLockFile

func CaddyLockFile(user string) string

CaddyLockFile returns the path to the Caddy lock file for the given user.

Types

type ActiveHealthCheck

type ActiveHealthCheck struct {
	Path     string              `json:"path,omitempty"`
	Port     int                 `json:"port,omitempty"`
	Interval string              `json:"interval,omitempty"`
	Timeout  string              `json:"timeout,omitempty"`
	Headers  map[string][]string `json:"headers,omitempty"`
}

ActiveHealthCheck configures active health checking

type AdminConfig

type AdminConfig struct {
	Listen string `json:"listen,omitempty"`
}

AdminConfig configures the Caddy admin API

type AppsConfig

type AppsConfig struct {
	HTTP *HTTPApp `json:"http,omitempty"`
	TLS  *TLSApp  `json:"tls,omitempty"`
}

AppsConfig holds Caddy application configurations

type AutoHTTPSConfig

type AutoHTTPSConfig struct {
	Disable          bool `json:"disable,omitempty"`
	DisableRedirects bool `json:"disable_redirects,omitempty"`
}

AutoHTTPSConfig configures automatic HTTPS behavior.

type CaddyClient

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

CaddyClient manages Caddy proxy via its admin API

func NewCaddyClient

func NewCaddyClient(sshClient *ssh.Client) *CaddyClient

NewCaddyClient creates a new Caddy client

func (*CaddyClient) AddUpstream

func (c *CaddyClient) AddUpstream(host, serverName string, routeIndex int, upstream *Upstream) error

AddUpstream adds an upstream to a route

func (*CaddyClient) GetConfig

func (c *CaddyClient) GetConfig(host string) (*CaddyConfig, error)

GetConfig retrieves the current Caddy configuration

func (*CaddyClient) GetUpstreamRequestCount

func (c *CaddyClient) GetUpstreamRequestCount(host, upstreamAddr string) (int, error)

GetUpstreamRequestCount returns the number of active requests for a specific upstream address (e.g., "my-app:3000"). Returns 0 if the upstream is not found (already removed).

func (*CaddyClient) GetUpstreamStatuses

func (c *CaddyClient) GetUpstreamStatuses(host string) ([]UpstreamStatus, error)

GetUpstreamStatuses queries Caddy's admin API for all upstream statuses. Returns the active request counts and health status per upstream.

func (*CaddyClient) LoadConfig

func (c *CaddyClient) LoadConfig(host string, config *CaddyConfig) error

LoadConfig loads a configuration from a path

func (*CaddyClient) RemoveUpstream

func (c *CaddyClient) RemoveUpstream(host, serverName string, routeIndex int, dial string) error

RemoveUpstream removes an upstream from a route

func (*CaddyClient) SetConfig

func (c *CaddyClient) SetConfig(host string, config *CaddyConfig) error

SetConfig sets the full Caddy configuration

func (*CaddyClient) Stop

func (c *CaddyClient) Stop(host string) error

Stop stops the Caddy server

type CaddyConfig

type CaddyConfig struct {
	Admin   *AdminConfig   `json:"admin,omitempty"`
	Apps    *AppsConfig    `json:"apps,omitempty"`
	Logging *LoggingConfig `json:"logging,omitempty"`
}

CaddyConfig represents the full Caddy configuration

type CertificatesConfig

type CertificatesConfig struct {
	LoadPEM []LoadedCertificate `json:"load_pem,omitempty"`
}

CertificatesConfig holds certificate loading configuration

type Encoder

type Encoder struct {
	Format string             `json:"format,omitempty"` // console, json, filter
	Wrap   *Encoder           `json:"wrap,omitempty"`
	Fields map[string]*Filter `json:"fields,omitempty"`
}

Encoder configures log format

type Filter

type Filter struct {
	Filter string `json:"filter,omitempty"`
}

Filter configures a log field filter.

type HTTPApp

type HTTPApp struct {
	Servers map[string]*HTTPServer `json:"servers,omitempty"`
}

HTTPApp configures the HTTP server

type HTTPServer

type HTTPServer struct {
	Listen    []string         `json:"listen,omitempty"`
	Routes    []*Route         `json:"routes,omitempty"`
	Logs      *ServerLogs      `json:"logs,omitempty"`
	AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"`
}

HTTPServer represents an HTTP server configuration

type Handler

type Handler struct {
	Handler   string      `json:"handler"`
	Upstreams []*Upstream `json:"upstreams,omitempty"`

	// For static_response handler
	StatusCode    int                 `json:"status_code,omitempty"`
	StaticHeaders map[string][]string `json:"headers,omitempty"`
	Body          string              `json:"body,omitempty"`

	// For reverse_proxy handler
	LoadBalancing   *LoadBalancing `json:"load_balancing,omitempty"`
	HealthChecks    *HealthChecks  `json:"health_checks,omitempty"`
	ProxyHeaders    *HeadersConfig `json:"header_up,omitempty"`
	Transport       *Transport     `json:"transport,omitempty"`
	FlushInterval   string         `json:"flush_interval,omitempty"`
	BufferRequests  bool           `json:"buffer_requests,omitempty"`
	BufferResponses bool           `json:"buffer_responses,omitempty"`

	// For request_body handler
	MaxSize int64 `json:"max_size,omitempty"`
}

Handler defines how to handle matched requests

type HeaderOps

type HeaderOps struct {
	Set    map[string][]string `json:"set,omitempty"`
	Add    map[string][]string `json:"add,omitempty"`
	Delete []string            `json:"delete,omitempty"`
}

HeaderOps defines header operations

type HeadersConfig

type HeadersConfig struct {
	Request  *HeaderOps `json:"request,omitempty"`
	Response *HeaderOps `json:"response,omitempty"`
}

HeadersConfig configures header manipulation

type HealthChecks

type HealthChecks struct {
	Active  *ActiveHealthCheck  `json:"active,omitempty"`
	Passive *PassiveHealthCheck `json:"passive,omitempty"`
}

HealthChecks configures health checking

type Issuer

type Issuer struct {
	Module string `json:"module,omitempty"` // acme, zerossl, internal
	CA     string `json:"ca,omitempty"`     // For ACME: https://acme-v02.api.letsencrypt.org/directory
	Email  string `json:"email,omitempty"`
}

Issuer configures a certificate issuer

type LoadBalancing

type LoadBalancing struct {
	SelectionPolicy *SelectionPolicy `json:"selection_policy,omitempty"`
}

LoadBalancing configures load balancing

type LoadedCertificate

type LoadedCertificate struct {
	Certificate string   `json:"certificate"` // PEM content of the certificate
	Key         string   `json:"key"`         // PEM content of the private key
	Tags        []string `json:"tags,omitempty"`
}

LoadedCertificate represents a certificate loaded from PEM content

type Log

type Log struct {
	Level   string   `json:"level,omitempty"`
	Writer  *Writer  `json:"writer,omitempty"`
	Encoder *Encoder `json:"encoder,omitempty"`
}

Log configures a logger

type LoggingConfig

type LoggingConfig struct {
	Logs map[string]*Log `json:"logs,omitempty"`
}

LoggingConfig configures logging

type Manager

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

Manager provisions and configures Caddy reverse proxies on remote hosts.

func NewManager

func NewManager(sshClient *ssh.Client, log *output.Logger) *Manager

NewManager creates a new proxy manager. Defaults to root user for state paths.

func NewManagerWithOptions

func NewManagerWithOptions(sshClient *ssh.Client, log *output.Logger, user string, rootful bool, hostPortUpstreams bool) *Manager

NewManagerWithOptions creates a proxy manager with explicit runtime options.

func NewManagerWithUser

func NewManagerWithUser(sshClient *ssh.Client, log *output.Logger, user string) *Manager

NewManagerWithUser creates a new proxy manager with a specific SSH user.

func (*Manager) AddUpstream

func (m *Manager) AddUpstream(host, serviceHost, upstream string) error

AddUpstream adds an upstream to an existing service using route-specific API operations. Falls back to full config replacement on error.

func (*Manager) Boot

func (m *Manager) Boot(host string, config *ProxyConfig) error

Boot starts the Caddy proxy on a host

func (*Manager) BootAll

func (m *Manager) BootAll(hosts []string, config *ProxyConfig) error

BootAll starts the proxy on multiple hosts in parallel.

func (*Manager) DeregisterService

func (m *Manager) DeregisterService(host, serviceHost string) error

DeregisterService removes a service from the proxy using route-specific API operations. Falls back to full config replacement on error.

func (*Manager) DrainUpstream

func (m *Manager) DrainUpstream(host, upstream string, timeout time.Duration) error

DrainUpstream waits for all in-flight requests to the given upstream to complete by polling Caddy's /reverse_proxy/upstreams admin endpoint. The upstream should already have been removed from the route so no new requests are sent to it. The method returns when the active request count reaches zero or the timeout expires.

A minimum grace period of 5 seconds is always applied, even if the upstream is no longer tracked by Caddy, to allow in-transit TCP connections to complete naturally.

func (*Manager) EnsureConfig

func (m *Manager) EnsureConfig(host string) error

EnsureConfig ensures the proxy has TLS/ACME and logging settings applied. Safe to call on every deploy — it reads the running config and updates only the settings layer (TLS, AutoHTTPS, logging) without touching routes.

func (*Manager) GetUpstreamRequestCount

func (m *Manager) GetUpstreamRequestCount(host, upstream string) (int, error)

GetUpstreamRequestCount returns the active request count for an upstream.

func (*Manager) GetUpstreamWeights

func (m *Manager) GetUpstreamWeights(host, serviceHost string) ([]UpstreamWeight, error)

GetUpstreamWeights returns all upstreams with their weights for a service using route-specific API operations.

func (*Manager) Logs

func (m *Manager) Logs(host string, follow bool, tail string) (*ssh.Result, error)

Logs retrieves proxy logs

func (*Manager) LogsStream

func (m *Manager) LogsStream(host string, follow bool, tail string, stdout, stderr io.Writer) error

LogsStream follows proxy logs without buffering an unbounded stream in memory.

func (*Manager) Reboot

func (m *Manager) Reboot(host string, config *ProxyConfig) error

Reboot restarts the Caddy proxy. If config is provided, it is applied after restart so that TLS/ACME changes take effect immediately.

func (*Manager) RegisterService

func (m *Manager) RegisterService(host string, service *ServiceConfig) error

RegisterService registers a service with the proxy using route-specific API operations. If a route for the service host already exists, only that route is updated via a PATCH. Otherwise a new route is appended. This avoids replacing the entire Caddy configuration and prevents race conditions when multiple services are deployed concurrently.

func (*Manager) Remove

func (m *Manager) Remove(host string) error

Remove removes the Caddy proxy container

func (*Manager) RemoveUpstream

func (m *Manager) RemoveUpstream(host, serviceHost, upstream string) error

RemoveUpstream removes an upstream from a service using route-specific API operations. Falls back to full config replacement on error.

func (*Manager) SetCanaryWeights

func (m *Manager) SetCanaryWeights(host, serviceHost, stable string, stableWeight int, canary string, canaryWeight int) error

SetCanaryWeights atomically replaces a two-upstream route with the requested stable/canary percentages and reads it back before success. It rejects extra upstreams so scaling and canary cannot silently produce misleading weights.

func (*Manager) SetProxyConfig

func (m *Manager) SetProxyConfig(config *ProxyConfig)

SetProxyConfig stores the proxy configuration for use when rebuilding the full Caddy config during service registration fallback.

func (*Manager) Status

func (m *Manager) Status(host string) (*ProxyStatus, error)

Status returns the proxy status on a host

func (*Manager) Stop

func (m *Manager) Stop(host string) error

Stop stops the Caddy proxy on a host

type Match

type Match struct {
	Host []string `json:"host,omitempty"`
	Path []string `json:"path,omitempty"`
}

Match defines matching criteria for a route

type PassiveHealthCheck

type PassiveHealthCheck struct {
	FailDuration     string `json:"fail_duration,omitempty"`
	MaxFails         int    `json:"max_fails,omitempty"`
	UnhealthyLatency string `json:"unhealthy_latency,omitempty"`
}

PassiveHealthCheck configures passive health checking

type ProxyConfig

type ProxyConfig struct {
	// Hosts to route to (e.g., myapp.example.com)
	Hosts []string

	// Enable automatic HTTPS via Let's Encrypt
	AutoHTTPS bool

	// Email for Let's Encrypt notifications
	Email string

	// Use Let's Encrypt staging CA (for testing, avoids rate limits)
	Staging bool

	// Redirect HTTP to HTTPS
	SSLRedirect bool

	// Admin API listen address (default: localhost:2019)
	AdminListen string

	// HTTP port (default 80)
	HTTPPort int

	// HTTPS port (default 443)
	HTTPSPort int

	// Custom SSL certificate PEM content (if provided, disables ACME)
	SSLCertificate string

	// Custom SSL private key PEM content
	SSLPrivateKey string

	// Enable access logging (even without header redaction)
	LoggingEnabled bool

	// Request headers to redact from access logs
	RedactRequestHeaders []string

	// Response headers to redact from access logs
	RedactResponseHeaders []string
}

type ProxyStatus

type ProxyStatus struct {
	Host       string
	Running    bool
	Stats      string
	RouteCount int
}

type Route

type Route struct {
	Match    []*Match   `json:"match,omitempty"`
	Handle   []*Handler `json:"handle,omitempty"`
	Terminal bool       `json:"terminal,omitempty"`
}

Route defines a routing rule

type SelectionPolicy

type SelectionPolicy struct {
	Policy string `json:"policy,omitempty"` // round_robin, least_conn, random, first, ip_hash, uri_hash, header
}

SelectionPolicy defines how to select upstreams

type ServerLogs

type ServerLogs struct {
	DefaultLoggerName string `json:"default_logger_name,omitempty"`
}

ServerLogs configures per-server logging

type ServiceConfig

type ServiceConfig struct {
	// Service name
	Name string

	// Hostname for routing
	Host string

	// Additional hostnames for routing
	Hosts []string

	// Upstream addresses (host:port)
	Upstreams []string

	// Health check path for liveness (used by Caddy active health checks)
	HealthPath string

	// Health check interval
	HealthInterval string

	// Health check timeout
	HealthTimeout string

	// Full response timeout (maps to Caddy read_timeout)
	ResponseTimeout string

	// Response header timeout (maps to Caddy response_header_timeout)
	ResponseHeaderTimeout string

	// Forward proxy headers to upstream
	ForwardHeaders bool

	// Buffer request bodies
	BufferRequests bool

	// Buffer responses
	BufferResponses bool

	// Maximum request body size (bytes)
	MaxRequestBody int64

	// Request body buffer size (bytes) when max size is not provided
	BufferMemory int64

	// Enable HTTPS
	HTTPS bool
}

type TLSApp

type TLSApp struct {
	Automation   *TLSAutomation      `json:"automation,omitempty"`
	Certificates *CertificatesConfig `json:"certificates,omitempty"`
}

TLSApp configures TLS/HTTPS

type TLSAutomation

type TLSAutomation struct {
	Policies []*TLSPolicy `json:"policies,omitempty"`
}

TLSAutomation configures automatic certificate management

type TLSPolicy

type TLSPolicy struct {
	Subjects         []string  `json:"subjects,omitempty"`
	Issuers          []*Issuer `json:"issuers,omitempty"`
	OnDemand         bool      `json:"on_demand,omitempty"`
	DisableAutomatic bool      `json:"disable_automatic,omitempty"` // Disable automatic cert management for these subjects
}

TLSPolicy defines a TLS automation policy

type Transport

type Transport struct {
	Protocol              string `json:"protocol,omitempty"`
	ResponseHeaderTimeout string `json:"response_header_timeout,omitempty"`
	ReadTimeout           string `json:"read_timeout,omitempty"`
}

Transport configures the HTTP transport

type Upstream

type Upstream struct {
	Dial string `json:"dial"`
}

Upstream represents a backend server

type UpstreamStatus

type UpstreamStatus struct {
	Address     string `json:"address"`
	Healthy     bool   `json:"healthy"`
	NumRequests int    `json:"num_requests"`
}

UpstreamStatus represents the status of a reverse proxy upstream as reported by Caddy's /reverse_proxy/upstreams admin endpoint.

type UpstreamWeight

type UpstreamWeight struct {
	Dial   string
	Weight int
}

type Writer

type Writer struct {
	Output string `json:"output,omitempty"` // stdout, stderr, file
}

Writer configures log output

Jump to

Keyboard shortcuts

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