sdk

package
v0.0.0-...-34138cd Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package sdk provides the hadron public sdk for plans

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNetworkCheck indicates failure checking if Docker network exists.
	ErrNetworkCheck = errors.New("failed to check network existence")

	// ErrNetworkCreate indicates failure creating Docker network.
	ErrNetworkCreate = errors.New("failed to create network")

	// ErrVolumeCheck indicates failure checking if Docker volume exists.
	ErrVolumeCheck = errors.New("failed to check volume existence")

	// ErrVolumeCreate indicates failure creating Docker volume.
	ErrVolumeCreate = errors.New("failed to create volume")

	// ErrContainerCheck indicates failure checking if Docker container exists.
	ErrContainerCheck = errors.New("failed to check container existence")
)
View Source
var ErrFailedLoadingGluon = errors.New("Failed to load gluon manifest")
View Source
var ErrFailedRetrievingCredentials = errors.New("Failed to retrieve credentials")
View Source
var ErrNoSuchImage = errors.New("No such image")

Functions

func ConfigureDefaultLogger

func ConfigureDefaultLogger(ctx context.Context, level ...zerolog.Level)

ConfigureDefaultLogger configures the global zerolog logger with sensible defaults. It uses a console writer with RFC3339 timestamps for human-readable output. If a log level is provided, it sets that level. Otherwise, it reads from the LOG_LEVEL environment variable (defaults to "info" if not set or invalid). Wraps Hadron's ConfigureDefaultLogger for convenience.

func FromGluon

func FromGluon(ctx context.Context, plan *sdk.Plan, name, filepath string) (*sdk.Image, error)

func GetEnv

func GetEnv(key string) (string, error)

GetEnv retrieves a required environment variable. Returns an error if the variable does not exist. Empty values (FOO="") are allowed and will not cause an error.

func GetEnvWithFallback

func GetEnvWithFallback(key, defaultValue string) string

GetEnvWithFallback retrieves an environment variable or returns a default value. Wraps Hadron's GetEnvWithFallback for convenience.

func GetSecret

func GetSecret(ctx context.Context, itemRef string, fields []string) (map[string]string, error)

func LoadEnv

func LoadEnv(path string) error

LoadEnv loads environment variables from a .env file. Wraps Hadron's LoadEnv for convenience.

Types

type Container

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

Container represents a Docker container.

func (*Container) ConfigHash

func (c *Container) ConfigHash() string

ConfigHash returns a SHA256 hash of the container configuration. Used for idempotent deployments.

func (*Container) DependsOn

func (c *Container) DependsOn() []*Container

DependsOn returns the containers this container depends on.

func (*Container) HealthCheck

func (c *Container) HealthCheck() *HealthCheck

HealthCheck returns the health check configuration.

func (*Container) Host

func (c *Container) Host() *Host

Host returns the host where this container runs.

func (*Container) Image

func (c *Container) Image() string

Image returns the container image.

func (*Container) Name

func (c *Container) Name() string

Name returns the container name.

func (*Container) NetworkAlias

func (c *Container) NetworkAlias() string

NetworkAlias returns the DNS alias for this container.

type ContainerBuilder

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

ContainerBuilder builds a Container with a fluent API.

func (*ContainerBuilder) Build

func (cb *ContainerBuilder) Build() *Container

Build creates the Container and registers it with the plan.

func (*ContainerBuilder) CPUShares

func (cb *ContainerBuilder) CPUShares(shares int64) *ContainerBuilder

CPUShares sets the CPU shares (relative weight) for the container.

func (*ContainerBuilder) CPUs

func (cb *ContainerBuilder) CPUs(cpus string) *ContainerBuilder

CPUs sets the hard CPU limit for the container (e.g., "1.5" for 1.5 CPUs).

func (*ContainerBuilder) CapAdd

func (cb *ContainerBuilder) CapAdd(capability string) *ContainerBuilder

CapAdd adds a Linux capability.

func (*ContainerBuilder) CapDrop

func (cb *ContainerBuilder) CapDrop(capability string) *ContainerBuilder

CapDrop drops a Linux capability.

func (*ContainerBuilder) Command

func (cb *ContainerBuilder) Command(args ...string) *ContainerBuilder

Command sets optional command arguments to append to docker run. These arguments are passed after the image name: docker run [OPTIONS] IMAGE [COMMAND...].

func (*ContainerBuilder) DependsOn

