system

package
v0.2.13 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package system implements host-level operations including disk mounting and formatting, OS kernel and limit tuning, static XML validation and installation, and systemd unit management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HardwareProfilesOverlayXML added in v0.1.2

func HardwareProfilesOverlayXML(memBytes uint64) string

HardwareProfilesOverlayXML renders a users.d overlay (z_hardware-profiles.xml) sizing external aggregation and sort spill thresholds to the host's physical RAM so queries/backfills spill to disk before hitting max_server_memory_usage_to_ram_ratio (Code 241).

func HardwareSizingOverlayXML added in v0.1.2

func HardwareSizingOverlayXML(vcpus int, memBytes uint64, cacheDisks ...CacheDiskSizing) string

func LookPath

func LookPath(bin string) (string, error)

LookPath reports whether a binary exists (the golden-AMI require step).

func ValidateConfigSemantics

func ValidateConfigSemantics(path string, data []byte) error

ValidateConfigSemantics walks one config fragment's element tree and rejects the settings-placement patterns that crash ClickHouse at STARTUP — the three fatal classes the convergence audit found in shipped config templates (Code 137 user-level settings at top level; Code 115 merge_tree-scoped settings outside <merge_tree>). The server's own startup check is the last line of defense; this is the first — a broken template fails the boot's install step ONCE with a pointed error instead of a crash loop.

func ValidateXML

func ValidateXML(path string) error

ValidateXML checks a ClickHouse config fragment: non-empty, a root element the config-merge parser accepts (<clickhouse> / <yandex>), and well-formed (the Go XML decoder replaces xmllint --noout; no external binary needed).

Why strict: a malformed fragment in config.d makes clickhouse-server refuse to start — the bash script validated before install for exactly this reason, and a broken downloaded bundle must fail the install step loudly instead of poisoning the config directory.

func WriteFile

func WriteFile(path, content string, mode os.FileMode) error

WriteFile converges one file: create parent dirs, write only when the content differs (preserving mtimes when nothing changed), chmod.

Types

type CacheDiskSizing added in v0.2.0

type CacheDiskSizing struct {
	// MountBytes is the total byte capacity of the mounted cache volume
	// (/var/lib/clickhouse/disks). Zero skips the storage_configuration
	// override so storage.xml's static <max_size> remains in effect.
	MountBytes uint64
	// DiskNames lists the cache wrapper disk names declared in
	// storage.xml (e.g. ["s3_cache"] or ["s3_cache", "cas_cache"]).
	// Defaults to ["s3_cache"] when empty.
	DiskNames []string
	// NvmeHot indicates that storage.xml declares a local <nvme_hot> disk
	// under /var/lib/clickhouse/disks/hot/ and this node is an active
	// writer eligible to carve 50% of a large (>=400 GiB) NVMe mount for
	// hot MergeTree inserts/merges while reserving 40% for cache wrappers.
	NvmeHot bool
}

CacheDiskSizing describes the mounted cache filesystem capacity and the cache wrapper disk names (e.g. s3_cache, cas_cache) present in storage.xml that share the mountpoint.

func (CacheDiskSizing) CacheMaxSizeBytes added in v0.2.0

func (c CacheDiskSizing) CacheMaxSizeBytes() uint64

CacheMaxSizeBytes computes the per-wrapper <max_size> in bytes (90% of the mounted cache volume divided evenly across the active cache disk wrappers, or 40% when 50% is carved for <nvme_hot> on large *gd writers).

func (CacheDiskSizing) NvmeHotKeepFreeBytes added in v0.2.11

func (c CacheDiskSizing) NvmeHotKeepFreeBytes() uint64

NvmeHotKeepFreeBytes returns the <keep_free_space_bytes> override for <nvme_hot> when activated (50% of MountBytes, leaving the upper 50% for hot parts and protecting the 40% cache wrapper budget + 10% OS margin).

type CacheDiskSizings added in v0.2.0

type CacheDiskSizings []CacheDiskSizing

CacheDiskSizings is a domain collection of CacheDiskSizing entries.

type CommandError

type CommandError struct {
	Cmd    string
	Output string
	Err    error
}

