Documentation
¶
Index ¶
- Constants
- func BuildHTTPRouteJSON(route CompiledHTTPRoute) (json.RawMessage, error)
- func BuildHTTPRoutesJSON(routes []CompiledHTTPRoute) ([]json.RawMessage, error)
- func BuildTCPRouteJSON(route CompiledTCPRoute) (json.RawMessage, error)
- func BuildTCPServerJSON(port int, routes []CompiledTCPRoute) (json.RawMessage, error)
- func GroupTCPRoutesByPort(routes []CompiledTCPRoute) map[int][]CompiledTCPRoute
- type AdminConsul
- type ChangeType
- type CompiledConfig
- type CompiledHTTPRoute
- type CompiledTCPRoute
- type Conflict
- type ConflictType
- type ConsulProxyHandler
- func (ConsulProxyHandler) CaddyModule() caddy.ModuleInfo
- func (h *ConsulProxyHandler) Provision(ctx caddy.Context) error
- func (h *ConsulProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error
- func (h *ConsulProxyHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- type ConsulRouter
- func (ConsulRouter) CaddyModule() caddy.ModuleInfo
- func (cr *ConsulRouter) Cleanup() error
- func (cr *ConsulRouter) Provision(ctx caddy.Context) error
- func (cr *ConsulRouter) RouteTable() *RouteTable
- func (cr *ConsulRouter) Start() error
- func (cr *ConsulRouter) Stop() error
- func (cr *ConsulRouter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
- type ConsulWatcher
- func (w *ConsulWatcher) CatalogIndex() uint64
- func (w *ConsulWatcher) HealthStateIndex() uint64
- func (w *ConsulWatcher) PassingChecks() map[string][]string
- func (w *ConsulWatcher) RestoreState(catalogIndex uint64, healthStateIndex uint64, ...)
- func (w *ConsulWatcher) Start()
- func (w *ConsulWatcher) Stop()
- type HealthPolicy
- type MetricsCollector
- type Protocol
- type Reconciler
- type RouteCompiler
- type RouteDefinition
- type RouteTable
- type ServiceChange
- type ServiceInstance
- type ServiceRegistrar
- type ServiceState
- type SidecarResolver
- type Upstream
- type UpstreamManager
- type UpstreamMode
Constants ¶
const ( DefaultConsulAddr = "127.0.0.1:8500" DefaultConsulScheme = "http" DefaultHealthPolicy = "passing" DefaultConflictPolicy = "reject" DefaultServiceProxyEnable = true DefaultConnectProxyEnable = false DefaultDebounce = "500ms" DefaultConnectAutoRegister = true DefaultPollInterval = "50ms" DefaultFullSyncInterval = "5m" DefaultCaddyAdminAPI = "localhost:2019" DefaultServiceTag = "caddy-consul" DefaultConnectTag = "caddy-consul-connect" DefaultConnectPortStart = 19000 DefaultConnectPortEnd = 29000 DefaultL4Mode = "global" // MaxServiceNameLen is the max length for a Consul service name (DNS label). MaxServiceNameLen = 63 )
Variables ¶
This section is empty.
Functions ¶
func BuildHTTPRouteJSON ¶
func BuildHTTPRouteJSON(route CompiledHTTPRoute) (json.RawMessage, error)
BuildHTTPRouteJSON builds the Caddy JSON config fragment for an HTTP route.
func BuildHTTPRoutesJSON ¶
func BuildHTTPRoutesJSON(routes []CompiledHTTPRoute) ([]json.RawMessage, error)
BuildHTTPRoutesJSON builds an array of Caddy JSON route configs for all HTTP routes.
func BuildTCPRouteJSON ¶
func BuildTCPRouteJSON(route CompiledTCPRoute) (json.RawMessage, error)
BuildTCPRouteJSON builds the Caddy L4 JSON config fragment for a TCP route.
func BuildTCPServerJSON ¶
func BuildTCPServerJSON(port int, routes []CompiledTCPRoute) (json.RawMessage, error)
BuildTCPServerJSON builds a complete L4 server config for a given port with its routes.
func GroupTCPRoutesByPort ¶
func GroupTCPRoutesByPort(routes []CompiledTCPRoute) map[int][]CompiledTCPRoute
GroupTCPRoutesByPort groups compiled TCP routes by their port number.
Types ¶
type AdminConsul ¶
type AdminConsul struct {
// contains filtered or unexported fields
}
AdminConsul is a Caddy admin module that exposes consul metrics and debug endpoints.
func (AdminConsul) CaddyModule ¶
func (AdminConsul) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (*AdminConsul) Cleanup ¶
func (ac *AdminConsul) Cleanup() error
Cleanup cleans up the admin handler.
func (*AdminConsul) Provision ¶
func (ac *AdminConsul) Provision(ctx caddy.Context) error
Provision sets up the admin consul handler.
func (*AdminConsul) Routes ¶
func (ac *AdminConsul) Routes() []caddy.AdminRoute
Routes returns the routes for the admin API.
type ChangeType ¶
type ChangeType string
ChangeType represents the type of service change.
const ( ChangeAdded ChangeType = "added" ChangeUpdated ChangeType = "updated" ChangeRemoved ChangeType = "removed" )
type CompiledConfig ¶
type CompiledConfig struct {
HTTPRoutes []CompiledHTTPRoute
TCPRoutes []CompiledTCPRoute
Conflicts []Conflict
Warnings []string
}
CompiledConfig holds the result of route compilation.
type CompiledHTTPRoute ¶
type CompiledHTTPRoute struct {
Host string
Path string
Upstreams []Upstream
StripPrefix bool
ServiceName string
Via string // routing tag for X-Caddy-Consul-Via response header
RedirectCode int
RedirectURL string
}
CompiledHTTPRoute is a Consul-managed HTTP route ready for injection into Caddy config.
type CompiledTCPRoute ¶
type CompiledTCPRoute struct {
Port int
SNI string
Upstreams []Upstream
Passthrough bool
ServiceName string
}
CompiledTCPRoute is a Consul-managed TCP route ready for injection into Caddy config.
type Conflict ¶
type Conflict struct {
Type ConflictType
Winner *RouteDefinition
Loser *RouteDefinition
Reason string
}
Conflict represents a detected route conflict.
type ConflictType ¶
type ConflictType string
ConflictType represents the type of route conflict.
const ( ConflictDuplicateHostPath ConflictType = "duplicate_host_path" ConflictDuplicatePortSNI ConflictType = "duplicate_port_sni" ConflictConflictingTLS ConflictType = "conflicting_tls" ConflictStaticWins ConflictType = "static_wins" )
type ConsulProxyHandler ¶ added in v0.0.5
type ConsulProxyHandler struct {
// contains filtered or unexported fields
}
ConsulProxyHandler is a Caddy HTTP handler that dynamically routes requests based on Consul service discovery. It reads from an in-memory route table shared with the consul app module — no admin API calls, no config reloads.
func (ConsulProxyHandler) CaddyModule ¶ added in v0.0.5
func (ConsulProxyHandler) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (*ConsulProxyHandler) Provision ¶ added in v0.0.5
func (h *ConsulProxyHandler) Provision(ctx caddy.Context) error
Provision sets up the handler by getting a reference to the consul app's route table.
func (*ConsulProxyHandler) ServeHTTP ¶ added in v0.0.5
func (h *ConsulProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error
ServeHTTP handles an HTTP request by matching it against the dynamic route table.
func (*ConsulProxyHandler) UnmarshalCaddyfile ¶ added in v0.0.5
func (h *ConsulProxyHandler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile parses the consul_proxy directive. It takes no arguments.
consul_proxy
type ConsulRouter ¶
type ConsulRouter struct {
// Consul connection
ConsulAddr string `json:"address,omitempty"`
ConsulToken string `json:"token,omitempty"`
ConsulScheme string `json:"scheme,omitempty"`
ConsulDC string `json:"datacenter,omitempty"`
// TLS to Consul
ConsulTLSCA string `json:"tls_ca,omitempty"`
ConsulTLSCert string `json:"tls_cert,omitempty"`
ConsulTLSKey string `json:"tls_key,omitempty"`
ConsulTLSSkipVerify bool `json:"insecure_skip_verify,omitempty"`
// Behavior
ServiceProxyEnable *bool `json:"service_proxy_enable,omitempty"`
HealthPolicy string `json:"health_policy,omitempty"`
ConflictPolicy string `json:"conflict_policy,omitempty"`
ConnectProxyEnable *bool `json:"connect_proxy_enable,omitempty"`
DebounceDuration string `json:"debounce_duration,omitempty"`
PollInterval string `json:"poll_interval,omitempty"`
FullSyncInterval string `json:"full_sync_interval,omitempty"`
// Connect
ConnectServiceName string `json:"connect_service_name,omitempty"`
ConnectAutoRegister *bool `json:"connect_auto_register,omitempty"`
// Caddy admin API
CaddyAdminAPI string `json:"caddy_admin_api,omitempty"`
// Service discovery tags
ServiceTag string `json:"service_tag,omitempty"`
ConnectTag string `json:"connect_tag,omitempty"`
// Connect port range for dynamic sidecar upstreams
ConnectPortStart int `json:"connect_port_range_start,omitempty"`
ConnectPortEnd int `json:"connect_port_range_end,omitempty"`
// Data directory for runtime state (persisted across reloads)
DataDir string `json:"data_dir,omitempty"`
// Metrics
Metrics string `json:"metrics,omitempty"`
// Layer 4 mode: "global" (default) or "node"
// In "node" mode, TCP/L4 routes are only materialized for services that
// have at least one healthy instance on the local Consul node.
L4Mode string `json:"l4_mode,omitempty"`
L4NodeHostname string `json:"l4_node_hostname,omitempty"` // explicit override for node identity
// contains filtered or unexported fields
}
ConsulRouter is a Caddy app that dynamically configures HTTP and TCP/TLS routing from Consul service registrations.
func (ConsulRouter) CaddyModule ¶
func (ConsulRouter) CaddyModule() caddy.ModuleInfo
CaddyModule returns the Caddy module information.
func (*ConsulRouter) Provision ¶
func (cr *ConsulRouter) Provision(ctx caddy.Context) error
Provision sets up the ConsulRouter.
func (*ConsulRouter) RouteTable ¶ added in v0.0.5
func (cr *ConsulRouter) RouteTable() *RouteTable
RouteTable returns the shared route table for the consul_proxy handler.
func (*ConsulRouter) Start ¶
func (cr *ConsulRouter) Start() error
Start begins the Consul watcher. This is non-blocking. The admin API connectivity is verified lazily on the first reconciliation attempt, with retries, to avoid a chicken-and-egg problem during Caddy startup.
func (*ConsulRouter) Stop ¶
func (cr *ConsulRouter) Stop() error
Stop gracefully shuts down the Consul watcher and cert manager. Note: we intentionally do NOT deregister from Consul here. Stop() is called on every config reload (via admin API PATCH), not just on final shutdown. Deregistering would cause a registration gap between the old and new app instances. The registration persists and the TTL will expire naturally.
func (*ConsulRouter) UnmarshalCaddyfile ¶
func (cr *ConsulRouter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error
UnmarshalCaddyfile sets up the ConsulRouter from Caddyfile tokens.
consul {
address 127.0.0.1:8500
token {env.CONSUL_HTTP_TOKEN}
scheme https
datacenter dc1
tls_ca /path/to/ca.pem
tls_cert /path/to/cert.pem
tls_key /path/to/key.pem
insecure_skip_verify false
service_proxy_enable true
health_policy passing
conflict_policy reject
connect_proxy_enable false
connect_service_name my-ingress
connect_auto_register true
poll_interval 50ms
full_sync_interval 5m
debounce 500ms
caddy_admin_api localhost:2019
service_tag caddy-consul
connect_tag caddy-consul-connect
connect_port_range_start 19000
connect_port_range_end 29000
data_dir /var/lib/caddy-consul
metrics /metrics/consul
l4_mode node
l4_node_hostname worker-03.dc1
}
type ConsulWatcher ¶
type ConsulWatcher struct {
// contains filtered or unexported fields
}
ConsulWatcher watches Consul for service changes using two blocking queries:
- /v1/catalog/services — detects service add/remove
- /v1/health/state/passing — detects health changes across ALL services
This architecture uses 2 connections regardless of service count, scaling to 10,000+ services without overwhelming the Consul agent.
func NewConsulWatcher ¶
func NewConsulWatcher( client *consul.Client, logger *zap.Logger, healthPolicy HealthPolicy, debounce time.Duration, pollInterval time.Duration, fullSyncInterval time.Duration, serviceTag string, connectTag string, onChange func([]ServiceChange, map[string]*ServiceState), ) *ConsulWatcher
NewConsulWatcher creates a new ConsulWatcher.
func (*ConsulWatcher) CatalogIndex ¶ added in v0.0.5
func (w *ConsulWatcher) CatalogIndex() uint64
CatalogIndex returns the current catalog blocking query index (exported for state persistence).
func (*ConsulWatcher) HealthStateIndex ¶ added in v0.0.5
func (w *ConsulWatcher) HealthStateIndex() uint64
HealthStateIndex returns the current health state blocking query index.
func (*ConsulWatcher) PassingChecks ¶ added in v0.0.5
func (w *ConsulWatcher) PassingChecks() map[string][]string
PassingChecks returns the current passing checks map for state persistence.
func (*ConsulWatcher) RestoreState ¶ added in v0.0.5
func (w *ConsulWatcher) RestoreState(catalogIndex uint64, healthStateIndex uint64, services map[string]*persistedServiceState, passingChecks map[string][]string)
RestoreState restores watcher state from a previous run.
func (*ConsulWatcher) Start ¶
func (w *ConsulWatcher) Start()
Start begins watching Consul for service changes. Non-blocking. Launches 3 goroutines: catalog watcher, health state watcher, and periodic full sync.
func (*ConsulWatcher) Stop ¶
func (w *ConsulWatcher) Stop()
Stop gracefully stops all watchers. Safe to call multiple times.
type HealthPolicy ¶
type HealthPolicy int
HealthPolicy controls which instances are considered routable.
const ( HealthPolicyPassing HealthPolicy = iota HealthPolicyWarning HealthPolicyAny )
type MetricsCollector ¶
type MetricsCollector struct {
ServicesTotal prometheus.Gauge
RoutesTotal *prometheus.GaugeVec
UpstreamsHealthy *prometheus.GaugeVec
UpstreamsTotal *prometheus.GaugeVec
ReconcileDuration prometheus.Histogram
ReconcileErrors prometheus.Counter
WatcherErrors prometheus.Counter
ConflictsTotal *prometheus.CounterVec
DebounceEvents prometheus.Counter
// contains filtered or unexported fields
}
MetricsCollector handles all metrics collection for the caddy-consul plugin.
func GetMetrics ¶
func GetMetrics() *MetricsCollector
GetMetrics returns the global MetricsCollector, or nil if not initialized.
func GetOrCreateGlobalMetrics ¶
func GetOrCreateGlobalMetrics(logger *zap.Logger) *MetricsCollector
GetOrCreateGlobalMetrics returns the global MetricsCollector, creating it if needed.
func (*MetricsCollector) ServeHTTP ¶
func (m *MetricsCollector) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP handles Prometheus metrics scraping.
type Reconciler ¶
type Reconciler struct {
// contains filtered or unexported fields
}
Reconciler applies compiled TCP routes to Caddy's running config via the Admin API. HTTP routes are handled in-memory by the consul_proxy handler and do NOT use this.
TCP routes require the admin API because new listeners (ports) cannot be created without a config change. TCP route changes are infrequent (only when TCP services are added/removed). TCP state is persisted across reloads to prevent cascading reload cycles.
func NewReconciler ¶
func NewReconciler(logger *zap.Logger, adminAddr string) *Reconciler
NewReconciler creates a new Reconciler targeting the given Caddy admin address.
func (*Reconciler) ApplyTCP ¶ added in v0.0.5
func (r *Reconciler) ApplyTCP(compiled *CompiledConfig) error
ApplyTCP reconciles TCP routes with Caddy's live L4 config via the admin API. HTTP routes are handled in-memory by the consul_proxy handler and do not use this.
func (*Reconciler) RestoreTCPState ¶ added in v0.0.5
func (r *Reconciler) RestoreTCPState(hashes map[string]string, names []string)
RestoreTCPState restores TCP reconciler state from a previous reload cycle. This prevents the reconciler from re-applying identical TCP servers and triggering another unnecessary config reload.
After restoring, it verifies that the servers actually exist in the live Caddy config. If any are missing (e.g., after a reload wiped them), the hashes are cleared so the reconciler will re-create them.
func (*Reconciler) TCPState ¶ added in v0.0.5
func (r *Reconciler) TCPState() (hashes map[string]string, names []string)
TCPState returns the current TCP state for persistence across reloads.
func (*Reconciler) VerifyTCPServersExist ¶ added in v0.0.5
func (r *Reconciler) VerifyTCPServersExist()
VerifyTCPServersExist checks that persisted TCP servers actually exist in the live Caddy config. If any are missing, clears the hash state so they get re-created on the next reconciliation.
type RouteCompiler ¶
type RouteCompiler struct {
// contains filtered or unexported fields
}
RouteCompiler converts RouteDefinitions into compiled Caddy config structures.
func NewRouteCompiler ¶
func NewRouteCompiler(logger *zap.Logger) *RouteCompiler
NewRouteCompiler creates a new RouteCompiler.
func (*RouteCompiler) Compile ¶
func (rc *RouteCompiler) Compile(routes []RouteDefinition) *CompiledConfig
Compile takes a set of RouteDefinitions and produces a CompiledConfig. It groups routes by protocol, detects conflicts, and applies resolution rules.
type RouteDefinition ¶
type RouteDefinition struct {
ServiceName string
Protocol Protocol
Host string
Path string
Port int
UpstreamMode UpstreamMode
Priority int
Weight int
StripPrefix bool
Enabled bool
Upstreams []Upstream
Via string // routing tag value for X-Caddy-Consul-Via header
RedirectCode int // HTTP redirect status code (301, 302, etc.); 0 = not a redirect
RedirectURL string // redirect target URL template (may contain {http.request.uri})
}
RouteDefinition holds parsed routing instructions from Consul metadata/tags.
func FilterTCPRoutesByNode ¶ added in v0.0.7
func FilterTCPRoutesByNode(routes []RouteDefinition, nodeName string) []RouteDefinition
FilterTCPRoutesByNode returns only routes that should be materialized on the given node. TCP/TLS-passthrough routes are kept only if at least one upstream runs on nodeName. When kept, ALL upstreams are preserved (not just local ones) so Caddy can load-balance across the full set. HTTP/HTTPS routes pass through unchanged. If nodeName is empty, all routes pass through (safety fallback).
func ParseServiceRoutes ¶
func ParseServiceRoutes(svc *ServiceState, serviceTag, connectTag string, logger *zap.Logger) []RouteDefinition
ParseServiceRoutes extracts RouteDefinitions from a service's metadata and tags.
Each instance is processed independently — its effective metadata is built by merging service-level meta (svc.Meta) with instance-level meta (inst.Meta wins). Routes are parsed from that per-instance metadata, and the instance becomes the sole upstream for its own routes. Instances that produce identical route definitions (same host, path, protocol, port, etc.) are grouped into one route with multiple upstreams for load balancing.
Precedence per instance: indexed (caddy-route-N-*) > non-indexed (caddy-*) > Fabio (urlprefix-).
An instance is only considered if it has the serviceTag/connectTag in its Tags, or has caddy-* keys in its own Meta, or has urlprefix-* in its own Tags.
func (*RouteDefinition) IsRedirect ¶ added in v0.0.2
func (rd *RouteDefinition) IsRedirect() bool
IsRedirect returns true if this route is an HTTP redirect (not a proxy).
type RouteTable ¶ added in v0.0.5
type RouteTable struct {
// contains filtered or unexported fields
}
RouteTable is a thread-safe in-memory HTTP route table shared between the consul app (writer) and the consul_proxy handler (reader). It is updated whenever the watcher detects service changes and the compiler produces new compiled routes. The handler reads from it on every HTTP request.
func NewRouteTable ¶ added in v0.0.5
func NewRouteTable() *RouteTable
NewRouteTable creates an empty RouteTable.
func (*RouteTable) Len ¶ added in v0.0.5
func (rt *RouteTable) Len() int
Len returns the number of routes in the table.
func (*RouteTable) Match ¶ added in v0.0.5
func (rt *RouteTable) Match(host, path string) *CompiledHTTPRoute
Match finds the best matching route for the given host and path. Returns nil if no route matches.
Matching rules:
- Exact host match takes priority over wildcard
- Longest path prefix wins among same-host matches
- Routes are pre-sorted by priority from the compiler
- Port-aware: if a route pattern includes a port, the request must match on host:port; if the pattern has no port, only the hostname is compared
func (*RouteTable) Routes ¶ added in v0.0.5
func (rt *RouteTable) Routes() []CompiledHTTPRoute
Routes returns a snapshot of the current routes (for debugging/metrics).
func (*RouteTable) Update ¶ added in v0.0.5
func (rt *RouteTable) Update(routes []CompiledHTTPRoute)
Update replaces the entire route set atomically. Routes should already be sorted by priority (handled by the compiler).
type ServiceChange ¶
type ServiceChange struct {
Type ChangeType
Service *ServiceState
}
ServiceChange represents a change to a Consul service.
type ServiceInstance ¶
type ServiceInstance struct {
ID string
Address string
Port int
Tags []string
Meta map[string]string
Healthy bool
Weight int
NodeName string // Consul node name where this instance runs
}
ServiceInstance represents a single instance of a Consul service.
type ServiceRegistrar ¶
type ServiceRegistrar struct {
// contains filtered or unexported fields
}
ServiceRegistrar handles auto-registration of Caddy as a service in Consul with a Connect sidecar proxy definition. This is required for both sidecar and direct Connect modes — without registration, Caddy has no mesh identity.
The registrar keeps the TTL health check alive via a background goroutine. Registration is idempotent — safe to call on every Caddy config reload.
func NewServiceRegistrar ¶
func NewServiceRegistrar(client *consul.Client, logger *zap.Logger, serviceName string) *ServiceRegistrar
NewServiceRegistrar creates a new ServiceRegistrar.
func (*ServiceRegistrar) Deregister ¶ added in v0.0.5
func (sr *ServiceRegistrar) Deregister()
Deregister removes the service and its sidecar proxy from Consul. This should only be called on actual process exit, not on config reloads.
func (*ServiceRegistrar) Register ¶
func (sr *ServiceRegistrar) Register() error
Register registers Caddy as a service in Consul with Connect enabled and starts a background goroutine to keep the TTL health check alive. If the service is already registered, it skips re-registration to avoid overwriting existing sidecar proxy configurations (e.g., upstream entries).
func (*ServiceRegistrar) Stop ¶
func (sr *ServiceRegistrar) Stop()
Stop stops the TTL updater. Does NOT deregister the service — registration persists across config reloads. The TTL will eventually expire if Caddy truly shuts down. Use Deregister() for clean removal on process exit.
type ServiceState ¶
type ServiceState struct {
Name string
Tags []string
Meta map[string]string
Instances []ServiceInstance
LastIndex uint64
}
ServiceState holds the current known state of a Consul service.
type SidecarResolver ¶
type SidecarResolver struct {
// contains filtered or unexported fields
}
SidecarResolver resolves upstream addresses by querying Caddy's own sidecar proxy for local bind ports.
func NewSidecarResolver ¶
func NewSidecarResolver(client *consul.Client, logger *zap.Logger, serviceName string) *SidecarResolver
NewSidecarResolver creates a new SidecarResolver.
func (*SidecarResolver) ResolveUpstreams ¶
func (sr *SidecarResolver) ResolveUpstreams(route *RouteDefinition) error
ResolveUpstreams replaces the route's upstreams with the sidecar proxy's local bind address for the target service. It queries Caddy's own sidecar at /v1/agent/service/<serviceName>-sidecar-proxy and matches the route's service name against Proxy.Upstreams[].DestinationName.
type Upstream ¶
type Upstream struct {
Address string
Weight int
Healthy bool
NodeName string // Consul node name (used for l4_mode filtering; not serialized to Caddy)
}
Upstream represents a single backend target.
type UpstreamManager ¶ added in v0.0.5
type UpstreamManager struct {
// contains filtered or unexported fields
}
UpstreamManager dynamically manages sidecar proxy upstream registrations in Consul. When caddy-consul discovers a Connect service, it allocates a local port and adds the upstream to the sidecar's Proxy.Upstreams. Envoy detects the change via xDS and opens a local listener on that port.
func NewUpstreamManager ¶ added in v0.0.5
func NewUpstreamManager( client *consul.Client, logger *zap.Logger, serviceName string, portStart, portEnd int, ) *UpstreamManager
NewUpstreamManager creates a new UpstreamManager.
func (*UpstreamManager) Allocations ¶ added in v0.0.5
func (um *UpstreamManager) Allocations() map[string]int
Allocations returns the current port allocations for persistence.
func (*UpstreamManager) RestoreAllocations ¶ added in v0.0.5
func (um *UpstreamManager) RestoreAllocations(allocations map[string]int)
RestoreAllocations restores port allocations from persisted state.
func (*UpstreamManager) SyncUpstreams ¶ added in v0.0.5
func (um *UpstreamManager) SyncUpstreams(desired map[string]bool) (bool, error)
SyncUpstreams ensures the sidecar proxy registration's Proxy.Upstreams matches the desired set of Connect services. Adds missing upstreams with allocated ports, removes stale ones. Makes a single Consul API call.
Returns true if the registration was updated (upstreams changed).
type UpstreamMode ¶
type UpstreamMode string
UpstreamMode determines how traffic reaches the backend.
const ( UpstreamDirect UpstreamMode = "direct" // no mesh, connect directly UpstreamConnectSidecar UpstreamMode = "connect-sidecar" // via local sidecar proxy )
func (UpstreamMode) IsConnect ¶
func (m UpstreamMode) IsConnect() bool
IsConnect returns true if the mode involves Consul Connect.