Documentation
¶
Index ¶
- Constants
- Variables
- func AdditionalPortHostIP(useProxy, exposePublic bool) string
- func ApplyDiskQuota(hostConfig *container.HostConfig, diskMB int64)
- func ApplyOverrides(overrides *v1.DockerOverrides, config *container.Config, ...)
- func CanonicalServerImage(dockerImage string) (string, error)
- 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 IsMinecraftImage(image string) bool
- func IsPrivilegedDockerOverride(overrides *v1.DockerOverrides) bool
- func LoadOrCreateInstallationID(dataDir string) (string, error)
- func ModuleSafeRoots(serverDataPath, backupDir string) []string
- func NewAPIClient(opts ...client.Opt) (*client.Client, error)
- func NewAPIClientContext(parent context.Context, opts ...client.Opt) (*client.Client, error)
- func PreflightProfile(profile RuntimeProfile) error
- func PreflightRuntime(spec RuntimeSpec) error
- func PrivilegedOverrideFields(overrides *v1.DockerOverrides) map[string]any
- func ReconcileAndCleanupContainers(ctx context.Context, store ReconcileStore, dockerClient *Client, ...) error
- func ResolveServerImage(dockerImage string) (string, 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 SetTransitionWarner(fn func(format string, args ...any))
- func StopTimeoutSeconds(window time.Duration) int
- func StopWindow(cfg *models.ServerConfig) time.Duration
- func TransitionDebug(serverID string) string
- func TranslateToHostPath(containerPath string) string
- 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 NewClient(host string, log *logger.Logger, config ...ClientConfig) (*Client, error)
- func NewClientForNode(node *models.Node, log *logger.Logger, baseConfig ClientConfig) (*Client, error)
- func NewClientForNodeContext(ctx context.Context, node *models.Node, log *logger.Logger, ...) (*Client, error)
- func (c *Client) AllocatedHostPorts(ctx context.Context, protocol string) (map[int]bool, error)
- 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) DaemonEnforcement(ctx context.Context) (DaemonEnforcement, error)
- func (c *Client) DaemonID(ctx context.Context) (string, error)
- func (c *Client) DetectContainerJavaVersion(ctx context.Context, containerID string) (int, error)
- func (c *Client) EnsureNetwork() error
- func (c *Client) EnsureNetworkContext(parent context.Context) 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) ImageStoreTotalBytes(ctx context.Context) (int64, error)
- func (c *Client) IsRemote() bool
- 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) ResolveModuleContainerPreferring(ctx context.Context, moduleID, recordedID string) (*container.Summary, error)
- func (c *Client) RestartContainer(ctx context.Context, containerID string, delay time.Duration) error
- func (c *Client) SelfMounts(ctx context.Context) ([]hostmount.Mount, error)
- func (c *Client) ServerImageID(ctx context.Context, server *models.Server) (string, error)
- func (c *Client) ServerImageIdentity(ctx context.Context, server *models.Server) (string, string, error)
- func (c *Client) SetLogStreamer(ls ContainerLogStreamer)
- func (c *Client) SetProxyEnabled(enabled bool)
- func (c *Client) SetRestartPolicy(ctx context.Context, containerID string, policy container.RestartPolicy) error
- 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) TailContainerLogs(ctx context.Context, containerID string, tailLines int) ([]string, 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) GetClientStrictContext(ctx context.Context, 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) ProbeNodes(ctx context.Context) ([]NodeProbe, 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 ContainerLimits
- type ContainerLogClientResolver
- type ContainerLogStreamer
- type ContainerLookup
- type ContainerState
- type ContainerStats
- type DaemonEnforcement
- 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 Executor
- 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) SetFreezerResolver(resolver func(nodeID string) ContainerFreezer)
- 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 Locator
- type ModuleVolumeMount
- type NodeProbe
- type NodeStore
- type PlacementEngine
- type PlacementStore
- type PlacementStrategy
- type PoolStats
- type ReconcileOptions
- type ReconcileStore
- type RecreateContainerResult
- type ResourceEnforcementView
- type RouteRefresher
- type RuntimeIssue
- type RuntimeIssueCode
- type RuntimeIssueSeverity
- type RuntimeProfile
- type RuntimeSpec
- type SleepCommander
- type SleepController
- type SleepControllerResolver
- type SleeperStore
- type StorageTransport
- type Transition
- 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 ( RuntimeFatal = runtimeprofile.RuntimeFatal RuntimeWarning = runtimeprofile.RuntimeWarning RuntimeIssueDataMountMissing = runtimeprofile.RuntimeIssueDataMountMissing RuntimeIssueDataMountReadOnly = runtimeprofile.RuntimeIssueDataMountReadOnly RuntimeIssueRootfsReadOnlyNsswitch = runtimeprofile.RuntimeIssueRootfsReadOnlyNsswitch RuntimeIssueBootstrapCapabilitiesMissing = runtimeprofile.RuntimeIssueBootstrapCapabilitiesMissing RuntimeIssueNoNewPrivilegesDisabled = runtimeprofile.RuntimeIssueNoNewPrivilegesDisabled RuntimeIssuePrivilegedMode = runtimeprofile.RuntimeIssuePrivilegedMode RuntimeIssueWritableRootfs = runtimeprofile.RuntimeIssueWritableRootfs RuntimeIssueNonNumericUser = runtimeprofile.RuntimeIssueNonNumericUser RuntimeIssueCustomEntrypoint = runtimeprofile.RuntimeIssueCustomEntrypoint RuntimeIssueTmpfsMissing = runtimeprofile.RuntimeIssueTmpfsMissing RuntimeIssueTmpfsTooSmall = runtimeprofile.RuntimeIssueTmpfsTooSmall RuntimeIssueTmpfsExec = runtimeprofile.RuntimeIssueTmpfsExec RuntimeIssueHostNetwork = runtimeprofile.RuntimeIssueHostNetwork RuntimeIssueHostDevice = runtimeprofile.RuntimeIssueHostDevice RuntimeIssueDataOwnerMismatch = runtimeprofile.RuntimeIssueDataOwnerMismatch RuntimeIssueMemoryLimitUnset = runtimeprofile.RuntimeIssueMemoryLimitUnset RuntimeIssueSwapEnabled = runtimeprofile.RuntimeIssueSwapEnabled RuntimeIssuePidsLimitUnset = runtimeprofile.RuntimeIssuePidsLimitUnset RuntimeIssueWritableLayerUnbounded = runtimeprofile.RuntimeIssueWritableLayerUnbounded RuntimeIssueStorageQuotaIsNotAWorldQuota = runtimeprofile.RuntimeIssueStorageQuotaIsNotAWorldQuota RuntimeIssueWorldQuotaExceeded = runtimeprofile.RuntimeIssueWorldQuotaExceeded RuntimeIssueWorldQuotaUnmeasured = runtimeprofile.RuntimeIssueWorldQuotaUnmeasured RuntimeIssueWritableLayerCapIgnored = runtimeprofile.RuntimeIssueWritableLayerCapIgnored RuntimeIssueMemoryLimitUnsupported = runtimeprofile.RuntimeIssueMemoryLimitUnsupported RuntimeIssueSwapLimitUnsupported = runtimeprofile.RuntimeIssueSwapLimitUnsupported RuntimeIssuePidsLimitUnsupported = runtimeprofile.RuntimeIssuePidsLimitUnsupported RuntimeIssueRootlessCgroupUnqualified = runtimeprofile.RuntimeIssueRootlessCgroupUnqualified RuntimeIssueWritableLayerCapUnsupported = runtimeprofile.RuntimeIssueWritableLayerCapUnsupported RuntimeIssueImageUnpinned = runtimeprofile.RuntimeIssueImageUnpinned RuntimeIssueRootlessHostRootData = runtimeprofile.RuntimeIssueRootlessHostRootData RuntimeIssueReadOnlyRootUserMod = runtimeprofile.RuntimeIssueReadOnlyRootUserMod RuntimeIssueSensitiveMount = runtimeprofile.RuntimeIssueSensitiveMount RuntimeIssueTmpfsReplaced = runtimeprofile.RuntimeIssueTmpfsReplaced )
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 )
const ( // LabelInstallation records which controller installation created a container. // Startup reconciliation only adopts or purges containers carrying this // installation's identity (or legacy containers that match a live DB record). LabelInstallation = "carbon-panel.installation" )
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 ( ErrUnknownNode = errors.New("docker: unknown node") ErrNoClient = errors.New("docker: no client available") )
Typed locator failures. Callers can distinguish an unknown node from a node whose daemon is temporarily unavailable; neither is ever (nil, nil).
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 ErrDaemonIdentity = errors.New("docker: daemon identity mismatch")
ErrDaemonIdentity is returned when a node answers with a different Docker daemon than the one already accepted for that endpoint.
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.
var ErrFirewallUnsupported = errors.New("DOCKER-USER firewall enforcement is not available on this host")
ErrFirewallUnsupported means rate limiting or proxy isolation was requested and this host cannot apply DOCKER-USER rules. It is not a successful apply.
var ErrRuntimeIncompatible = runtimeprofile.ErrRuntimeIncompatible
var ErrTransitionInFlight = errors.New("server transition already in progress")
ErrTransitionInFlight reports that another lifecycle operation already owns the server.
var ErrTransitionServerID = errors.New("server transition requires a server ID")
ErrTransitionServerID reports a lifecycle operation that supplied no server ID to own.
Functions ¶
func AdditionalPortHostIP ¶ added in v1.0.40
AdditionalPortHostIP is the host address Docker publishes an extra port on.
func ApplyDiskQuota ¶ added in v1.0.39
func ApplyDiskQuota(hostConfig *container.HostConfig, diskMB int64)
ApplyDiskQuota sets a container storage size limit when the storage driver supports it (overlay2 size opt). diskMB <= 0 disables the limit.
func ApplyOverrides ¶
func ApplyOverrides(overrides *v1.DockerOverrides, config *container.Config, hostConfig *container.HostConfig)
ApplyOverrides applies DockerOverrides to container and host configs
func CanonicalServerImage ¶ added in v1.0.40
CanonicalServerImage returns the value to persist. Bare itzg/minecraft-server tags stay tags. Allowlisted full references are normalized. Anything else is rejected.
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 IsMinecraftImage ¶ added in v1.0.40
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)
- CARBON_WRITABLE_ROOTFS, which turns off the read-only root
Benign fields (PidsLimit, CpusetCpus, ReadOnly, CapDrop, "no-new-privileges:true", etc.) never make this return true.
func LoadOrCreateInstallationID ¶ added in v1.0.39
LoadOrCreateInstallationID returns the stable identity of this controller installation, creating it once under dataDir if it does not exist yet.
The identity lives next to the panel database so that upgrading, restarting or restoring an older database of the same installation keeps the same ownership scope. A second panel installation sharing a Docker daemon has a different data directory and therefore a different identity.
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 (native backups and restores stage archives under {{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 NewAPIClientContext ¶ added in v1.0.40
NewAPIClientContext carries the caller's lifetime through eager negotiation. A canceled construction closes its client rather than caching a live handle.
func PreflightProfile ¶ added in v1.0.40
func PreflightProfile(profile RuntimeProfile) error
func PreflightRuntime ¶ added in v1.0.40
func PreflightRuntime(spec RuntimeSpec) error
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, opts ReconcileOptions) error
ReconcileAndCleanupContainers performs safe, two-phase startup reconciliation of containers Carbon Panel manages.
Ownership: every container is classified by its carbon-panel.installation label. Containers created by another installation are never adopted, stopped or removed. Legacy containers (created before installation labels existed) may be adopted when a live DB record matches, because adoption only repairs the stored ContainerID; they are never purged automatically.
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 quarantined or, only for containers owned by this installation with ReconcileOptions.PurgeOrphans set, queued for phase 2.
Phase 2 (purge): only containers queued as owned orphans in phase 1 are stopped and removed, and ownership is revalidated against the daemon immediately before removal. 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 ResolveServerImage ¶ added in v1.0.40
ResolveServerImage returns the daemon reference for a stored server image.
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 SetTransitionWarner ¶ added in v1.0.39
SetTransitionWarner installs the callback used to warn about long-held lifecycle transitions. Passing nil restores the silent default.
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 TransitionDebug ¶ added in v1.0.39
TransitionDebug describes the current holder of serverID's lifecycle transition, for diagnostics. It returns "" when no transition is in flight.
func TranslateToHostPath ¶
TranslateToHostPath converts a path this process sees into the path the Docker daemon understands.
The mapping is resolved once at startup from the panel's own container mounts (see internal/hostmount), so no environment variable has to restate the volume mapping. A process that has not resolved one keeps the historical environment fallback; when nothing is configured the path is returned unchanged, which is correct for a panel running directly on the host.
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 network modes that do not publish the host ports the panel leases. "host" and "none" do not publish port bindings. "container:<name>" joins another container's network stack and ignores this container's bindings. Bridge and named networks still publish the leased address, protocol, and port.
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 NewClientForNodeContext ¶ added in v1.0.40
func NewClientForNodeContext(ctx context.Context, node *models.Node, log *logger.Logger, baseConfig ClientConfig) (*Client, error)
NewClientForNodeContext cancels node construction and owned network setup with the initiating operation, while keeping the legacy bounded wrappers.
func (*Client) AllocatedHostPorts ¶ added in v1.0.40
AllocatedHostPorts returns host ports published with protocol. protocol is "tcp" or "udp". An empty protocol includes every published port. A UDP publish does not occupy the same number on TCP.
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) DaemonEnforcement ¶ added in v1.0.40
func (c *Client) DaemonEnforcement(ctx context.Context) (DaemonEnforcement, error)
DaemonEnforcement reads /info and reports which limits the daemon can apply.
func (*Client) DaemonID ¶ added in v1.0.40
DaemonID is the Docker daemon id reported by Info. An empty id is an error so a caller cannot accept an unnamed daemon.
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) EnsureNetworkContext ¶ added in v1.0.40
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 host ports published by running containers for every protocol.
func (*Client) GetConfig ¶
func (c *Client) GetConfig() ClientConfig
func (*Client) GetContainerStats ¶
func (*Client) GetContainerStatus ¶
func (*Client) GetDockerClient ¶
GetDockerClient returns the underlying Docker client
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) ImageStoreTotalBytes ¶ added in v1.0.40
ImageStoreTotalBytes reports deduplicated Docker image-store bytes on the node.
func (*Client) IsRemote ¶ added in v1.0.39
IsRemote reports whether this client talks to a Docker daemon whose filesystem is not the panel process's filesystem. Remote daemons create bind sources through Docker's mount handling; the panel must not create a same- named directory locally and accidentally treat it as server storage.
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)
RecreateContainer replaces a server's container reversibly (OSS-230). The replacement is preflighted (ports and image) before the known-good container is touched; the old container is stopped and retained under a renamed identity until the replacement is created and started according to the preserved run intent. Any failure after that point rolls back to the old identity instead of leaving the server without an executable container.
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.
When an installation identity is configured the label lookup is scoped to it, so a stale database restored from another installation cannot resolve (and operate on) that installation's container. Legacy containers remain reachable through the name fallback.
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) ResolveModuleContainerPreferring ¶ added in v1.0.40
func (c *Client) ResolveModuleContainerPreferring(ctx context.Context, moduleID, recordedID string) (*container.Summary, error)
ResolveModuleContainerPreferring is ResolveModuleContainer with a recorded container id that stays preferred while it is still alive, so ports do not flip to a sibling labeled container.
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) SelfMounts ¶ added in v1.0.40
SelfMounts reports the mounts of the container this process is running in, so startup can work out where the daemon sees the data directory without an operator-maintained environment variable.
A nil slice with a nil error means this process is not a container the daemon knows about, which is the normal case for a panel running on the host.
func (*Client) ServerImageID ¶ added in v1.0.40
ServerImageID is the daemon identity of the server's resolved image. An image built for another OS or architecture is not that identity.
func (*Client) ServerImageIdentity ¶ added in v1.0.40
func (c *Client) ServerImageIdentity(ctx context.Context, server *models.Server) (string, string, error)
ServerImageIdentity is the daemon image ID and the registry repo digest for the server's resolved image. The digest is empty when this repository has no repo digest on the daemon. An image built for another OS or architecture is not an identity.
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) SetRestartPolicy ¶ added in v1.0.39
func (c *Client) SetRestartPolicy(ctx context.Context, containerID string, policy container.RestartPolicy) error
SetRestartPolicy updates a live container's restart policy. Deep sleep sets "no" before stopping the JVM, and wake restores DefaultRestartPolicy.
func (*Client) StartContainer ¶
func (*Client) StopContainer ¶
StopContainer stops a container using the default save window. Returns (containerFound, error). A missing container returns (false, nil).
func (*Client) StopContainerWithin ¶
func (c *Client) StopContainerWithin(ctx context.Context, containerID string, window time.Duration) (bool, error)
StopContainerWithin asks the JVM to stop, then waits window before SIGKILL.
func (*Client) TailContainerLogs ¶ added in v1.0.40
func (c *Client) TailContainerLogs(ctx context.Context, containerID string, tailLines int) ([]string, error)
TailContainerLogs returns the last tailLines of a container's combined stdout/stderr log, each prefixed with its daemon timestamp ("2006-01-02T15:04:05.999Z message"), oldest first. It is a one-shot read for failure detection, not a stream: callers that need live output use the log streamer instead.
type ClientConfig ¶
type ClientConfig struct {
APIVersion string
NetworkName string
NetworkMTU int
RegistryURL string
DNS string
Labels map[string]string
EnableRateLimit bool
RateLimitPerMin int
RateLimitBurst int
ProxyEnabled bool
// InstallationID identifies this controller installation. It is written to
// every managed container so reconciliation and name-conflict handling can
// distinguish this panel from another installation sharing a daemon.
InstallationID string
// ContainerWritableMB caps the container writable layer on a writable
// root. It never bounds a bind-mounted world and is ignored when the root
// is read-only.
ContainerWritableMB int64
// WorldQuotaMB refuses create when measured world bytes meet or exceed
// this many mebibytes. 0 disables. Not a daemon or xfs world quota.
WorldQuotaMB int64
}
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. A named node that cannot be resolved returns an error. It is not served by the local daemon. Empty, "local", the default node id, and a node marked local use the controller client.
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) GetClientStrictContext ¶ added in v1.0.40
GetClientStrictContext resolves and constructs a node client within the operation lifetime. Cancellation never substitutes the controller client.
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) ProbeNodes ¶ added in v1.0.40
func (p *ClientPool) ProbeNodes(ctx context.Context) ([]NodeProbe, error)
ProbeNodes pings every enabled node in parallel. An empty result means the pool has no node inventory to fan out to; callers should fall back to the default client. Listing the inventory is an observation: a list error is returned so health can report unknown rather than inventing an outage.
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 records the historical fallback flag. A named node is never served by the local daemon, whether or not the flag is set. Local aliases ("", "local", the default node id, and a node marked local) still use the controller client.
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 ContainerLimits ¶ added in v1.0.40
type ContainerLimits = runtimeprofile.ContainerLimits
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
// StartedAt is when the container process last (re)started, zero when
// Docker did not report one. Failure detection scopes log evidence to
// lines at or after it so a previous boot's crash cannot paint a fresh
// boot red.
StartedAt time.Time
}
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 DaemonEnforcement ¶ added in v1.0.40
type DaemonEnforcement = runtimeprofile.DaemonEnforcement
DaemonEnforcement is the public daemon capability record. DescribeDaemonEnforcement maps a Docker /info payload onto it.
func DescribeDaemonEnforcement ¶ added in v1.0.40
func DescribeDaemonEnforcement(info system.Info) DaemonEnforcement
DescribeDaemonEnforcement maps a Docker /info payload into the panel's qualification view. It uses the daemon's own capability flags instead of guessing from the OS string alone.
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 Executor ¶ added in v1.0.39
type Executor interface {
ExecCommand(ctx context.Context, containerID string, command string) (string, error)
}
Executor is the command-execution subset used by the command sender.
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. A requested apply on a host with no iptables returns ErrFirewallUnsupported instead of a successful result.
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) SetFreezerResolver ¶ added in v1.0.39
func (m *HibernationManager) SetFreezerResolver(resolver func(nodeID string) ContainerFreezer)
SetFreezerResolver installs a node-aware freezer resolver. The resolver is authoritative for explicit node IDs; the configured freezer remains the local fallback for empty/local/default aliases.
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 Locator ¶ added in v1.0.39
type Locator struct {
// contains filtered or unexported fields
}
Locator is the single adapter from a logical node to the Docker daemon or command executor that serves it. It owns local aliases, the standalone-client fallback, and store-backed local identity checks.
func NewExecutorLocator ¶ added in v1.0.39
func NewExecutorLocator(pool *ClientPool, local Executor, store NodeStore) *Locator
NewExecutorLocator returns a locator for command executors. It exists because the command sender accepts a testable Executor rather than a concrete client.
func NewLocator ¶ added in v1.0.39
func NewLocator(pool *ClientPool, local *Client, store NodeStore) *Locator
NewLocator returns a client locator. local may be nil when a pool is configured. store may be nil when the pool carries its own NodeStore.
func (*Locator) ExecutorFor ¶ added in v1.0.39
ExecutorFor is For cast to the command-execution interface.
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 NodeProbe ¶ added in v1.0.40
type NodeProbe struct {
Reachable bool
}
NodeProbe is one enabled node's reachability. It carries no hostname or secret: health aggregates these into counts.
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 ReconcileOptions ¶ added in v1.0.39
type ReconcileOptions struct {
// PurgeOrphans removes containers that this installation provably created but
// the DB no longer knows about. It defaults to false: orphaned, legacy and
// foreign containers are quarantined (reported, left running) unless an
// operator explicitly opts in after verifying them.
PurgeOrphans bool
}
ReconcileOptions controls startup reconciliation behaviour.
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.
// It is the original ID while the old container is retained — including
// after a rollback to it — and the replacement's ID after a verified
// cutover, or after a partial create that could not be rolled back.
NewContainerID string
WasRunning bool
// ImageID is the daemon identity of the image the replacement came up
// with. It is empty when the old container remains the one that runs.
ImageID string
// RepoDigest is the registry digest of that same image, when the daemon
// has one for the requested repository. It is not ImageID.
RepoDigest string
}
Result of a container recreation operation
type ResourceEnforcementView ¶ added in v1.0.40
type ResourceEnforcementView struct {
RequestedMemoryBytes int64
EffectiveMemoryBytes int64
RequestedWritableLayerMB int64
EffectiveWritableLayerMB int64
WorldDiskEnforced bool
WorldQuotaAdmission bool
MemoryEnforced bool
Warnings []string
}
ResourceEnforcementView is the API/console view of requested versus effective limits. MemoryEnforced is false until /info qualification says the cap applies. WorldDiskEnforced is never set from storage-opt.
func ViewResourceEnforcement ¶ added in v1.0.40
func ViewResourceEnforcement(profile RuntimeProfile, daemonQualified bool, worldQuotaMB int64) ResourceEnforcementView
ViewResourceEnforcement maps a runtime profile onto the console contract. daemonQualified is true only when Docker /info was read for this view.
type RouteRefresher ¶
type RouteRefresher func(serverID string)
RouteRefresher re-resolves a server's proxy route after a transition.
type RuntimeIssue ¶ added in v1.0.40
type RuntimeIssue = runtimeprofile.RuntimeIssue
type RuntimeIssueCode ¶ added in v1.0.40
type RuntimeIssueCode = runtimeprofile.RuntimeIssueCode
type RuntimeIssueSeverity ¶ added in v1.0.40
type RuntimeIssueSeverity = runtimeprofile.RuntimeIssueSeverity
type RuntimeProfile ¶ added in v1.0.40
type RuntimeProfile = runtimeprofile.RuntimeProfile
func DescribeConfiguredResourceLimits ¶ added in v1.0.40
func DescribeConfiguredResourceLimits(requestedMemoryMB, writableLayerMB, worldQuotaMB, worldBytes int64, daemon *DaemonEnforcement) RuntimeProfile
DescribeConfiguredResourceLimits builds a RuntimeProfile for the configured memory/writable-layer/world-quota request against optional daemon /info.
func DescribeRuntime ¶ added in v1.0.40
func DescribeRuntime(spec RuntimeSpec) RuntimeProfile
type RuntimeSpec ¶ added in v1.0.40
type RuntimeSpec = runtimeprofile.RuntimeSpec
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)
// SetRestartPolicy changes the container restart policy without recreating it.
SetRestartPolicy(ctx context.Context, containerID string, policy container.RestartPolicy) 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.
type StorageTransport ¶ added in v1.0.40
type StorageTransport struct {
// contains filtered or unexported fields
}
StorageTransport runs the carbon-storage accessor worker on remote daemons through a one-shot attached container (OSS-281).
func NewStorageTransport ¶ added in v1.0.40
func NewStorageTransport(pool *ClientPool, log *logger.Logger, workerImage string) *StorageTransport
NewStorageTransport constructs a nodestorage.Transport backed by Docker.
func (*StorageTransport) Open ¶ added in v1.0.40
func (t *StorageTransport) Open(ctx context.Context, node nodestorage.NodeInfo, dataRoot string) (nodestorage.Accessor, error)
Open implements nodestorage.Transport.
type Transition ¶ added in v1.0.39
type Transition struct {
// contains filtered or unexported fields
}
Transition is one lifecycle operation's claim on a server. It is the only handle that can release the claim, so a caller cannot clear a transition it never acquired. Release is idempotent and safe to defer.
func TryBeginServerTransition ¶
func TryBeginServerTransition(serverID string) (*Transition, error)
TryBeginServerTransition claims the lifecycle transition for serverID.
func (*Transition) Done ¶ added in v1.0.39
func (t *Transition) Done() <-chan struct{}
Done is closed once the transition is released.
func (*Transition) Release ¶ added in v1.0.39
func (t *Transition) Release()
Release ends the transition. It removes the registration only while this handle still owns it, so releasing a stale handle cannot evict a later owner that has since claimed the server.
func (*Transition) ServerID ¶ added in v1.0.39
func (t *Transition) ServerID() string
ServerID is the server this transition owns.
Source Files
¶
- cleanup.go
- client.go
- container_logs.go
- daemon_enforcement.go
- detect.go
- firewall.go
- freezer.go
- hardening.go
- idle.go
- image_ensure.go
- image_ref.go
- image_store.go
- installation.go
- locator.go
- log_resolver.go
- module.go
- placement.go
- pool.go
- resource_enforcement.go
- runtime_owner_unix.go
- runtime_profile.go
- sleep.go
- stop.go
- storage_transport.go
- transition.go
- work_temp.go