CommandError captures a failed command with its output for the boot log (the bash exit_if_error context, structured).

func (*CommandError) Error

func (e *CommandError) Error() string

func (*CommandError) Unwrap

func (e *CommandError) Unwrap() error

type DiskManager

type DiskManager struct {

	// Platform selects the first-boot device-candidate set ("azure"
	// mounts by SCSI LUN; empty/aws use the EBS names). The boot wires
	// it from the detected cloud.
	Platform string
	// contains filtered or unexported fields
}

DiskManager mounts the node's data disks by LABEL (never device path NVMe renaming on Graviton renames devices between boots; labels and fstab LABEL= entries survive).

Convergence (what the bash script re-derived every boot, now probed): - label resolves via blkid → device already formatted, just mount - no label but a blank device → mkfs.ext4 -L, then mount - filesystem present with the wrong label → e2label in place - mountpoint already mounted → skip the mount - fstab already has LABEL= → skip the append

func NewDiskManager

func NewDiskManager(runner Runner) *DiskManager

NewDiskManager builds the manager over a runner.

func (*DiskManager) MountAll

func (d *DiskManager) MountAll(ctx context.Context, spec model.BootSpec, hostnameSet func()) ([]MountedDisk, error)

MountAll mounts the role's disks. The metadata disk is Critical (its loss makes S3 data an unreadable pile of parts); cache is BestEffort (falls back to a metadata-disk subdirectory); keeper is BestEffort (keeper runs on default storage when the dedicated disk is missing, with an IOPS-contention warning). The caller (boot step) supplies the retry policy; this function is one convergent pass.

A metadata disk that is not YET VISIBLE returns a plain (retryable) error — never Fatal. EBS volumes attach asynchronously and the first boot pass can legitimately run before the attachment surfaces; the boot step's bootWait policy (30 attempts, ~1 min) is the wait that closes the race. Fatal here would misclassify a transient attach as permanent and abort the boot on a healthy instance: a scale-out can hit mount_data_disks while a volume is still attaching, and a fatal there wedges the ASG instance refresh at half capacity. Fatal stays reserved for the cases a retry cannot cure: the metadata-disk MOUNT itself failing (corrupt fs, device error).

func (*DiskManager) MountDisk

func (d *DiskManager) MountDisk(ctx context.Context, label, mountPoint, device string) (MountedDisk, error)

MountDisk converges one disk to "mounted at mountPoint, in fstab by label". Idempotent: re-running on a mounted, fstab'd disk is a no-op.

func (*DiskManager) ResolveByLabel

func (d *DiskManager) ResolveByLabel(ctx context.Context, label string) (string, error)

ResolveByLabel finds the device carrying LABEL=label, or "" when none.

func (*DiskManager) ResolveCacheDevice added in v0.2.0

func (d *DiskManager) ResolveCacheDevice(ctx context.Context, label, fallbackCandidates, excludeDevice string) (string, error)

ResolveCacheDevice resolves the S3/CAS cache disk: label first (repeat boots), then any blank local ephemeral NVMe instance-store disk (or RAID-0 stripe across multiple ephemeral NVMe disks), falling back to the platform's attached cache volume candidates.

func (*DiskManager) ResolveDevice

func (d *DiskManager) ResolveDevice(ctx context.Context, label, fallbackCandidates string) (string, error)

ResolveDevice resolves a disk: label first (repeat boots), then the first-boot device-path fallback. Returns "" when neither exists yet (the boot step waits and retries — EBS volumes attach asynchronously).

func (*DiskManager) WithPlatform

func (d *DiskManager) WithPlatform(platform string) *DiskManager

WithPlatform pins the first-boot device-candidate selection (the boot wires it from the detected cloud; empty = the AWS-shaped defaults).

type ExecRunner

type ExecRunner struct{}

ExecRunner is the real runner.

func (ExecRunner) Run

func (ExecRunner) Run(ctx context.Context, cmd string, args ...string) (string, error)

Run runs the command, capturing combined stdout+stderr.

type MountedDisk

type MountedDisk struct {
	Label  string
	Device string
	Mount  string
}