func (cb *ContainerBuilder) DependsOn(container *Container) *ContainerBuilder

DependsOn adds a dependency on another container. This container will start after the dependency is healthy.

func (*ContainerBuilder) Env

func (cb *ContainerBuilder) Env(key, value string) *ContainerBuilder

Env sets an environment variable.

func (*ContainerBuilder) EnvFile

func (cb *ContainerBuilder) EnvFile(path string) *ContainerBuilder

EnvFile sets the path to an environment file to load.

func (*ContainerBuilder) ExtraHosts

func (cb *ContainerBuilder) ExtraHosts(mapping string) *ContainerBuilder

ExtraHosts adds a custom host-to-IP mapping (format: "hostname:ip"). Special value "host-gateway" maps to the host's gateway IP. Example: ExtraHosts("host.docker.internal:host-gateway").

func (*ContainerBuilder) GroupAdd

func (cb *ContainerBuilder) GroupAdd(group string) *ContainerBuilder

GroupAdd adds an additional group for the container user. Useful for granting access to host resources (e.g., "docker" for socket access).

func (*ContainerBuilder) HealthCheck

func (cb *ContainerBuilder) HealthCheck(check *HealthCheck) *ContainerBuilder

HealthCheck sets the health check for this container.

func (*ContainerBuilder) Host

func (cb *ContainerBuilder) Host(host *Host) *ContainerBuilder

Host sets the host where this container will run.

func (*ContainerBuilder) Hostname

func (cb *ContainerBuilder) Hostname(hostname string) *ContainerBuilder

Hostname sets the hostname for the container.

func (*ContainerBuilder) Image

func (cb *ContainerBuilder) Image(image string) *ContainerBuilder

Image sets the container image (should include digest for immutability).

func (*ContainerBuilder) Label

func (cb *ContainerBuilder) Label(key, value string) *ContainerBuilder

Label sets a Docker label for metadata and service discovery.

func (*ContainerBuilder) Memory

func (cb *ContainerBuilder) Memory(limit string) *ContainerBuilder

Memory sets the memory limit for the container (e.g., "512m", "2g").

func (*ContainerBuilder) MemoryReservation

func (cb *ContainerBuilder) MemoryReservation(limit string) *ContainerBuilder

MemoryReservation sets the memory soft limit for the container.

func (*ContainerBuilder) Mount

func (cb *ContainerBuilder) Mount(localPath, containerPath string, mode ...string) *ContainerBuilder

Mount mounts a local file or directory into the container. The local path is uploaded to the remote host and mounted into the container.

func (*ContainerBuilder) MountData

func (cb *ContainerBuilder) MountData(data []byte, containerPath string, mode ...string) *ContainerBuilder

MountData mounts raw data as a file into the container. The data is content-addressed (SHA256 hash) and uploaded to the remote host. This avoids creating temporary files locally with sensitive data.

func (*ContainerBuilder) Network

func (cb *ContainerBuilder) Network(network *Network) *ContainerBuilder

Network sets the Docker network for this container. Network adds a network to the container. Can be called multiple times to connect to multiple networks.

func (*ContainerBuilder) NetworkAlias

func (cb *ContainerBuilder) NetworkAlias(alias string) *ContainerBuilder

NetworkAlias sets a DNS alias for this container on the network.

func (*ContainerBuilder) PIDsLimit

func (cb *ContainerBuilder) PIDsLimit(limit int64) *ContainerBuilder

PIDsLimit sets the maximum number of PIDs (process limit) for the container.

func (*ContainerBuilder) Port

func (cb *ContainerBuilder) Port(port string) *ContainerBuilder

Port adds a port mapping (format: "host:container" or "port").

func (*ContainerBuilder) ReadOnly

func (cb *ContainerBuilder) ReadOnly() *ContainerBuilder

ReadOnly sets the container filesystem to read-only.

func (*ContainerBuilder) Restart

func (cb *ContainerBuilder) Restart(policy string) *ContainerBuilder

Restart sets the restart policy (default: unless-stopped).

func (*ContainerBuilder) SecurityOpt

func (cb *ContainerBuilder) SecurityOpt(opt string) *ContainerBuilder

SecurityOpt adds a security option.

func (*ContainerBuilder) Tmpfs

func (cb *ContainerBuilder) Tmpfs(mountPoint string, options ...string) *ContainerBuilder

Tmpfs mounts a tmp filesysten ("/tmp", "size=100m") -> results in "noexec,nosuid,nodev,size=100m".

