Documentation
¶
Index ¶
- Variables
- type Config
- func (c *Config) AllowedBrowserOrigins() []string
- func (c *Config) BuildLogStore() *logstore.Store
- func (c *Config) DeploymentURL() string
- func (c *Config) InitStorage()
- func (c *Config) InitWorker() error
- func (c *Config) Initialize(app *okapi.Okapi) error
- func (c *Config) LogLevelFor() (logger.LogLevel, error)
- type DatabaseConfig
- type LogStoreConfig
- type RedisConfig
- type RegistryConfig
- type SystemSMTPConfig
Constants ¶
This section is empty.
Variables ¶
var ( Version = "dev" CommitID = "unknown" )
Build information, overridable at link time via -ldflags.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
Database DatabaseConfig
Redis RedisConfig
Env string
Port int
DevMode bool
// LogLevel is MIABI_LOG_LEVEL: debug | info | warn | error | off. Empty follows
// the environment — debug in dev, info otherwise — which is what it did before
// this was configurable.
LogLevel string
JWTSecret string
EncryptionKey string
AdminEmail string
AdminPassword string
PasswordResetEnabled bool
OpenAPIDocs bool
MetricsEnabled bool
UpdateCheck bool
// PlanEnforcement gates per-workspace resource quotas. On by default; set it
// false and all plan limits and capabilities become unlimited/allowed.
PlanEnforcement bool
// SecurityEnforcement guards platform-managed resources from disruptive raw
// Docker actions in the admin dashboard. When true (default), a platform admin
// cannot stop or remove a Miabi-managed container (apps, databases, …) from the
// node containers list — those are managed through their owning resource.
// Setting it false is an escape hatch for break-glass operations.
SecurityEnforcement bool
// GPU management. GPUEnabled is the master off-switch: when false the control
// plane never probes nodes for GPUs and the UI hides all GPU controls (an
// air-gapped / no-GPU fleet pays nothing). NvidiaRuntime is the container
// runtime name that signals the NVIDIA Container Toolkit is present.
// GPUProbeImage is the one-shot image the inventory probe runs `nvidia-smi -q
// -x` in (point it at a mirror for air-gapped/registry-pinned fleets).
// GPUInventoryMinutes is the device rescan interval.
GPUEnabled bool
NvidiaRuntime string
GPUProbeImage string
GPUInventoryMinutes int
// LicensePublicKey is the base64 Ed25519 public key used to verify a
// commercial license offline. In Enterprise builds a key is normally baked
// into the binary; this env override is for dev/test. Empty in Community.
LicensePublicKey string
// LicenseFile, when set, is a path to a signed license token auto-installed on
// boot (air-gapped / IaC friendly: drop the file and restart). A newer
// DB-installed license still takes precedence.
LicenseFile string
// Metrics history scraper.
MetricsScrapeSeconds int
MetricsRetentionHours int
CORSOrigins string
AppWebURL string
ApiBaseURL string
// LoginTokenTTLHours is the default lifetime of a CLI "login command" token
// (the OpenShift-style short-lived personal API token). LoginTokenMaxTTLHours
// is the hard ceiling a caller may request. Kept short by design.
LoginTokenTTLHours int
LoginTokenMaxTTLHours int
// AppName is the product name shown in platform notification emails.
AppName string
// SystemSMTP is the SMTP server Miabi uses to send its own platform
// notification emails (password resets, workspace invitations, welcomes).
// When unset (no host/from), those emails are silently skipped.
SystemSMTP SystemSMTPConfig
// WebDir overrides where the web UI is served from. The UI is normally
// embedded in the binary (internal/web); setting MIABI_WEB_DIR serves it from
// this directory on disk instead — for frontend development (live rebuilds) or
// to swap in a custom build without recompiling. Empty ⇒ use the embedded UI.
WebDir string
// AllowDowngrade lets the server boot even when the binary's version is
// older than the version recorded in the database. Off by default.
AllowDowngrade bool
// WebhookAllowPrivateTargets permits outbound webhooks to RFC1918/ULA
// private addresses (homelab/LAN targets). Loopback and link-local
// (incl. cloud metadata) are always blocked regardless. Off by default.
WebhookAllowPrivateTargets bool
// Worker settings.
WorkerConcurrency int
WorkerMaxRetries int
// DockerHost is the Docker engine endpoint (informational; the SDK reads
// DOCKER_HOST from the environment via FromEnv).
DockerHost string
// MarketplaceURL is where Miabi syncs official + community templates from.
// The default is the marketplace repo's latest GitHub Release asset; that path
// always serves the newest published (immutable) release, so the catalog stays
// fresh without flapping like a floating branch ref would, and updates decouple
// from Miabi releases.
//
// Alternatives: any static bundle URL (a CDN-served export.json, used
// directly) or a marketplace server base URL, e.g. https://marketplace.miabi.io
// (the /v1/export path is appended). Set MIABI_MARKETPLACE_URL to an explicit
// empty value to disable syncing — the catalog falls back to the embedded
// official floor only (offline / air-gapped kill switch).
MarketplaceURL string
// GomaProviderDir is Goma Gateway's watched file-provider directory. When
// set, Miabi writes route files there; otherwise an in-memory proxy is
// used (dev). TLS/ACME is configured on Goma itself.
GomaProviderDir string
// DeletionGraceDays is how many days an admin-scheduled account deletion waits
// before the account and all its data are permanently purged. Default 7.
DeletionGraceDays int
// DNSReconcileMinutes is the cadence of the managed-DNS reconcile sweep, which
// re-asserts ledgered records and refreshes provider status. Default 30.
DNSReconcileMinutes int
// StorageUsageEnabled runs the sweep that measures real volume disk usage
// (docker system df) and caches it. Default on; off shows declared sizes only.
StorageUsageEnabled bool
// StorageUsageMinutes is that sweep's cadence. Default 30.
StorageUsageMinutes int
// AnalyticsEnabled runs the Workspace Analytics consumer: it reads Goma's
// per-request event stream and rolls it up into minute buckets. Default on.
AnalyticsEnabled bool
// AnalyticsStream is the Redis stream Goma writes request events to (its
// GOMA_ANALYTICS_STREAM). Must match the gateway's setting.
AnalyticsStream string
// AnalyticsFlushSeconds is how often the consumer persists closed buckets.
AnalyticsFlushSeconds int
// AnalyticsRetentionDays bounds how long rollups are kept before pruning.
AnalyticsRetentionDays int
// ACMEDirectoryURL is the ACME CA directory Miabi issues managed (DNS-01)
// certificates from. Empty = Let's Encrypt production. Point it at the LE
// staging directory for testing so issuance never burns prod rate limits.
ACMEDirectoryURL string
// CertRenewDays is how many days before expiry a managed certificate is
// auto-renewed. Default 30.
CertRenewDays int
// KeyAutoRotate enables the per-workspace encryption-key auto-rotation cron;
// KeyRotateMonths is how old an active key may get before it is rotated
// (re-encrypting the workspace's secrets). Off by default.
KeyAutoRotate bool
KeyRotateMonths int
// HostProcPath is the procfs directory used to read real host CPU/memory for
// the local node. Defaults to /host/proc (the convention when the host's
// procfs is bound read-only); if that isn't present the local /proc is used,
// which already reflects host stats. Host metrics are simply unavailable when
// neither is readable.
HostProcPath string
// ProxyNetwork is the shared Docker network that Goma Gateway and all
// managed app containers join so the proxy can reach app backends. Goma must
// also be attached to this network.
ProxyNetwork string
// ControlURL is the public base URL remote nodes reach the control plane at
// (e.g. https://miabi.example.com). Used to point a node's own Goma Gateway
// at the HTTP-provider endpoint. Falls back to ApiBaseURL when unset.
ControlURL string
// ExternalBaseDomain is the wildcard base domain for one-click external access
// (e.g. "apps.example.com", DNS *.apps.example.com). When set it is the
// authoritative value for the `external_base_domain` platform setting, applied
// on every boot; leave empty to manage it from the admin Settings UI instead.
ExternalBaseDomain string
// ExternalBaseProvider names the Goma certManager provider used for the
// generated external-access routes' certificates ("" = the gateway default).
// Authoritative for the `external_base_provider` setting when set, like
// ExternalBaseDomain.
ExternalBaseProvider string
// NodeGatewayImage is the Goma Gateway image deployed on edge-gateway nodes.
NodeGatewayImage string
// RunnerImage is the miabi-runner image shown in the runner enrollment command.
RunnerImage string
// AcmeEmail is the contact address a node gateway's ACME (Let's Encrypt)
// certificate manager registers with.
AcmeEmail string
// GomaConfigEncryptionKey, when set, is injected into every edge gateway as
// GOMA_CONFIG_ENCRYPTION_KEY so Goma encrypts sensitive parts of its config
// (middleware rules and TLS material) at rest. Empty = no config encryption.
GomaConfigEncryptionKey string
// Registry is the built-in Docker registry config. When any field is set it is
// authoritative on boot (overriding the admin Settings UI), mirroring the
// ExternalBaseDomain convention; otherwise manage it from Settings.
Registry RegistryConfig
// LogStore is the shared store for execution logs (deployments, pipeline
// steps, jobs). Filesystem-backed by default; see plans/log-storage.md.
LogStore LogStoreConfig
// HostPortMin/HostPortMax bound the host ports an admin may approve for port
// bindings. Defaults allow the full non-privileged range.
HostPortMin int
HostPortMax int
// Database port-forward (on-demand external access to managed databases).
// ForwardBindAddr is the interface the ephemeral forward listeners bind to
// (default 127.0.0.1 — admins set it to a reachable interface to allow remote
// DB clients). ForwardAdvertiseHost is the host shown to users in the
// connection string (falls back to the bind address). ForwardRelayImage is
// the socat image run as the in-network relay. ForwardTTLMinutes is how long
// a session stays open before it is reaped.
ForwardBindAddr string
ForwardAdvertiseHost string
ForwardRelayImage string
ForwardTTLMinutes int
// RestoreMaxMB caps the size of an uploaded database dump for restore.
RestoreMaxMB int
// Container security profile (OpenShift-style "run as non-root"). When a
// workspace's plan selects the "restricted" profile — or ForceNonRootUser is
// set globally — application and job containers are started as RestrictedUID:0
// with no-new-privileges and NET_RAW dropped. RestrictedUID is the platform
// non-root UID (GID is always 0, the arbitrary-UID convention). SecurityInitImage
// is the tiny image run to chown a restricted app's managed volumes to that UID.
RestrictedUID int
ForceNonRootUser bool
SecurityInitImage string
// Managed network subnet allocation. Miabi carves a unique subnet out of
// NetworkPoolCIDR for every Docker network it creates (workspace/user/stack/
// gateway/overlay) and passes it as explicit IPAM, instead of relying on
// Docker's small built-in default-address-pools (which exhaust with the error
// "all predefined address pools have been fully subnetted"). It follows a
// cluster-CIDR → per-network /24 scheme. NetworkSubnetPrefix is the size of each
// carved subnet; the default /12 pool split into /24s yields 4096 networks.
// The default base (10.64.0.0/12) is chosen to avoid common Kubernetes CNI, Docker,
// and LAN/VPN/Tailscale ranges.
NetworkPoolCIDR string
NetworkSubnetPrefix int
// Runners: dedicated build/pipeline machines that keep build load off the app
// hosting nodes (see plans/runners.md). Every build runs on a registered
// runner — there is no in-process/on-node fallback. Register a runner from
// Settings → Runners (or an admin-managed shared runner).
//
// RunnerWaitTimeout bounds how long a build waits for an available runner
// before it fails ("no runner became available"). While waiting the run stays
// pending and is re-checked periodically. Prevents runs piling up forever when
// no runner is ever registered.
RunnerWaitTimeout time.Duration
// JobAPITokenEnabled injects the scoped MIABI_JOB_TOKEN callback credential
// into runner jobs (report status/logs, deploy this app by digest). A
// hardened install can withhold it while still injecting registry
// credentials. Default true.
JobAPITokenEnabled bool
// BuildTimeoutMinutes is the hard per-build deadline the runner dispatcher
// enforces on a build job (0 = none).
BuildTimeoutMinutes int
// contains filtered or unexported fields
}
Config holds all runtime configuration, loaded from the environment.
func New ¶
func New() *Config
New loads configuration from the environment (and an optional .env file).
func (*Config) AllowedBrowserOrigins ¶
AllowedBrowserOrigins returns the browser origins permitted for same-origin checks (e.g. WebSocket upgrades): the configured CORS allowlist plus the web UI URL. A "*" entry (dev) means no restriction.
func (*Config) BuildLogStore ¶
BuildLogStore constructs the shared execution-log store from configuration. It returns a disabled (nil) store when the backend is "off" or the filesystem directory can't be prepared — the store is never a hard boot dependency, so producers fall back to the DB-tail-only behavior.
func (*Config) DeploymentURL ¶
DeploymentURL is this instance's public URL, used to bind a URL-scoped license (matched by host). Prefers the web URL, falling back to the API URL; empty when neither is configured, which disables the license URL check.
func (*Config) InitStorage ¶
func (c *Config) InitStorage()
InitStorage connects to PostgreSQL and Redis. Fatal on failure.
func (*Config) InitWorker ¶
InitWorker prepares configuration for the worker process.
The worker honours MIABI_LOG_LEVEL exactly as the server does: it is a separate process, so it configures its own logger, and a level that applied to only one of the two would be a confusing half-measure (deploy logs come from the worker).
func (*Config) Initialize ¶
Initialize validates config and applies it to the Okapi app (logger, CORS, OpenAPI docs, error handler). Storage is connected separately in InitStorage.
func (*Config) LogLevelFor ¶ added in v1.4.0
LogLevelFor resolves MIABI_LOG_LEVEL to a logger level.
Empty keeps the previous behaviour exactly: debug in dev, info in production. An unrecognized value is an ERROR, not a silent fallback — an operator who sets MIABI_LOG_LEVEL=verbose and is quietly given `info` would sit and watch logs that do not contain what they turned it on to see, with nothing to tell them why.
"warn" is accepted alongside the library's "warning": slog and most tooling spell it the short way, and being pedantic about it buys nothing.
"off" is deliberately NOT accepted, even though logger.LevelOff exists. The library cannot honour it for the calls Miabi actually makes: with a disabled level, logger.New() installs a discard handler on its own instance and returns early, never assigning the package-level logger that every bare logger.Info() resolves through — so "off" silences Okapi's logger and nothing else. Offering a switch that looks like it turns logging off while the logs keep coming is worse than not offering it. Use "error" for near-silence.
type DatabaseConfig ¶
DatabaseConfig holds PostgreSQL connection settings and the live GORM handle.
func (DatabaseConfig) PostgresConn ¶
func (d DatabaseConfig) PostgresConn() (host string, port int, name, user, password, sslmode string)
PostgresConn resolves the control-plane database connection parameters, parsing MIABI_DB_URL when set and otherwise using the discrete MIABI_DB_* fields. Used by the platform backup runner to point pg-bkup at Miabi's own database. sslmode defaults to "disable" when not otherwise specified.
type LogStoreConfig ¶
type LogStoreConfig struct {
Backend string // "filesystem" | "off"
Dir string // shared directory for the filesystem backend
RetentionDays int // retention window for the sweeper (0 = keep forever)
MaxBytes int64 // per-log cap; middle-truncated past it (0 = default)
TailBytes int // bounded DB tail size
Compression string // "gzip" | "none"
}
LogStoreConfig configures the shared execution-log store. The filesystem backend (default) writes gzip log objects under Dir, which must be a shared mount across the control plane and every worker that reads/writes it. Backend "off" keeps today's DB-tail-only behavior (no store).
func (LogStoreConfig) Enabled ¶
func (l LogStoreConfig) Enabled() bool
Enabled reports whether logs should be externalized to the store.
type RedisConfig ¶
type RedisConfig struct {
Client *redis.Client
Addr string
Password string
DB int // Redis database index (MIABI_REDIS_DB); must match Goma's GOMA_REDIS_DB for analytics
}
RedisConfig holds Redis connection settings and the live client.
type RegistryConfig ¶
type RegistryConfig struct {
Enabled bool
Host string
StorageType string // "filesystem" | "s3"
Image string // override the registry image (also via the image catalog)
// AuthURL is the address the gateway's forwardAuth calls to reach Miabi's
// /internal/registry/auth (e.g. http://miabi:9000). Falls back to ControlURL.
AuthURL string
// PlatformToken is an OPTIONAL override for the shared secret the build/deploy
// worker uses to push and pull built images to/from the registry (the
// "platform-minted credential"). Leave it empty: the platform derives the token
// internally from the master encryption key, so distribution works with no
// operator action. Set it only to pin a specific value (e.g. to share with
// external tooling). Authorize accepts it as a platform principal for any
// namespace.
PlatformToken string
S3Endpoint string
S3Bucket string
S3Region string
S3AccessKey string
S3SecretKey string
S3ForcePath bool
}
RegistryConfig is the boot-authoritative config for the built-in registry. A set field overrides the corresponding admin setting on boot.
func (RegistryConfig) IsSet ¶
func (r RegistryConfig) IsSet() bool
IsSet reports whether any registry env var was provided, i.e. env is the authoritative source for the registry config on this boot.
type SystemSMTPConfig ¶
type SystemSMTPConfig struct {
Host string
Port int
Username string
Password string
From string
Encryption string
}
SystemSMTPConfig is the SMTP server Miabi uses to send its own platform notification emails. Encryption is one of: none, starttls, ssl.
func (SystemSMTPConfig) IsConfigured ¶
func (s SystemSMTPConfig) IsConfigured() bool
IsConfigured reports whether enough is set to send (a host and a From address).