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 ¶
- func HardwareProfilesOverlayXML(memBytes uint64) string
- func HardwareSizingOverlayXML(vcpus int, memBytes uint64, cacheDisks ...CacheDiskSizing) string
- func LookPath(bin string) (string, error)
- func ValidateConfigSemantics(path string, data []byte) error
- func ValidateXML(path string) error
- func WriteFile(path, content string, mode os.FileMode) error
- type CacheDiskSizing
- type CacheDiskSizings
- type CommandError
- type DiskManager
- func (d *DiskManager) MountAll(ctx context.Context, spec model.BootSpec, hostnameSet func()) ([]MountedDisk, error)
- func (d *DiskManager) MountDisk(ctx context.Context, label, mountPoint, device string) (MountedDisk, error)
- func (d *DiskManager) ResolveByLabel(ctx context.Context, label string) (string, error)
- func (d *DiskManager) ResolveCacheDevice(ctx context.Context, label, fallbackCandidates, excludeDevice string) (string, error)
- func (d *DiskManager) ResolveDevice(ctx context.Context, label, fallbackCandidates string) (string, error)
- func (d *DiskManager) WithPlatform(platform string) *DiskManager
- type ExecRunner
- type MountedDisk
- type OSTuner
- type Runner
- type StaticConfigInstaller
- type UnitFile
- type UnitInstaller
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HardwareProfilesOverlayXML ¶ added in v0.1.2
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
HardwareSizingOverlayXML renders a server-level config.d overlay (z_hardware-sizing.xml) proportional to the host's actual vCPU count and physical RAM, plus optional dynamic cache <max_size> sizing when a dedicated cache disk is mounted at /var/lib/clickhouse/disks.
Why: a single cluster CHI spec is shared across heterogeneous roles (e.g. 8-16 vCPU / 64 GiB writers alongside 2-4 vCPU / 8 GiB readers, or writers stepping across a vertical type ladder). Static writer-sized pools (background_pool_size=16) and caches (mark_cache_size=5 GiB) on a 2-vCPU / 4-8 GiB node peg CPU at 100% on background merges and trigger Code 241 OOMs, while clamping chi.yaml down to the smallest node wastes capacity on scaled-up writers.
Every <merge_tree> free-entry threshold is scaled strictly below background_pool_size so ClickHouse 26.x never refuses startup with Code 36 when background_pool_size < 20 (the upstream default of number_of_free_entries_in_pool_to_execute_mutation).
func ValidateConfigSemantics ¶
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 ¶
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.
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
}
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 sharing the mountpoint).
type CacheDiskSizings ¶ added in v0.2.0
type CacheDiskSizings []CacheDiskSizing
CacheDiskSizings is a domain collection of CacheDiskSizing entries.
type CommandError ¶
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 ¶
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 MountedDisk ¶
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 ¶
NewOSTuner builds the tuner over a runner.
func (*OSTuner) RequireBinaries ¶
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).
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 ¶
func (i *StaticConfigInstaller) WithRole(role model.Role) *StaticConfigInstaller
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).