func (*ContainerBuilder) User

func (cb *ContainerBuilder) User(user string) *ContainerBuilder

User sets the user to run the container as (user:group or UID:GID).

func (*ContainerBuilder) Volume

func (cb *ContainerBuilder) Volume(source any, target string, mode ...string) *ContainerBuilder

Volume can be used for bind mounts: ("/host/path", "/container/path", "ro").

type DataMount

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

DataMount represents raw data mounted as a file into a container.

type FileMount

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

FileMount represents a local file or directory mounted into a container.

type FirewallBuilder

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

FirewallBuilder builds firewall configuration with a fluent API.

func (*FirewallBuilder) Allow

func (fb *FirewallBuilder) Allow(port int, protocol string) *FirewallRuleBuilder

Allow adds a firewall rule to allow a port.

func (*FirewallBuilder) ClearDefaultRules

func (fb *FirewallBuilder) ClearDefaultRules() *FirewallBuilder

ClearDefaultRules removes the default SSH/HTTP/HTTPS rules. Useful if you want full control over rules.

func (*FirewallBuilder) DefaultIncoming

func (fb *FirewallBuilder) DefaultIncoming(policy string) *FirewallBuilder

DefaultIncoming sets the default policy for incoming traffic.

func (*FirewallBuilder) DefaultOutgoing

func (fb *FirewallBuilder) DefaultOutgoing(policy string) *FirewallBuilder

DefaultOutgoing sets the default policy for outgoing traffic.

func (*FirewallBuilder) Done

func (fb *FirewallBuilder) Done() *HostBuilder

Done finalizes firewall configuration and returns to host builder.

type FirewallConfig

type FirewallConfig struct {
	Enabled         bool
	DefaultIncoming string // "deny" or "allow"
	DefaultOutgoing string // "deny" or "allow"
	Rules           []FirewallRule
}

FirewallConfig represents firewall configuration for a host.

type FirewallRule

type FirewallRule struct {
	Port      int
	Protocol  string // "tcp" or "udp"
	Comment   string
	RateLimit bool
}

FirewallRule represents a single firewall rule.

type FirewallRuleBuilder

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

FirewallRuleBuilder builds a single firewall rule.

func (*FirewallRuleBuilder) Comment

func (frb *FirewallRuleBuilder) Comment(comment string) *FirewallRuleBuilder

Comment sets a comment for the rule.

func (*FirewallRuleBuilder) Done

func (frb *FirewallRuleBuilder) Done() *FirewallBuilder

Done finalizes this rule and returns to firewall builder.

func (*FirewallRuleBuilder) RateLimit

func (frb *FirewallRuleBuilder) RateLimit() *FirewallRuleBuilder

RateLimit enables rate limiting for this rule (useful for SSH).

type HealthCheck

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

HealthCheck represents a container health check configuration.

func CommandCheck

func CommandCheck(command string, args ...string) *HealthCheck

CommandCheck creates a command-based health check. Accepts command and optional arguments: CommandCheck("curl", "-f", "http://localhost/health").

func HTTPCheck

func HTTPCheck(path string, port int) *HealthCheck

HTTPCheck creates an HTTP health check.

func TCPCheck

func TCPCheck(port int) *HealthCheck

TCPCheck creates a TCP health check.

func UDPCheck

func UDPCheck(port int) *HealthCheck

UDPCheck creates a UDP health check.

func (*HealthCheck) String

func (hc *HealthCheck) String() string

String returns a string representation of the health check.

func (*HealthCheck) WithInterval

func (hc *HealthCheck) WithInterval(interval time.Duration) *HealthCheck

WithInterval sets the interval between health check attempts.

func (*HealthCheck) WithRetries

func (hc *HealthCheck) WithRetries(retries int) *HealthCheck

WithRetries sets the number of retries before marking as unhealthy.

func (*HealthCheck) WithTimeout

func (hc *HealthCheck) WithTimeout(timeout time.Duration) *HealthCheck

WithTimeout sets the total timeout for the health check.

type HealthCheckType

type HealthCheckType string

HealthCheckType defines the type of health check.

const (
	// HealthCheckHTTP performs an HTTP GET request.
	HealthCheckHTTP HealthCheckType = "http"
	// HealthCheckTCP performs a TCP connection check.
	HealthCheckTCP HealthCheckType = "tcp"
	// HealthCheckUDP performs a UDP connection check.
	HealthCheckUDP HealthCheckType = "udp"
	// HealthCheckCommand executes a command inside the container.
	HealthCheckCommand HealthCheckType = "command"
)

