Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyOverrides(overrides *v1.DockerOverrides, config *container.Config, ...)
- func EndServerTransition(serverID string)
- func FilterEligibleNodes(nodes []*models.Node, reqMemoryMB int64) []*models.Node
- func GetOptimalDockerTag(mcVersion string, modLoader models.ModLoader, preferGraalVM bool) string
- func GetRequiredJavaVersion(mcVersion string, modLoader models.ModLoader) string
- func IsPrivilegedDockerOverride(overrides *v1.DockerOverrides) bool
- func ModuleSafeRoots(serverDataPath, backupDir string) []string
- func NewAPIClient(opts ...client.Opt) (*client.Client, error)
- func PrivilegedOverrideFields(overrides *v1.DockerOverrides) map[string]any
- func ReconcileAndCleanupContainers(ctx context.Context, store ReconcileStore, dockerClient *Client, ...) error
- func SelectLeastMemory(eligible []*models.Node) *models.Node
- func SelectLeastServers(eligible []*models.Node) *models.Node
- func ServerOverrideSafeRoots(serverDataPath string) []string
- func ServerTransitionInFlight(serverID string) bool
- func StopTimeoutSeconds(window time.Duration) int
- func StopWindow(cfg *models.ServerConfig) time.Duration
- func TranslateToHostPath(path string) string
- func TryBeginServerTransition(serverID string) bool
- func ValidateDockerDevices(devices []string) error
- func ValidateDockerNetworkMode(mode string) error
- func ValidateDockerOverrides(overrides *v1.DockerOverrides, allowPrivileged bool) error
- func ValidateDockerOverridesConfinement(overrides *v1.DockerOverrides, safeRoots ...string) error
- func ValidateDockerVolumeOverrides(volumes []*v1.VolumeMount, safeRoots ...string) error
- func ValidateJVMOptions(opts string) error
- func ValidateModuleVolumeMounts(volumes []ModuleVolumeMount, safeRoots ...string) error
- func ValidateVolumeSource(source, mountType string, safeRoots ...string) error
- func WaitForServerTransition(ctx context.Context, serverID string) error
- type Client
- func (c *Client) Close() error
- func (c *Client) CreateContainer(ctx context.Context, server *models.Server, serverConfig *models.ServerConfig) (string, error)
- func (c *Client) CreateModuleContainer(ctx context.Context, module *models.Module, template *models.ModuleTemplate, ...) (string, error)
- func (c *Client) DetectContainerJavaVersion(ctx context.Context, containerID string) (int, error)
- func (c *Client) EnsureNetwork() error
- func (c *Client) Exec(ctx context.Context, containerID string, execCmd []string) (string, error)
- func (c *Client) ExecCommand(ctx context.Context, containerID string, command string) (string, error)
- func (c *Client) GetAllocatedHostPorts(ctx context.Context) (map[int]bool, error)
- func (c *Client) GetConfig() ClientConfig
- func (c *Client) GetContainerStats(ctx context.Context, containerID string) (*ContainerStats, error)
- func (c *Client) GetContainerStatus(ctx context.Context, containerID string) (models.ServerStatus, error)
- func (c *Client) GetDockerClient() *client.Client
- func (c *Client) GetDockerImages() []DockerImageTag
- func (c *Client) GetFirewallManager() *FirewallManager
- func (c *Client) GetModuleContainerIP(ctx context.Context, containerID string) (string, error)
- func (c *Client) HostMemoryMB(ctx context.Context) (int64, error)
- func (c *Client) ObserveContainer(ctx context.Context, containerID string) (*ContainerState, error)
- func (c *Client) PauseContainer(ctx context.Context, containerID string) error
- func (c *Client) Ping(ctx context.Context) (client.PingResult, error)
- func (c *Client) RecreateContainer(ctx context.Context, oldContainerID string, server *models.Server, ...) (*RecreateContainerResult, error)
- func (c *Client) RemoveContainer(ctx context.Context, containerID string) error
- func (c *Client) ResolveContainer(ctx context.Context, serverID string) (*container.Summary, error)
- func (c *Client) ResolveModuleContainer(ctx context.Context, moduleID string) (*container.Summary, error)
- func (c *Client) RestartContainer(ctx context.Context, containerID string, delay time.Duration) error
- func (c *Client) SetLogStreamer(ls ContainerLogStreamer)
- func (c *Client) SetProxyEnabled(enabled bool)
- func (c *Client) StartContainer(ctx context.Context, containerID string) error
- func (c *Client) StopContainer(ctx context.Context, containerID string) (bool, error)
- func (c *Client) StopContainerWithin(ctx context.Context, containerID string, window time.Duration) (bool, error)
- func (c *Client) UnpauseContainer(ctx context.Context, containerID string) error
- type ClientConfig
- type ClientPool
- func (p *ClientPool) Close() error
- func (p *ClientPool) GetClient(nodeID string) (*Client, error)
- func (p *ClientPool) GetClientStrict(nodeID string) (*Client, error)
- func (p *ClientPool) GetDefaultClient() *Client
- func (p *ClientPool) GetDefaultNodeID() string
- func (p *ClientPool) GetHostMemoryMB(ctx context.Context, nodeID string) (int64, error)
- func (p *ClientPool) IsFallbackEnabled() bool
- func (p *ClientPool) PingNode(ctx context.Context, nodeID string) (bool, error)
- func (p *ClientPool) RegisterClient(nodeID string, cli *Client)
- func (p *ClientPool) RemoveNode(nodeID string) error
- func (p *ClientPool) SetFallbackEnabled(enabled bool)
- func (p *ClientPool) SetProxyEnabled(enabled bool)
- func (p *ClientPool) StartHealthChecker(interval time.Duration)
- func (p *ClientPool) Stats() PoolStats
- func (p *ClientPool) StopHealthChecker()
- type ContainerFreezer
- type ContainerLogClientResolver
- type ContainerLogStreamer
- type ContainerLookup
- type ContainerState
- type ContainerStats
- type DeepSleepManager
- func (m *DeepSleepManager) CheckIdleServers(ctx context.Context) error
- func (m *DeepSleepManager) IsAsleep(ctx context.Context, serverID string) bool
- func (m *DeepSleepManager) IsTransitioning(serverID string) bool
- func (m *DeepSleepManager) RecordActivity(serverID string)
- func (m *DeepSleepManager) SetControllerResolver(resolver SleepControllerResolver)
- func (m *DeepSleepManager) SetPlayerCountProvider(provider func(serverID string) int)
- func (m *DeepSleepManager) SetWakePreparer(preparer WakePreparer)
- func (m *DeepSleepManager) SleepServer(ctx context.Context, serverID string) error
- func (m *DeepSleepManager) Start(ctx context.Context, checkInterval time.Duration)
- func (m *DeepSleepManager) Stop()
- func (m *DeepSleepManager) WakeServer(ctx context.Context, serverID string) error
- type DockerCandidate
- type DockerImageTag
- type FirewallManager
- func (f *FirewallManager) ApplyPortRateLimiting(ctx context.Context, port int, ratePerMin, burst int) error
- func (f *FirewallManager) ApplyProxyPortIsolation(ctx context.Context, port int) error
- func (f *FirewallManager) BuildIsolationRules(port int) [][]string
- func (f *FirewallManager) BuildPortRules(port int, ratePerMin, burst int) [][]string
- func (f *FirewallManager) RemovePortRateLimiting(ctx context.Context, port, ratePerMin, burst int) error
- func (f *FirewallManager) RemoveProxyPortIsolation(ctx context.Context, port int) error
- type FreezerStore
- type HibernationManager
- func (m *HibernationManager) CheckIdleServers(ctx context.Context) error
- func (m *HibernationManager) HibernateServer(ctx context.Context, serverID string) error
- func (m *HibernationManager) IsHibernated(ctx context.Context, serverID string) bool
- func (m *HibernationManager) RecordActivity(serverID string)
- func (m *HibernationManager) RegisterWakeCallback(cb func(serverID string))
- func (m *HibernationManager) SetPlayerCountProvider(provider func(serverID string) int)
- func (m *HibernationManager) Start(ctx context.Context, checkInterval time.Duration)
- func (m *HibernationManager) Stop()
- func (m *HibernationManager) TotalHibernated() uint64
- func (m *HibernationManager) TotalWoken() uint64
- func (m *HibernationManager) WakeServer(ctx context.Context, serverID string) error
- type ModuleVolumeMount
- type NodeStore
- type PlacementEngine
- type PlacementStore
- type PlacementStrategy
- type PoolStats
- type ReconcileStore
- type RecreateContainerResult
- type RouteRefresher
- type SleepCommander
- type SleepController
- type SleepControllerResolver
- type SleeperStore
- type WakePreparer
Constants ¶
const ( // Default Minecraft server port inside containers DefaultMinecraftPort = 25565 // Default RCON port inside containers DefaultRCONPort = 25575 // Offset added to game port for RCON host binding RCONPortOffset = 10 )
const ( // DefaultStopWindow is how long a stop waits for the JVM to save before // Docker escalates from SIGTERM to SIGKILL. It matches itzg STOP_DURATION. DefaultStopWindow = 60 * time.Second // MaxStopWindow caps a per-server override so a bad config cannot pin a worker. MaxStopWindow = 180 * time.Second )
Variables ¶
var ( ErrDockerVolumeOutsideSafeRoot = errors.New("docker volume source is outside the allowed roots") ErrDockerDevicesNotAllowed = errors.New("docker overrides must not request host device mappings") ErrDockerNetworkModeNotAllowed = errors.New("docker network mode is not allowed") )
Confinement errors returned by the volume/device/network validators below. Unlike ErrElevatedDockerPermissionRequired these are NOT permission-gated: a host-path bind mount outside the caller's safe roots, a host device mapping, or host/none networking breaks container confinement for ANY caller, including holders of the elevated docker permission, so they are rejected outright (map to Connect CodeInvalidArgument at the RPC layer).
var DefaultRestartPolicy = container.RestartPolicy{
Name: "on-failure",
MaximumRetryCount: 5,
}
DefaultRestartPolicy is the Docker restart policy applied to every Carbon Panel container. "on-failure:5" lets the daemon re-attempt crashed containers up to 5 times while honouring an explicit operator /stop (exit 0) — desired-state authority stays with the panel's reconciler which self-heals missing containers. Pinned by TestDefaultRestartPolicy — change deliberately.
var ErrContainerNotResolved = fmt.Errorf("no matching docker container found")
ErrContainerNotResolved is returned by Resolve* methods when a container cannot be found by label or by the deterministic name convention. It signals "genuinely gone" (as opposed to a transient Docker API error) so callers can safely fall through to creating a new container.
var ErrElevatedDockerPermissionRequired = errors.New("docker overrides request privileged mode, added capabilities, or a confinement-weakening security option; this requires the servers/manage_docker_privileged permission")
ErrElevatedDockerPermissionRequired is returned by ValidateDockerOverrides when the caller requested a host-breakout-capable Docker override (Privileged mode, CapAdd, or a confinement-weakening SecurityOpt) without the elevated permission.
Functions ¶
func ApplyOverrides ¶
func ApplyOverrides(overrides *v1.DockerOverrides, config *container.Config, hostConfig *container.HostConfig)
ApplyOverrides applies DockerOverrides to container and host configs
func EndServerTransition ¶
func EndServerTransition(serverID string)
EndServerTransition releases a lifecycle transition claimed by TryBeginServerTransition.
func FilterEligibleNodes ¶
FilterEligibleNodes filters nodes that are enabled, online, and within memory & server capacity limits.
func GetOptimalDockerTag ¶
Gets ideal docker tag for a given Minecraft version + mod loader
func GetRequiredJavaVersion ¶
Gets required Java version for a Minecraft version
func IsPrivilegedDockerOverride ¶
func IsPrivilegedDockerOverride(overrides *v1.DockerOverrides) bool
IsPrivilegedDockerOverride reports whether the given overrides request any genuinely dangerous, host-breakout-capable setting:
- full --privileged mode
- any added Linux capability (CapAdd)
- a confinement-weakening SecurityOpt (apparmor:unconfined, seccomp:unconfined, label:disable, and their "=" spellings)
Benign fields (PidsLimit, CpusetCpus, ReadOnly, CapDrop, "no-new-privileges:true", etc.) never make this return true.
func ModuleSafeRoots ¶
ModuleSafeRoots returns the safe roots for module volume mounts: the owning server's data path (builtin templates mount {{server.data_path}}/...) and the global backup directory (the mc-backup template mounts {{config.storage.backup_dir}}). Empty roots are dropped; with no safe roots every absolute bind source is rejected (fail closed).
func NewAPIClient ¶
NewAPIClient creates a Docker API client and negotiates the API version eagerly, with a bounded ping, before returning it.
The SDK's lazy negotiation (client.WithAPIVersionNegotiation) runs that ping while holding negotiateLock — a plain, non-cancellable mutex. One unreachable daemon therefore blocks every subsequent caller of that client until the OS connect timeout, regardless of their own deadlines, which is what turns a single dead node into "socket hang up" on unrelated RPCs. Negotiating here keeps that lock off the request path entirely; callers must not pass client.WithAPIVersionNegotiation, or the SDK re-enters the lazy path whenever this eager ping fails.
func PrivilegedOverrideFields ¶
func PrivilegedOverrideFields(overrides *v1.DockerOverrides) map[string]any
PrivilegedOverrideFields extracts a structured map of requested privileged fields for immutable audit trail recording (SEC-3).
func ReconcileAndCleanupContainers ¶
func ReconcileAndCleanupContainers(ctx context.Context, store ReconcileStore, dockerClient *Client, log *logger.Logger) error
ReconcileAndCleanupContainers performs safe, two-phase startup reconciliation of containers Carbon Panel manages.
Phase 1 (adoption): every container labeled carbon-panel.managed=true is matched back to a DB record via its carbon-panel.server.id / carbon-panel.module.id label. If the record exists but its stored ContainerID is stale or empty, it is updated to match reality (adoption). If no record exists at all for that ID, the container is a genuine orphan and is queued for phase 2 — it is never deleted in phase 1.
Phase 2 (purge): only containers queued as genuine orphans in phase 1 are stopped and removed. Every container that matches a live DB record — even one whose ContainerID had drifted, now fixed in phase 1 — is left alone. Detached servers/modules (Server.Detached / Module.Detached) can never end up in the orphan set in the first place, since "detached" is a property of an existing DB record and orphan status requires the absence of one; they are therefore always safe from phase-2 purge by construction.
Fail-safe: if the DB cannot be read (ListServers/ListModules error), reconciliation aborts entirely and returns an error without ever reaching phase 2. Proceeding with a partial or empty server/module list would make every real container look orphaned and destroy them.
func SelectLeastMemory ¶
SelectLeastMemory chooses the node with the minimum allocated memory.
func SelectLeastServers ¶
SelectLeastServers chooses the node with the fewest running instances.
func ServerOverrideSafeRoots ¶
ServerOverrideSafeRoots returns the safe roots for per-server DockerOverrides volume sources: the server's own data path, plus its host-translated form for when the panel itself runs in a container (TranslateToHostPath is a no-op on host runs, so including both views is always safe).
func ServerTransitionInFlight ¶
ServerTransitionInFlight reports whether a lifecycle operation owns serverID.
func StopTimeoutSeconds ¶
StopTimeoutSeconds is the Docker stop timeout for window. Docker sends SIGTERM immediately and SIGKILL only after this many seconds.
func StopWindow ¶
func StopWindow(cfg *models.ServerConfig) time.Duration
StopWindow returns the save window for a server. A missing or non-positive StopDuration uses DefaultStopWindow. Values above MaxStopWindow are clamped.
func TranslateToHostPath ¶
Converts a container-internal path to a host path. When CARBONPANEL_HOST_DATA_PATH is not set (running on host), it returns the path unchanged.
func TryBeginServerTransition ¶
TryBeginServerTransition claims the lifecycle transition for serverID.
func ValidateDockerDevices ¶
ValidateDockerDevices rejects any host device mapping. There is no legitimate panel flow that maps host devices into server containers.
func ValidateDockerNetworkMode ¶
ValidateDockerNetworkMode rejects the confinement-breaking network modes. "host" shares the host network namespace and "none" breaks the panel's proxy/networking assumptions; anything else (empty/default, named networks) is left alone.
func ValidateDockerOverrides ¶
func ValidateDockerOverrides(overrides *v1.DockerOverrides, allowPrivileged bool) error
ValidateDockerOverrides enforces that only callers holding the elevated Docker permission may request privileged-mode settings (see IsPrivilegedDockerOverride). It must be called with the caller's permission status BEFORE the overrides are persisted to a server record; once persisted, later container (re)creation trusts the stored value and does not re-check permission, since the caller at container-creation time (e.g. an operator starting an already-configured server) is not necessarily the same caller - or as privileged - as whoever originally set the overrides.
func ValidateDockerOverridesConfinement ¶
func ValidateDockerOverridesConfinement(overrides *v1.DockerOverrides, safeRoots ...string) error
ValidateDockerOverridesConfinement is the single authoritative entry point for the volume/device/network gap: it rejects host-breakout-capable DockerOverrides for ALL callers (no permission bypass). Wire it in before overrides are persisted (CreateServer/UpdateServer) in addition to the permission-gated ValidateDockerOverrides above.
func ValidateDockerVolumeOverrides ¶
func ValidateDockerVolumeOverrides(volumes []*v1.VolumeMount, safeRoots ...string) error
ValidateDockerVolumeOverrides applies ValidateVolumeSource to every DockerOverrides volume entry (Path A: server overrides).
func ValidateJVMOptions ¶
ValidateJVMOptions validates JVM arguments and flags for dangerous options or invalid heap bounds (INF-3, SEC-6). It disallows command-execution hooks and native library loaders that can breach container confinement or execute arbitrary commands upon crash/OOM.
func ValidateModuleVolumeMounts ¶
func ValidateModuleVolumeMounts(volumes []ModuleVolumeMount, safeRoots ...string) error
ValidateModuleVolumeMounts applies ValidateVolumeSource to every module volume entry (Path B: module volumes, post alias-substitution).
func ValidateVolumeSource ¶
ValidateVolumeSource enforces host-path confinement for a single mount source. Docker named volumes (explicit Type "volume", an empty source, or a non-absolute source name) reference daemon-managed storage rather than a host path and are always allowed. Anything else that names an absolute host path (a bind mount, the default when Type is empty) must resolve inside one of safeRoots, checked with files.Within so sibling-prefix (/data/srv-evil) and ".." escapes are rejected.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func NewClientForNode ¶
func NewClientForNode(node *models.Node, log *logger.Logger, baseConfig ClientConfig) (*Client, error)
NewClientForNode constructs a *Client configured specifically for a Node. Supports unix:// sockets, tcp:// (with optional TLS certs or TLS skip verify), and ssh://.
func (*Client) CreateContainer ¶
func (*Client) CreateModuleContainer ¶
func (c *Client) CreateModuleContainer(ctx context.Context, module *models.Module, template *models.ModuleTemplate, server *models.Server, serverConfig *models.ServerConfig, cfg *config.Config, siblingModules ...map[string]*models.Module) (string, error)
Create container for a module w/ optional map of sibling modules by name for inter-module references
func (*Client) DetectContainerJavaVersion ¶
DetectContainerJavaVersion attempts to auto-detect the Java runtime version from a running container
func (*Client) EnsureNetwork ¶
Creates the Docker network if it doesn't exist - attaches itself to that network when applicable
func (*Client) Exec ¶
Runs shell command, script, or executable inside the container and returns the output
func (*Client) ExecCommand ¶
func (c *Client) ExecCommand(ctx context.Context, containerID string, command string) (string, error)
ExecCommand executes a command inside the container and returns the output
func (*Client) GetAllocatedHostPorts ¶
GetAllocatedHostPorts returns a set of host ports currently allocated/bound by running containers.
func (*Client) GetConfig ¶
func (c *Client) GetConfig() ClientConfig
func (*Client) GetContainerStats ¶
func (*Client) GetContainerStatus ¶
func (*Client) GetDockerClient ¶
Get the docker client instance from the client object
func (*Client) GetDockerImages ¶
func (c *Client) GetDockerImages() []DockerImageTag
func (*Client) GetFirewallManager ¶
func (c *Client) GetFirewallManager() *FirewallManager
GetFirewallManager returns the firewall manager for DOCKER-USER rules
func (*Client) GetModuleContainerIP ¶
GetModuleContainerIP gets the IP address of a module container on the Carbon Panel network
func (*Client) HostMemoryMB ¶
HostMemoryMB returns the memory visible to the Docker daemon. Callers use this as a hard upper bound when a node has no operator-configured capacity.
func (*Client) ObserveContainer ¶
ObserveContainer inspects a container once and returns its consolidated runtime state. A container that does not exist is reported by the returned error (errdefs.IsNotFound); callers expecting it to exist should treat that as "container missing" rather than a transient failure.
func (*Client) PauseContainer ¶
PauseContainer pauses all processes in the container using cgroup freezer (MINE-18)
func (*Client) RecreateContainer ¶
func (c *Client) RecreateContainer(ctx context.Context, oldContainerID string, server *models.Server, serverConfig *models.ServerConfig) (*RecreateContainerResult, error)
Stops, removes, and creates a new container - Returns new container ID and whether it was running before
func (*Client) RemoveContainer ¶
func (*Client) ResolveContainer ¶
ResolveContainer attempts to deterministically re-find the Docker container belonging to the given server ID, independent of any (possibly empty or stale) stored container ID.
Resolution order:
- ContainerList filtered by the carbon-panel.server.id label (includes stopped containers).
- Fallback: ContainerInspect on the canonical deterministic name "carbon-panel-server-<id>", in case the container exists but was created before labels were consistently applied, or the label was somehow stripped/lost.
Returns ErrContainerNotResolved (wrapped) if neither strategy finds a container. Any other error is a transient/unexpected Docker API failure and should NOT be treated as "not found".
func (*Client) ResolveModuleContainer ¶
func (c *Client) ResolveModuleContainer(ctx context.Context, moduleID string) (*container.Summary, error)
ResolveModuleContainer is the module-scoped analogue of ResolveContainer. It re-finds the Docker container belonging to a module ID via the carbon-panel.module.id label, falling back to the deterministic name "carbon-panel-module-<id>".
func (*Client) RestartContainer ¶
func (c *Client) RestartContainer(ctx context.Context, containerID string, delay time.Duration) error
Stops and starts a container with an optional delay between operations
func (*Client) SetLogStreamer ¶
func (c *Client) SetLogStreamer(ls ContainerLogStreamer)
Auto manage streams at the client level when set
func (*Client) SetProxyEnabled ¶
SetProxyEnabled toggles the proxy mode for port isolation and proxy routing
func (*Client) StartContainer ¶
func (*Client) StopContainer ¶
StopContainer stops a container using the default save window. Returns (containerFound, error). A missing container returns (false, nil).
type ClientConfig ¶
type ClientPool ¶
type ClientPool struct {
// contains filtered or unexported fields
}
ClientPool manages Docker client instances for multiple nodes concurrently.
func NewClientPool ¶
func NewClientPool(store NodeStore, defaultClient *Client, log *logger.Logger, cfg ...ClientConfig) *ClientPool
NewClientPool creates a new multi-node Docker ClientPool.
func (*ClientPool) Close ¶
func (p *ClientPool) Close() error
Close closes all managed clients and stops background tasks.
func (*ClientPool) GetClient ¶
func (p *ClientPool) GetClient(nodeID string) (*Client, error)
GetClient retrieves the Docker client for the given nodeID. If the node cannot be found, the store is unavailable, or its client cannot be created, it gracefully falls back to the default client (typically the local Docker daemon), logging only a Warn. This fallback is convenient but dangerous for multi-node correctness: if a remote node blips, callers can silently end up operating against the LOCAL daemon instead of the intended remote node (e.g. creating a "remote" container locally by mistake).
Prefer GetClientStrict for any operation where acting on the wrong node would be a correctness or safety problem (container create/start/stop/remove, recreate, etc.). Only use GetClient where a best-effort fallback to local is truly acceptable (e.g. read-only status checks where local UI needs to degrade gracefully) and other code may already depend on this behavior.
func (*ClientPool) GetClientStrict ¶
func (p *ClientPool) GetClientStrict(nodeID string) (*Client, error)
GetClientStrict retrieves the Docker client for the given nodeID without fallback to default. This is the recommended path for multi-node-sensitive operations: callers get an explicit error instead of silently executing against the local Docker daemon when the requested node is unavailable. See GetClient's doc comment for why the fallback there is risky.
func (*ClientPool) GetDefaultClient ¶
func (p *ClientPool) GetDefaultClient() *Client
GetDefaultClient returns the default Docker client (typically local host).
func (*ClientPool) GetDefaultNodeID ¶
func (p *ClientPool) GetDefaultNodeID() string
GetDefaultNodeID returns the configured ID of the default node (e.g. "default").
func (*ClientPool) GetHostMemoryMB ¶
GetHostMemoryMB returns the cached host memory capacity in MB for a node, or queries the Docker daemon directly if not yet cached.
func (*ClientPool) IsFallbackEnabled ¶
func (p *ClientPool) IsFallbackEnabled() bool
IsFallbackEnabled reports whether silent fallback to the default client is enabled.
func (*ClientPool) PingNode ¶
PingNode tests connectivity to a specific Docker node and updates its DB status.
func (*ClientPool) RegisterClient ¶
func (p *ClientPool) RegisterClient(nodeID string, cli *Client)
func (*ClientPool) RemoveNode ¶
func (p *ClientPool) RemoveNode(nodeID string) error
RemoveNode closes and unregisters a node client from the pool.
func (*ClientPool) SetFallbackEnabled ¶
func (p *ClientPool) SetFallbackEnabled(enabled bool)
SetFallbackEnabled controls whether GetClient may fall back to the default client when a specific requested node cannot be found or fails to connect. By default, fallback is disabled for security and correctness so that operations targeted to a specific remote node are never silently executed on the local daemon.
func (*ClientPool) SetProxyEnabled ¶
func (p *ClientPool) SetProxyEnabled(enabled bool)
RegisterClient explicitly registers a client for a given nodeID. SetProxyEnabled propagates the proxy mode setting across all pooled clients and base config.
func (*ClientPool) StartHealthChecker ¶
func (p *ClientPool) StartHealthChecker(interval time.Duration)
StartHealthChecker starts background health checking for all enabled nodes.
func (*ClientPool) Stats ¶
func (p *ClientPool) Stats() PoolStats
Stats returns a point-in-time snapshot of the ClientPool metrics.
func (*ClientPool) StopHealthChecker ¶
func (p *ClientPool) StopHealthChecker()
StopHealthChecker stops background health checking.
type ContainerFreezer ¶
type ContainerFreezer interface {
PauseContainer(ctx context.Context, containerID string) error
UnpauseContainer(ctx context.Context, containerID string) error
GetContainerStatus(ctx context.Context, containerID string) (db.ServerStatus, error)
}
ContainerFreezer defines the container pause/unpause and status capabilities
type ContainerLogClientResolver ¶
type ContainerLogClientResolver struct {
// contains filtered or unexported fields
}
ContainerLogClientResolver attributes a container to its node and returns that node's Docker SDK client, so the log streamer can tail containers on remote nodes instead of silently inspecting the local daemon (MINE-108).
A container it cannot attribute (e.g. a module container, which has no server record) yields (nil, nil), which the streamer treats as "use the local client" — preserving the previous single-node behaviour.
func NewContainerLogClientResolver ¶
func NewContainerLogClientResolver(store ContainerLookup, pool *ClientPool) *ContainerLogClientResolver
NewContainerLogClientResolver constructs a resolver over a node-aware ClientPool.
func (*ContainerLogClientResolver) ResolveLogClient ¶
func (r *ContainerLogClientResolver) ResolveLogClient(ctx context.Context, containerID string) (*client.Client, error)
ResolveLogClient implements logger.LogClientResolver.
type ContainerLogStreamer ¶
type ContainerLookup ¶
type ContainerLookup interface {
GetServerByContainerID(ctx context.Context, containerID string) (*models.Server, error)
}
ContainerLookup resolves a server by the Docker container ID that backs it. *db.Store satisfies this via the MINE-103 reverse lookup.
type ContainerState ¶
type ContainerState struct {
ContainerID string
Status models.ServerStatus
Running bool
// ExitCode is the container process's last exit code. Only meaningful when
// HasExited is true.
ExitCode int
// HasExited reports whether the container is not currently running, i.e.
// ExitCode reflects a completed process rather than a live one.
HasExited bool
// OOMKilled reports whether Docker recorded the last exit as an OOM kill.
OOMKilled bool
}
ContainerState is the consolidated, reconciler-relevant view of a container's runtime state. It captures the mapped ServerStatus plus the exit code and OOM flag that are only available from a full ContainerInspect, in a single Docker round-trip. MINE-107's level-triggered reconciler uses this to converge DB state with observed reality without inspecting twice.
type ContainerStats ¶
type DeepSleepManager ¶
type DeepSleepManager struct {
// contains filtered or unexported fields
}
DeepSleepManager stops idle Minecraft servers entirely (zero RAM/CPU) and boots them on login intent via the proxy (MINE-121). Unlike the cgroup freezer (HibernationManager), nothing of the server stays resident: wake is a full container start, so the proxy must hold the client until the backend answers (see internal/proxy down-route handling).
func NewDeepSleepManager ¶
func NewDeepSleepManager(controller SleepController, store SleeperStore, commander SleepCommander, refresher RouteRefresher, log *logger.Logger) *DeepSleepManager
NewDeepSleepManager creates a new DeepSleepManager. commander and refresher may be nil (RCON flush and route refresh are then skipped).
func (*DeepSleepManager) CheckIdleServers ¶
func (m *DeepSleepManager) CheckIdleServers(ctx context.Context) error
CheckIdleServers evaluates all running deep-sleep-enabled servers and stops idle ones.
func (*DeepSleepManager) IsAsleep ¶
func (m *DeepSleepManager) IsAsleep(ctx context.Context, serverID string) bool
IsAsleep returns whether the server is currently deeply asleep.
func (*DeepSleepManager) IsTransitioning ¶
func (m *DeepSleepManager) IsTransitioning(serverID string) bool
IsTransitioning returns whether the server is currently transitioning (sleeping or waking).
func (*DeepSleepManager) RecordActivity ¶
func (m *DeepSleepManager) RecordActivity(serverID string)
RecordActivity marks a server as recently active, resetting its idle countdown.
func (*DeepSleepManager) SetControllerResolver ¶
func (m *DeepSleepManager) SetControllerResolver(resolver SleepControllerResolver)
SetControllerResolver installs a multi-node controller resolver so deep sleep operations target the Docker daemon on the server's assigned node.
func (*DeepSleepManager) SetPlayerCountProvider ¶
func (m *DeepSleepManager) SetPlayerCountProvider(provider func(serverID string) int)
SetPlayerCountProvider configures the online-player source of truth (same rationale as HibernationManager: store rows never persist PlayersOnline).
func (*DeepSleepManager) SetWakePreparer ¶
func (m *DeepSleepManager) SetWakePreparer(preparer WakePreparer)
SetWakePreparer installs the staged-configuration preflight for cold wakes.
func (*DeepSleepManager) SleepServer ¶
func (m *DeepSleepManager) SleepServer(ctx context.Context, serverID string) error
SleepServer gracefully stops a server container and marks it deeply asleep. The status is pre-set to StatusDeepSleep and proxy route updated before stopping the container, so the reconciler never misclassifies the container exit as an unexpected stop or clobbers proxy routes (MINE-121, MINE-172).
func (*DeepSleepManager) Start ¶
func (m *DeepSleepManager) Start(ctx context.Context, checkInterval time.Duration)
Start begins the background idle-checker routine.
func (*DeepSleepManager) Stop ¶
func (m *DeepSleepManager) Stop()
Stop terminates the background idle-checker routine.
func (*DeepSleepManager) WakeServer ¶
func (m *DeepSleepManager) WakeServer(ctx context.Context, serverID string) error
WakeServer boots a deeply asleep server. Concurrent callers wait for the current lifecycle transition, then re-read state; a completed wake is idempotent while an in-flight sleep is followed by a wake.
type DockerCandidate ¶
type DockerCandidate struct {
Host string `json:"host"`
Port int `json:"port"`
Reachable bool `json:"reachable"`
LatencyMs int64 `json:"latencyMs"`
Source string `json:"source"`
}
DockerCandidate is a single auto-detect probe result for a Docker daemon endpoint reachable on one of the host's network interfaces.
func DetectDockerDaemons ¶
func DetectDockerDaemons(ctx context.Context) []DockerCandidate
DetectDockerDaemons probes the local unix socket plus TCP 2375/2376 on every up network interface address (and its likely gateway) to find active Docker daemons. Probes run concurrently and are bounded by ctx; unreachable endpoints are still returned with Reachable=false so the UI can show what was scanned.
type DockerImageTag ¶
type DockerImageTag struct {
Tag string `json:"tag"` // Docker tag name (e.g., "latest", "java21", etc.)
Java string `json:"java"` // Java version number
Distribution string `json:"distribution"` // Linux distribution (ubuntu, alpine, oracle)
JVM string `json:"jvm"` // JVM type (hotspot, graalvm)
Architectures []string `json:"architectures"` // Supported architectures
Deprecated bool `json:"deprecated"` // Whether this tag is deprecated
LTS bool `json:"lts"` // Whether this is an LTS version
JDK bool `json:"jdk"` // Whether this includes JDK
Notes string `json:"notes"` // Additional notes about the tag
}
type FirewallManager ¶
type FirewallManager struct {
// contains filtered or unexported fields
}
FirewallManager manages DOCKER-USER chain iptables rules for Minecraft ports
func NewFirewallManager ¶
func NewFirewallManager(log *logger.Logger, enabled bool, rateMin, burst int) *FirewallManager
NewFirewallManager creates a new DOCKER-USER firewall manager
func (*FirewallManager) ApplyPortRateLimiting ¶
func (f *FirewallManager) ApplyPortRateLimiting(ctx context.Context, port int, ratePerMin, burst int) error
ApplyPortRateLimiting applies DOCKER-USER chain rules for the given port.
Rules are inserted at increasing positions (1, 2, 3, ...) so the chain order matches BuildPortRules' evaluation order. Inserting every rule at position 1 would reverse the order and put the catch-all DROP first, blackholing the port.
func (*FirewallManager) ApplyProxyPortIsolation ¶
func (f *FirewallManager) ApplyProxyPortIsolation(ctx context.Context, port int) error
ApplyProxyPortIsolation isolates a proxied server port in the DOCKER-USER chain
func (*FirewallManager) BuildIsolationRules ¶
func (f *FirewallManager) BuildIsolationRules(port int) [][]string
BuildIsolationRules generates iptables rules to drop all external traffic to the proxied server port, allowing only local loopback (127.0.0.1) and internal private/docker subnets.
func (*FirewallManager) BuildPortRules ¶
func (f *FirewallManager) BuildPortRules(port int, ratePerMin, burst int) [][]string
BuildPortRules generates the DOCKER-USER iptables arguments for SYN flood and per-source connection rate limiting on a published game port.
The returned slice is in evaluation order and both ratePerMin and burst are honoured. ApplyPortRateLimiting inserts the rules while preserving this order, so the per-source DROP and the rate-limited ACCEPT are reached before the catch-all SYN DROP.
func (*FirewallManager) RemovePortRateLimiting ¶
func (f *FirewallManager) RemovePortRateLimiting(ctx context.Context, port, ratePerMin, burst int) error
RemovePortRateLimiting removes DOCKER-USER rules for a closed/deleted port. The same rate/burst values used when applying must be supplied so the generated rules match and can be deleted.
func (*FirewallManager) RemoveProxyPortIsolation ¶
func (f *FirewallManager) RemoveProxyPortIsolation(ctx context.Context, port int) error
RemoveProxyPortIsolation removes proxy port isolation rules
type FreezerStore ¶
type FreezerStore interface {
GetServer(ctx context.Context, id string) (*db.Server, error)
ListServers(ctx context.Context) ([]*db.Server, error)
UpdateServer(ctx context.Context, server *db.Server) error
UpdateServerStatus(ctx context.Context, id string, status db.ServerStatus) error
}
FreezerStore defines storage operations needed by HibernationManager
type HibernationManager ¶
type HibernationManager struct {
// contains filtered or unexported fields
}
HibernationManager manages cgroup freezer sleep/wake lifecycle for idle Minecraft servers
func NewHibernationManager ¶
func NewHibernationManager(freezer ContainerFreezer, store FreezerStore, log *logger.Logger) *HibernationManager
NewHibernationManager creates a new HibernationManager
func (*HibernationManager) CheckIdleServers ¶
func (m *HibernationManager) CheckIdleServers(ctx context.Context) error
CheckIdleServers evaluates all active servers and hibernates idle ones
func (*HibernationManager) HibernateServer ¶
func (m *HibernationManager) HibernateServer(ctx context.Context, serverID string) error
HibernateServer freezes a server container using cgroup freezer and updates status
func (*HibernationManager) IsHibernated ¶
func (m *HibernationManager) IsHibernated(ctx context.Context, serverID string) bool
IsHibernated returns whether the server is currently hibernated/paused
func (*HibernationManager) RecordActivity ¶
func (m *HibernationManager) RecordActivity(serverID string)
RecordActivity marks a server as recently active, resetting its idle countdown
func (*HibernationManager) RegisterWakeCallback ¶
func (m *HibernationManager) RegisterWakeCallback(cb func(serverID string))
RegisterWakeCallback registers a callback fired when a server is woken
func (*HibernationManager) SetPlayerCountProvider ¶
func (m *HibernationManager) SetPlayerCountProvider(provider func(serverID string) int)
SetPlayerCountProvider configures the online-player source of truth used by CheckIdleServers instead of the (never persisted) row field (MINE-120).
func (*HibernationManager) Start ¶
func (m *HibernationManager) Start(ctx context.Context, checkInterval time.Duration)
Start begins the background idle-checker routine
func (*HibernationManager) Stop ¶
func (m *HibernationManager) Stop()
Stop terminates the background idle-checker routine
func (*HibernationManager) TotalHibernated ¶
func (m *HibernationManager) TotalHibernated() uint64
TotalHibernated returns the cumulative number of server hibernations performed (SCH-6).
func (*HibernationManager) TotalWoken ¶
func (m *HibernationManager) TotalWoken() uint64
TotalWoken returns the cumulative number of server wakeups performed (SCH-6).
func (*HibernationManager) WakeServer ¶
func (m *HibernationManager) WakeServer(ctx context.Context, serverID string) error
WakeServer unfreezes a server container using cgroup freezer and restores running status
type ModuleVolumeMount ¶
type ModuleVolumeMount struct {
Source string `json:"source"`
Target string `json:"target"`
ReadOnly bool `json:"read_only,omitempty"`
Type string `json:"type,omitempty"` // "bind" or "volume"
CreateDir bool `json:"create_dir,omitempty"` // Pre-create source dirs
}
ModuleVolumeMount represents a volume mount from module configuration
type NodeStore ¶
type NodeStore interface {
GetNode(ctx context.Context, id string) (*models.Node, error)
ListNodes(ctx context.Context) ([]*models.Node, error)
UpdateNode(ctx context.Context, node *models.Node) error
}
NodeStore defines the DB interface needed by ClientPool
type PlacementEngine ¶
type PlacementEngine struct {
// contains filtered or unexported fields
}
PlacementEngine makes server placement decisions across Docker nodes.
func NewPlacementEngine ¶
func NewPlacementEngine(store PlacementStore) *PlacementEngine
NewPlacementEngine constructs a new PlacementEngine.
func (*PlacementEngine) SelectNode ¶
func (e *PlacementEngine) SelectNode(ctx context.Context, strategy PlacementStrategy, reqMemoryMB int64) (*models.Node, error)
SelectNode selects the best eligible Docker node based on strategy, required memory, and limits.
func (*PlacementEngine) SelectRoundRobin ¶
func (e *PlacementEngine) SelectRoundRobin(eligible []*models.Node) *models.Node
SelectRoundRobin distributes placements in round-robin order across eligible nodes.
type PlacementStore ¶
type PlacementStore interface {
ListNodesWithStats(ctx context.Context) ([]*models.Node, error)
ListNodes(ctx context.Context) ([]*models.Node, error)
GetNodeStats(ctx context.Context, nodeID string) (allocatedMemMB int64, serverCount int, runningCount int, err error)
}
PlacementStore defines the DB interface required by PlacementEngine
type PlacementStrategy ¶
type PlacementStrategy string
PlacementStrategy specifies which algorithm to use when assigning a container to a node.
const ( StrategyLeastMemory PlacementStrategy = "least_memory" StrategyLeastServers PlacementStrategy = "least_servers" StrategyRoundRobin PlacementStrategy = "round_robin" )
type PoolStats ¶
type PoolStats struct {
TotalRequests uint64
CacheHits uint64
CacheMisses uint64
Fallbacks uint64
CreateErrors uint64
}
PoolStats tracks telemetry for Docker client pool access (PERF-5).
type ReconcileStore ¶
type ReconcileStore interface {
ListServers(ctx context.Context) ([]*db.Server, error)
UpdateServer(ctx context.Context, server *db.Server) error
ListModules(ctx context.Context) ([]*db.Module, error)
UpdateModule(ctx context.Context, module *db.Module) error
}
ReconcileStore is the subset of *db.Store that startup reconciliation needs. It exists so the adopt-vs-orphan decision can be exercised in tests against an in-memory fake, without standing up a real database. *db.Store satisfies this interface.
type RecreateContainerResult ¶
type RecreateContainerResult struct {
// NewContainerID is the canonical container identity after the operation.
// On a failure before removal, it remains the original ID; after confirmed
// removal with no replacement, it is empty; after a partial create/start,
// it identifies the replacement that callers must continue tracking.
NewContainerID string
WasRunning bool
}
Result of a container recreation operation
type RouteRefresher ¶
type RouteRefresher func(serverID string)
RouteRefresher re-resolves a server's proxy route after a transition.
type SleepCommander ¶
type SleepCommander interface {
SendCommand(ctx context.Context, serverID string, command string) (string, error)
}
SleepCommander sends in-game console commands (RCON) for graceful shutdown.
type SleepController ¶
type SleepController interface {
StartContainer(ctx context.Context, containerID string) error
// StopContainer stops a container, returning (found, err).
StopContainer(ctx context.Context, containerID string) (bool, error)
GetContainerStatus(ctx context.Context, containerID string) (db.ServerStatus, error)
}
SleepController defines container start/stop/status capabilities for deep sleep.
type SleepControllerResolver ¶
type SleepControllerResolver func(nodeID string) SleepController
SleepControllerResolver resolves a node-specific SleepController.
type SleeperStore ¶
type SleeperStore interface {
GetServer(ctx context.Context, id string) (*db.Server, error)
ListServers(ctx context.Context) ([]*db.Server, error)
UpdateServer(ctx context.Context, server *db.Server) error
UpdateServerStatus(ctx context.Context, id string, status db.ServerStatus) error
}
SleeperStore defines storage operations needed by DeepSleepManager.