MountedDisk describes what a successful mount produced.

type OSTuner

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

OSTuner applies the OS-level optimizations the bash script performed: THP off (latency spikes), file-descriptor limits (ClickHouse holds huge part counts), the sysctl and the systemd drop-in persistence.

Convergence: every knob is checked (file exists / value current) before it is applied — a re-run is a no-op, and a node whose sysctl survived re-imaging skips the writes.

func NewOSTuner

func NewOSTuner(runner Runner) *OSTuner

NewOSTuner builds the tuner over a runner.

func (*OSTuner) RequireBinaries

func (t *OSTuner) RequireBinaries(ctx context.Context, bins []string) error

RequireBinaries verifies the golden-AMI contract: every component the packer image owns must be present, at the pinned version the image build validated. A missing binary is a FatalError — the ASG must replace a node whose image is wrong, not boot it degraded (apt-repo drift installing unvalidated versions was the failure mode the bash guard closed).

func (*OSTuner) Tune

func (t *OSTuner) Tune(ctx context.Context) error

Tune applies every optimization. Failures inside THP/irqbalance are warnings in the original script; disk-visible failures (limits, sysctl) are errors. The method is a single convergent pass — the step's policy retries the whole thing.

type Runner

type Runner interface {
	// Run executes cmd with args and returns combined output. A
	// non-zero exit is an error carrying the output.
	Run(ctx context.Context, cmd string, args ...string) (string, error)
}

Runner executes external commands. Production is ExecRunner (real os/exec); tests inject a recording fake with scripted responses.

type StaticConfigInstaller

type StaticConfigInstaller struct {

	// Role gates the backup-replica-specific overlay installed from the
	// bundle (the settings file is fetched and hash-covered for every
	// role; only the backup node installs it).
	Role model.Role
	// contains filtered or unexported fields
}

StaticConfigInstaller moves the downloaded bundle's static XMLs into /etc/clickhouse-server/config.d with validation and ownership, and retires the pre-chinit hand-written overlays whose duplicate sections would conflict at config-merge time with the rendered files.

func NewStaticConfigInstaller

func NewStaticConfigInstaller(runner Runner) *StaticConfigInstaller

NewStaticConfigInstaller builds the installer.

func (*StaticConfigInstaller) Install

func (i *StaticConfigInstaller) Install(ctx context.Context, bundleDir string) error

Install converges the static configs: validate each bundle XML, copy to its destination, fix ownership/perms. A missing or invalid bundle member is Fatal — the bundle SHA gate should have caught corruption, so reaching here with a bad file means the gate was skipped and the node must not boot half-configured.

func (*StaticConfigInstaller) WithRole

WithRole pins the node's role for the role-conditional overlays.

type UnitFile

type UnitFile struct {
	// Name is the unit filename ("schema-sync.service").
	Name string
	// Content is the full unit body.
	Content string
}

UnitFile describes one systemd unit chinit owns. Unit content is data (not heredocs): chinit subcommands are the ExecStart, so the unit is a thin wrapper — and golden-file tests compare it byte-for-byte.

type UnitInstaller

type UnitInstaller struct {
	// UnitDir is /etc/systemd/system (injectable for tests).
	UnitDir string
	// DropinDir is the clickhouse-server drop-in directory.
	DropinDir string
}

UnitInstaller writes systemd units and drop-ins under the system dirs.

func NewUnitInstaller

func NewUnitInstaller(unitDir string) *UnitInstaller

NewUnitInstaller builds an installer rooted at the given unit dir (production: /etc/systemd/system) with the clickhouse-server drop-in directory beside it.

func (*UnitInstaller) InstallDropin

func (u *UnitInstaller) InstallDropin(name, content string) error

InstallDropin writes one clickhouse-server drop-in.

func (*UnitInstaller) InstallUnits

func (u *UnitInstaller) InstallUnits(units []UnitFile) ([]string, error)

InstallUnits writes every unit and returns the paths written. After a successful call the boot step runs `systemctl daemon-reload` via the runner (kept out of the installer so tests never shell systemctl).

Jump to

Keyboard shortcuts

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