type Host

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

Host represents a remote Docker host accessible via SSH.

func (*Host) Endpoint

func (h *Host) Endpoint() string

Endpoint returns the SSH endpoint (IP, hostname, or SSH config alias).

func (*Host) SSHFingerprint

func (h *Host) SSHFingerprint() string

SSHFingerprint returns the configured SSH host key fingerprint, or empty string if not set.

func (*Host) SSHKeyContent

func (h *Host) SSHKeyContent() string

SSHKeyContent returns the configured SSH private key content, or empty string if not set.

func (*Host) String

func (h *Host) String() string

String returns a string representation of the host.

type HostBuilder

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

HostBuilder builds a Host with a fluent API.

func (*HostBuilder) Build

func (hb *HostBuilder) Build() *Host

Build creates the Host and registers it with the plan.

func (*HostBuilder) Fingerprint

func (hb *HostBuilder) Fingerprint(fingerprint string) *HostBuilder

Fingerprint sets the expected SSH host key fingerprint for verification. When set, Hadron will verify the host key matches this fingerprint instead of using ~/.ssh/known_hosts. This is useful for automated deployments where pre-populating known_hosts is not practical.

Supported formats: - SHA256: "SHA256:abc123..." (recommended, obtained via: ssh-keyscan -t ed25519 host | ssh-keygen -lf -) - MD5: "MD5:ab:cd:ef:..." (legacy, not recommended)

Example:

host := plan.Host("user@example.com").
    Fingerprint("SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8").
    Build()

func (*HostBuilder) Firewall

func (hb *HostBuilder) Firewall() *FirewallBuilder

Firewall starts firewall configuration with defaults. Default: deny incoming, allow outgoing, SSH (22) allowed with rate limiting.

func (*HostBuilder) HardenDocker

func (hb *HostBuilder) HardenDocker() *HostBuilder

HardenDocker enables Docker daemon security hardening. Applies recommended security settings from deploy-security.md: - live-restore: true (containers survive daemon restarts) - userland-proxy: false (better performance, uses iptables) - no-new-privileges: true (prevents privilege escalation) - icc: false (containers can't talk unless explicitly networked) - log-driver limits (prevents disk exhaustion).

func (*HostBuilder) HardenOS

func (hb *HostBuilder) HardenOS() *HostBuilder

HardenOS enables OS-level security hardening via sysctl. Applies balanced kernel parameter tuning that: - Enables SYN flood protection (tcp_syncookies) - Disables ICMP redirects (prevents MITM) - Restricts kernel information disclosure (dmesg, kptr) - Enables process isolation (ptrace_scope) - Protects against symlink/hardlink attacks - Optimizes network stack for security

Configuration is Docker-compatible and doesn't break normal operations. Settings are written to /etc/sysctl.d/99-hadron-security.conf.

func (*HostBuilder) HardenSSH

func (hb *HostBuilder) HardenSSH() *HostBuilder

HardenSSH enables SSH daemon security hardening. Applies hardened SSH configuration: - Ed25519 host keys only (disables RSA/ECDSA/DSA) - Public key authentication only (no passwords) - Modern cryptography (Curve25519, ChaCha20, AES-GCM) - Disables X11/agent/TCP forwarding - Connection timeouts and rate limiting - Verbose logging for auditing

Configuration is written to /etc/ssh/sshd_config (original backed up). SSH daemon is reloaded (not restarted) to preserve current connections.

func (*HostBuilder) Package

func (hb *HostBuilder) Package(name string) *HostBuilder

Package adds a Debian package to be installed on this host.

func (*HostBuilder) Registry

func (hb *HostBuilder) Registry(registry, username, password string) *HostBuilder

Registry adds Docker registry credentials for this host.

func (*HostBuilder) RemovePackage

func (hb *HostBuilder) RemovePackage(name string) *HostBuilder

RemovePackage adds a Debian package to be removed from this host.

func (*HostBuilder) SSHKey

func (hb *HostBuilder) SSHKey(keyContent string) *HostBuilder

SSHKey sets the SSH private key content for authentication. When set, Hadron will use this key instead of SSH agent for authentication. The key should be in OpenSSH format (PEM).

Note: Only unencrypted keys are supported. For passphrase-protected keys, use SSH agent instead.

Example:

keyContent := "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----"
host := plan.Host("user@example.com").
    SSHKey(keyContent).
    Build()

type Network

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

Network represents a Docker network.

func (*Network) ConfigHash

func (n *Network) ConfigHash() string

ConfigHash returns a SHA256 hash of the network configuration. Used for idempotent deployments.

func (*Network) Driver

func (n *Network) Driver() string

Driver returns the network driver.

func (*Network) Host

func (n *Network) Host() *Host

Host returns the host where this network is deployed.

func (*Network) Name

func (n *Network) Name() string

Name returns the network name.

type NetworkBuilder

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

NetworkBuilder builds a Network with a fluent API.

func (*NetworkBuilder) Build

func (nb *NetworkBuilder) Build() *Network

Build creates the Network and registers it with the plan.

func (*NetworkBuilder) Driver

func (nb *NetworkBuilder) Driver(driver string) *NetworkBuilder

Driver sets the network driver (default: bridge).

func (*NetworkBuilder) Host

func (nb *NetworkBuilder) Host(host *Host) *NetworkBuilder

Host sets the host where this network will be created.

type Package

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

Package represents a Debian package to be installed on a host.

func (*Package) Host

func (p *Package) Host() *Host

Host returns the host where this package will be installed.

func (*Package) Name

func (p *Package) Name() string

Name returns the package name.

type PackageRemoval

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

PackageRemoval represents a Debian package to be removed from a host.

func (*PackageRemoval) Host

func (pr *PackageRemoval) Host() *Host

Host returns the host where this package will be removed.

func (*PackageRemoval) Name

func (pr *PackageRemoval) Name() string

Name returns the package name to be removed.

type Plan

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

Plan represents a deployment plan containing hosts and resources.

func NewPlan

func NewPlan(name string) *Plan

NewPlan creates a new deployment plan with the given name.

func (*Plan) Container

func (p *Plan) Container(name string) *ContainerBuilder

Container creates a new container builder.

func (*Plan) Destroy

func (p *Plan) Destroy() error

Destroy removes all resources defined in the plan.

func (*Plan) DryRun

func (p *Plan) DryRun() error

DryRun shows what would be deployed without actually deploying.

func (*Plan) Execute

func (p *Plan) Execute(ctx context.Context) error

Execute executes the plan by deploying all resources to their respective hosts. Execute runs the plan with the given context.

func (*Plan) Host

func (p *Plan) Host(endpoint string) *HostBuilder

Host creates a new host builder. The endpoint can be an IP address, hostname, or SSH config alias.

func (*Plan) Network

func (p *Plan) Network(name string) *NetworkBuilder

Network creates a new network builder.

func (*Plan) Volume

func (p *Plan) Volume(name string) *VolumeBuilder

Volume creates a new volume builder.

func (*Plan) WithLogger

func (p *Plan) WithLogger(logger zerolog.Logger) *Plan

WithLogger sets the logger for the plan.

type RegistryCredential

type RegistryCredential struct {
	Registry string
	Username string
	Password string
}

RegistryCredential represents credentials for a Docker registry.

type Volume

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

Volume represents a Docker volume.

func (*Volume) ConfigHash

func (v *Volume) ConfigHash() string

ConfigHash returns a SHA256 hash of the volume configuration. Used for idempotent deployments.

func (*Volume) Driver

func (v *Volume) Driver() string

Driver returns the volume driver.

func (*Volume) Host

func (v *Volume) Host() *Host

Host returns the host where this volume is deployed.

func (*Volume) Name

func (v *Volume) Name() string

Name returns the volume name.

type VolumeBuilder

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

VolumeBuilder builds a Volume with a fluent API.

func (*VolumeBuilder) Build

func (vb *VolumeBuilder) Build() *Volume

Build creates the Volume and registers it with the plan.

func (*VolumeBuilder) Driver

func (vb *VolumeBuilder) Driver(driver string) *VolumeBuilder

Driver sets the volume driver (default: local).

func (*VolumeBuilder) Host

func (vb *VolumeBuilder) Host(host *Host) *VolumeBuilder

Host sets the host where this volume will be created.

type VolumeMount

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

VolumeMount represents a volume mount in a container.

Directories

Path Synopsis
Package hash provides file and directory hashing utilities.
Package hash provides file and directory hashing utilities.

Jump to

Keyboard shortcuts

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