database

package
v1.10.28 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 27 Imported by: 0

Documentation

Overview

Package database provisions shared database server instances and manages the logical databases they host.

Index

Constants

View Source
const (
	EnvFieldURL      = "url"
	EnvFieldLegacy   = "database_url" // deprecated alias of url
	EnvFieldHost     = "host"
	EnvFieldPort     = "port"
	EnvFieldName     = "name"
	EnvFieldUser     = "user"
	EnvFieldPassword = "password"
)

An env map keys on these to rename a field's variable, or blanks one to skip the field.

View Source
const (
	LinkKindDatabase = "database" // a logical database the app owns
	LinkKindInstance = "instance" // a whole instance (Redis), shareable across apps
)

Kinds of an app's database link.

View Source
const (
	SecretOwnerDatabase = "database"    // a logical database (its scoped user)
	SecretOwnerInstance = "db_instance" // an instance (redis / admin)
)

Owner kinds for a managed database's Vault secrets.

View Source
const (
	PathInPlace     = "in-place"     // swap the image on the same data volume
	PathDumpRestore = "dump-restore" // dump all logical DBs and restore into a fresh volume
)

Upgrade paths: how the data is carried from the old version to the new one.

Variables

View Source
var (
	ErrUnsupportedEngine  = errors.New("unsupported database engine")
	ErrSlugTaken          = errors.New("database name already taken in workspace")
	ErrNoLogicalDBs       = errors.New("this engine does not support multiple databases")
	ErrInstanceNotReady   = errors.New("database instance is not running yet")
	ErrNotFound           = errors.New("not found")
	ErrNameTaken          = errors.New("a database with this name already exists on the instance")
	ErrNoContainer        = errors.New("database has no container; re-provision it")
	ErrInstanceInUse      = errors.New("a database on this instance is attached to an application; detach it first")
	ErrInstanceLinked     = errors.New("this instance is linked to an application; unlink it first")
	ErrInstanceRunning    = errors.New("stop the database before deleting it")
	ErrNoWorkspaceNetwork = errors.New("could not resolve this workspace's network; the database was not created")
	ErrInstanceOwned      = errors.New("database is owned by another resource")
	// Upgrade errors.
	ErrInvalidVersion        = errors.New("invalid target version")
	ErrAlreadyOnVersion      = errors.New("instance is already on this version")
	ErrDowngrade             = errors.New("downgrade is not supported; data written by a newer version may be unreadable")
	ErrMongoMajorUpgrade     = errors.New("MongoDB major-version upgrades must be applied one major at a time and are not yet automated; create a new instance and migrate, or upgrade within the same major")
	ErrUpgradeInProgress     = errors.New("an upgrade is already in progress for this instance")
	ErrInstanceNotUpgradable = errors.New("instance must be running or stopped to upgrade")
	ErrDefaultNetwork        = errors.New("the workspace default network cannot be detached")
	ErrNoNetworkProvider     = errors.New("network management is not available")
	ErrInvalidResources      = errors.New("invalid database resources")
	ErrInstanceBusy          = errors.New("the instance is being provisioned or upgraded; try again once it is running")
)
View Source
var (
	// ErrLinkLogicalDatabase refuses an instance link where apps connect through a scoped logical database.
	ErrLinkLogicalDatabase = errors.New("this engine is linked through one of its databases, not the instance")
	ErrInvalidEnvMap       = errors.New("invalid env mapping")
	ErrEnvConflict         = errors.New("env vars already injected by another linked database")
)
View Source
var ErrInstanceDedicated = errors.New("this instance is dedicated to a single dependency and does not host other databases")
View Source
var ErrNoSharedInstance = errors.New("no compatible running database instance to share")
View Source
var ErrNodeGone = errors.New("the instance's node was removed; move or restore the instance instead")

ErrNodeGone refuses a redeploy whose node was removed: the data volume lived there.

View Source
var ErrReadOnlyUnsupported = errors.New("read-only users are available for PostgreSQL databases only")

ErrReadOnlyUnsupported refuses a read-only user on an engine that has none here.

View Source
var ErrSizesUnavailable = errors.New("database sizes need an Enterprise license with database sizes")

ErrSizesUnavailable refuses a named size where database sizes are not licensed.

View Source
var ErrTargetOlder = errors.New("the target instance runs an older version than the source")

ErrTargetOlder refuses restores into an older engine, which may not read a newer dump.

Functions

func CanRestoreInto added in v1.10.9

func CanRestoreInto(src, dst *models.DatabaseInstance) error

func DefaultEnvNames added in v1.10.13

func DefaultEnvNames(engine models.DBEngine) map[string]string

Redis uses REDIS_* so it can sit next to an unprefixed SQL database.

func EnvKeys added in v1.10.13

func EnvKeys(engine models.DBEngine, prefix string, m map[string]string) []string

EnvKeys returns the variable names a link injects, in write order.

func InjectedKeys added in v1.10.13

func InjectedKeys(engine models.DBEngine, prefix string, m map[string]string, recorded []string) []string

InjectedKeys falls back to the prefix-implied set for links made before keys were recorded.

func InstancePasswordSecretName

func InstancePasswordSecretName(inst *models.DatabaseInstance) string

func InstanceURLSecretName

func InstanceURLSecretName(inst *models.DatabaseInstance) string

func IsDedicated added in v1.10.28

func IsDedicated(inst *models.DatabaseInstance) bool

IsDedicated reports whether inst was provisioned for a single dependency and must not host others.

func NormalizeEnvMap added in v1.10.13

func NormalizeEnvMap(engine models.DBEngine, prefix string, m map[string]string) (map[string]string, error)

func PasswordSecretName

func PasswordSecretName(inst *models.DatabaseInstance, db *models.Database) string

The instance slug is unique per workspace, so secret names don't collide across instances.

func SanitizedName added in v1.10.28

func SanitizedName(name string) string

SanitizedName is the logical database name a manifest name becomes on the engine.

func URLSecretName

func URLSecretName(inst *models.DatabaseInstance, db *models.Database) string

Types

type AppController

type AppController interface {
	StopByID(ctx context.Context, workspaceID, appID uint) error
	StartByID(ctx context.Context, workspaceID, appID uint) error
}

AppController quiesces writers during a major (copy) upgrade; an interface avoids an app-service dependency.

type AppDatabase

type AppDatabase struct {
	models.Database
	Kind         string          `json:"kind"`
	InstanceName string          `json:"instance_name"`
	Engine       models.DBEngine `json:"engine"`
	Host         string          `json:"host"`
	Port         int             `json:"port"`
}

Kind "instance" rows are Redis instance links: ID and Name are the instance's.

type ConnectionInfo

type ConnectionInfo struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	Database string `json:"database"`
	URI      string `json:"uri"`
	// The read-only user's credentials, when the database has one (Postgres).
	ReadOnlyUsername string `json:"readonly_username,omitempty"`
	ReadOnlyPassword string `json:"readonly_password,omitempty"`
	ReadOnlyURI      string `json:"readonly_uri,omitempty"`
}

ConnectionInfo is the (sensitive) connection detail for a database.

type DumpRef

type DumpRef struct {
	Filename string
	Volume   string
}

type EngineDefault

type EngineDefault struct {
	Engine  models.DBEngine `json:"engine"`
	Image   string          `json:"image"`   // effective default image ref
	Version string          `json:"version"` // default tag
	// The least the engine runs on, and what an unsized instance gets in a capped workspace.
	MinMemoryMB     int     `json:"min_memory_mb"`
	DefaultMemoryMB int     `json:"default_memory_mb"`
	MinCPUCores     float64 `json:"min_cpu_cores"`
	DefaultCPUCores float64 `json:"default_cpu_cores"`
}

type Enqueuer

type Enqueuer interface {
	EnqueueProvisionDB(instanceID, serverID uint) error
	EnqueueUpgradeDB(instanceID, serverID uint, target, path string, stopApps bool) error
	EnqueueResizeDB(instanceID, serverID uint, previous Resources) error
	EnqueueRedeployDB(instanceID, serverID uint) error
}

Enqueuer schedules background provisioning; an interface avoids a database->worker import cycle.

type EnvLink struct {
	Prefix string
	Map    map[string]string
	Vars   []string
}

type EnvVar added in v1.10.13

type EnvVar struct {
	Key    string
	Value  string
	Secret bool
}

EnvVar is one variable a database link writes onto an app.

type EventRecorder added in v1.9.5

type EventRecorder interface {
	EmitDatabase(workspaceID, databaseID uint, name string, t models.AppEventType, sev models.AppEventSeverity, message string, meta map[string]string, actorID *uint)
	DeleteByDatabase(databaseID uint) error
}

type ImageResolver

type ImageResolver interface {
	Ref(key string) string
}

ImageResolver resolves a deployment-config catalog key to an image ref.

type LiveStatus

type LiveStatus struct {
	Status         string                  `json:"status"` // headline: stored lifecycle, or live-derived when running
	StoredStatus   models.DBStatus         `json:"stored_status"`
	ContainerState string                  `json:"container_state,omitempty"`
	Health         string                  `json:"health,omitempty"`
	Running        bool                    `json:"running"`
	Restarting     bool                    `json:"restarting"`
	RestartCount   int                     `json:"restart_count"`
	ExitCode       int                     `json:"exit_code"`
	StartedAt      string                  `json:"started_at,omitempty"`
	UptimeSeconds  int64                   `json:"uptime_seconds"`
	HasContainer   bool                    `json:"has_container"`
	NodeMissing    bool                    `json:"node_missing,omitempty"`
	Upgrade        *models.UpgradeProgress `json:"upgrade,omitempty"`
	Stats          *docker.StatsSample     `json:"stats,omitempty"`
}

LiveStatus is the pollable view of an instance: stored lifecycle status plus live Docker state when a container exists.

type LogicalBackup

type LogicalBackup interface {
	Dump(ctx context.Context, inst *models.DatabaseInstance, db *models.Database, comment string) (DumpRef, error)
	Load(ctx context.Context, inst *models.DatabaseInstance, db *models.Database, ref DumpRef, force bool) error
}

type MoveTarget added in v1.10.9

type MoveTarget struct {
	StorageClass string `json:"storage_class"`
	CreatedAt    string `json:"created_at"`
}

MoveTarget is an instance's data volume prepared on another node, ahead of moving the instance there.

type NetworkProvider

type NetworkProvider interface {
	EnsureDefault(ctx context.Context, workspaceID uint) (*models.Network, error)
	Get(workspaceID, id uint) (*models.Network, error)
}

type NodeDocker

type NodeDocker interface {
	For(serverID uint) (docker.Client, error)
	LocalID() uint
}

NodeDocker resolves the Docker client for a node id (0 = local).

type NodeGuard

type NodeGuard interface {
	Placeable(serverID uint) error
}

type OwnerExister

type OwnerExister func(kind string, id, workspaceID uint) bool

OwnerExister lets Delete refuse to orphan a database that still backs an app or stack.

type Placement

type Placement string

Placement decides how a database dependency is satisfied; shared by the marketplace installer and GitOps apply.

const (
	PlacementAuto Placement = "auto"
	// PlacementDedicated always provisions a fresh instance for the dependency.
	PlacementDedicated Placement = "dedicated"
	// Provisions only when every running instance is on another version: a database never silently runs a version it didn't ask for.
	PlacementShared Placement = "shared"
)

type Resources added in v1.10.0

type Resources struct {
	MemoryBytes int64
	NanoCPUs    int64
	// Size names the database size the limits come from (Enterprise); empty for limits set by hand.
	Size string
}

Resources are an instance's container limits. Zero means unlimited.

type SecretWriter

type SecretWriter interface {
	UpsertOwned(workspaceID uint, ownerKind string, ownerID uint, name, value, description string) (*models.Secret, error)
	DeleteOwned(workspaceID uint, ownerKind string, ownerID uint) ([]models.Application, error)
}

SecretWriter manages Vault secrets owned by a database; nil falls back to plaintext env injection.

type ServerInfo

type ServerInfo interface {
	Get(id uint) (*models.Server, error)
}

ServerInfo resolves a node's display metadata; optional, read paths show an empty server name when unset.

type Service

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

func NewService

func NewService(repo *repositories.DatabaseRepository, clients NodeDocker, enqueuer Enqueuer) *Service

func (*Service) AppEnv added in v1.10.13

func (s *Service) AppEnv(inst *models.DatabaseInstance, d *models.Database, prefix string, m map[string]string) ([]EnvVar, error)

Password and URL are Vault references when secrets are wired, so the app env never holds plaintext.

func (*Service) AttachNetwork

func (s *Service) AttachNetwork(ctx context.Context, workspaceID, instanceID, networkID uint) (*models.DatabaseInstance, error)

AttachNetwork connects the instance to another workspace network, live when its container exists; idempotent.

func (*Service) AttachToApp

func (s *Service) AttachToApp(workspaceID, dbID, appID uint, env EnvLink) (*models.Database, error)

AttachToApp links a logical database to an app; node-affinity and cross-app checks are the caller's job.

func (*Service) AuditSharedNetworkInstances added in v1.10.2

func (s *Service) AuditSharedNetworkInstances()

func (*Service) BringUpMoved added in v1.10.9

func (s *Service) BringUpMoved(ctx context.Context, inst *models.DatabaseInstance) error

func (*Service) CheckDedicatedAttach added in v1.10.28

func (s *Service) CheckDedicatedAttach(inst *models.DatabaseInstance, appID uint) error

CheckDedicatedAttach refuses attaching a database on a dedicated instance to an app other than the one it serves.

func (*Service) CreateDatabase

func (s *Service) CreateDatabase(ctx context.Context, workspaceID, instanceID uint, name string, appID *uint) (*models.Database, error)

func (*Service) DatabaseConnection

func (s *Service) DatabaseConnection(inst *models.DatabaseInstance, d *models.Database) (ConnectionInfo, error)

func (*Service) DatabaseConnectionForApp

func (s *Service) DatabaseConnectionForApp(workspaceID, appID, dbID uint) (ConnectionInfo, error)

DatabaseConnectionForApp reveals the app's own scoped credentials, not the instance admin ones.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, inst *models.DatabaseInstance) error

Delete refuses while the instance runs or while any of its databases is attached to an application.

func (*Service) DeleteDatabase

func (s *Service) DeleteDatabase(ctx context.Context, workspaceID, id uint) error

DeleteDatabase drops a logical database and its user from the instance.

func (*Service) DetachFromApp

func (s *Service) DetachFromApp(workspaceID, dbID uint) (*models.Database, error)

DetachFromApp returns the database with its prior prefix so the caller can clean up injected env vars.

func (*Service) DetachNetwork

func (s *Service) DetachNetwork(ctx context.Context, workspaceID, instanceID, networkID uint) (*models.DatabaseInstance, error)

DetachNetwork refuses the workspace default network, which carries the alias apps reach the instance by.

func (*Service) DisableReadOnly added in v1.10.21

func (s *Service) DisableReadOnly(ctx context.Context, d *models.Database) error

DisableReadOnly removes a database's read-only user and its privileges.

func (*Service) DropCopy added in v1.10.9

func (s *Service) DropCopy(ctx context.Context, serverID uint, containerID, volumeName, className string) error

DropCopy removes an instance's container and data volume from a node that no longer holds it.

func (*Service) DumpSpec added in v1.10.9

func (s *Service) DumpSpec(ctx context.Context, inst *models.DatabaseInstance, db *models.Database, name string) (docker.RunSpec, error)

DumpSpec is a one-shot container that writes a logical database to stdout, run next to the instance.

func (*Service) EnableReadOnly added in v1.10.21

func (s *Service) EnableReadOnly(ctx context.Context, d *models.Database) error

EnableReadOnly gives a database a read-only user; calling it again re-applies grants a restore stripped.

func (*Service) EngineDefaults

func (s *Service) EngineDefaults() []EngineDefault

func (*Service) EnsureNamedDatabase added in v1.10.28

func (s *Service) EnsureNamedDatabase(ctx context.Context, workspaceID uint, inst *models.DatabaseInstance, declName string, meta models.Metadata) (*models.Database, error)

EnsureNamedDatabase never suffixes: a database of that name the manifest did not create is ErrNameTaken.

func (*Service) FindDatabase added in v1.10.9

func (s *Service) FindDatabase(id uint) (*models.Database, error)

FindDatabase loads a logical database by id.

func (*Service) FindDatabaseByDeclName

func (s *Service) FindDatabaseByDeclName(workspaceID uint, declName string) (*models.Database, *models.DatabaseInstance, bool)

func (*Service) FindInstance added in v1.10.9

func (s *Service) FindInstance(id uint) (*models.DatabaseInstance, error)

FindInstance loads an instance by id, whatever its workspace, for a run that already holds it.

func (*Service) FindReusableInstance

func (s *Service) FindReusableInstance(workspaceID uint, engine models.DBEngine, version string, clusterID uint) *models.DatabaseInstance

FindReusableInstance lets a caller pre-resolve a dependency's target node; a non-zero clusterID scopes the search.

func (*Service) Get

func (s *Service) Get(workspaceID, id uint) (*models.DatabaseInstance, error)

func (*Service) GetDatabase

func (s *Service) GetDatabase(workspaceID, id uint) (*models.Database, error)

GetDatabase loads a logical database scoped to the workspace.

func (*Service) IDByUID

func (s *Service) IDByUID(uid string) (uint, error)

IDByUID resolves a database instance's portable uid to its numeric id.

func (*Service) InstanceConnection

func (s *Service) InstanceConnection(inst *models.DatabaseInstance) (ConnectionInfo, error)

InstanceConnection returns the admin connection, used for Redis and diagnostics.

func (*Service) InstanceConnectionForApp added in v1.10.13

func (s *Service) InstanceConnectionForApp(workspaceID, appID, instanceID uint) (ConnectionInfo, error)

func (*Service) InstanceLinkForApp added in v1.10.13

func (s *Service) InstanceLinkForApp(workspaceID, instanceID, appID uint) (*models.DatabaseInstanceLink, error)

InstanceLinkForApp loads an app's link to an instance.

func (*Service) LinkInstance added in v1.10.13

func (s *Service) LinkInstance(workspaceID, instanceID, appID uint, env EnvLink) (*models.DatabaseInstanceLink, error)

LinkInstance links a whole instance to an app; only engines without logical databases (Redis) link this way.

func (*Service) List

func (s *Service) List(workspaceID uint) ([]models.DatabaseInstance, error)

func (*Service) ListByApp

func (s *Service) ListByApp(workspaceID, appID uint) ([]AppDatabase, error)

func (*Service) ListByWorkspaceRaw added in v1.10.9

func (s *Service) ListByWorkspaceRaw(workspaceID uint) ([]models.DatabaseInstance, error)

ListByWorkspaceRaw lists a workspace's instances without the live annotations List adds.

func (*Service) ListDatabases

func (s *Service) ListDatabases(workspaceID, instanceID uint) ([]models.Database, error)

ListDatabases returns an instance's logical databases.

func (*Service) ListDatabasesByWorkspace

func (s *Service) ListDatabasesByWorkspace(workspaceID uint) ([]models.Database, error)

ListDatabasesByWorkspace returns every logical database in the workspace.

func (*Service) ListInstanceDatabases added in v1.10.9

func (s *Service) ListInstanceDatabases(instanceID uint) ([]models.Database, error)

ListInstanceDatabases lists an instance's logical databases.

func (s *Service) ListInstanceLinks(instanceID uint) ([]models.DatabaseInstanceLink, error)

ListInstanceLinks returns every app link to an instance.

func (*Service) LiveStatus

func (s *Service) LiveStatus(ctx context.Context, inst *models.DatabaseInstance) LiveStatus

LiveStatus falls back to the stored status when there is no container or the node is unreachable.

func (*Service) MarkNodeRemoved added in v1.10.2

func (s *Service) MarkNodeRemoved(serverID uint)

MarkNodeRemoved marks a deleted node's instances stopped but keeps rows, volume names and credentials.

func (*Service) MaybeRefreshSizes

func (s *Service) MaybeRefreshSizes(inst *models.DatabaseInstance)

MaybeRefreshSizes refreshes stale sizes in the background without blocking, debounced per instance.

func (*Service) PlanUpgrade

func (s *Service) PlanUpgrade(workspaceID, instanceID uint, target string) (*UpgradePlan, error)

func (*Service) PrepareDatabase

func (s *Service) PrepareDatabase(workspaceID, instanceID uint, name string, appID *uint) (*models.Database, error)

PrepareDatabase reserves a logical database without DDL; the CREATE runs once the instance is up.

func (*Service) PrepareMove added in v1.10.9

func (s *Service) PrepareMove(ctx context.Context, inst *models.DatabaseInstance, serverID uint) (MoveTarget, error)

PrepareMove creates the data volume on another node, keeping the storage class only if that node registers it.

func (*Service) Provision

func (s *Service) Provision(ctx context.Context, workspaceID, serverID uint, name string, engine models.DBEngine, version string, volumeSizeBytes int64, storageClass string, res Resources, meta, annotations models.Metadata) (*models.DatabaseInstance, error)

func (*Service) RecreateDatabase

func (s *Service) RecreateDatabase(ctx context.Context, inst *models.DatabaseInstance, db *models.Database) error

RecreateDatabase drops and recreates a logical database with the same credentials, for a force restore.

func (*Service) Redeploy added in v1.10.28

func (s *Service) Redeploy(ctx context.Context, inst *models.DatabaseInstance) error

Redeploy recreates the instance's container from its stored record on the same data volume, in the background.

func (*Service) Reencrypt

func (s *Service) Reencrypt(ctx context.Context, workspaceID uint) (int, error)

Reencrypt re-encrypts the workspace's database secrets under its active DEK; idempotent.

func (*Service) Resize added in v1.10.0

Resize recreates the container on the same volume so the engine is re-tuned; a stopped instance stays stopped.

func (*Service) ResolveDependency

func (s *Service) ResolveDependency(ctx context.Context, workspaceID, serverID, pinInstance uint, base, declName string, engine models.DBEngine, version string, placement Placement, res Resources, meta models.Metadata) (*models.DatabaseInstance, *models.Database, ConnectionInfo, bool, error)

declName stamps the logical database so a declarative reconcile maps a manifest name back to it exactly.

func (s *Service) ResolveEnvLink(workspaceID, appID uint, engine models.DBEngine, prefix string, m map[string]string, skipDB, skipInst uint) (EnvLink, error)

ResolveEnvLink refuses var names another app link already injects; skipDB/skipInst exclude the link being reattached.

func (*Service) Restart

func (s *Service) Restart(ctx context.Context, inst *models.DatabaseInstance) error

Restart restarts the instance container and marks it running.

func (*Service) RestoreSpec added in v1.10.9

func (s *Service) RestoreSpec(ctx context.Context, inst *models.DatabaseInstance, db *models.Database, name string) (docker.RunSpec, error)

RestoreSpec loads a dump from stdin; the database must exist and be empty first.

func (*Service) RunProvision

func (s *Service) RunProvision(ctx context.Context, instanceID uint) error

RunProvision performs the container bring-up for an instance (worker-invoked).

func (*Service) RunRedeploy added in v1.10.28

func (s *Service) RunRedeploy(ctx context.Context, instanceID uint) error

func (*Service) RunResize added in v1.10.0

func (s *Service) RunResize(ctx context.Context, instanceID uint, previous Resources) error

RunResize restores the previous limits if the container fails to come up, so a resize never leaves the DB down.

func (*Service) RunUpgradeJob

func (s *Service) RunUpgradeJob(ctx context.Context, instanceID uint, target, path string, stopApps bool) error

RunUpgradeJob always returns nil: a half-applied upgrade must not be blindly retried.

func (*Service) SetAppController

func (s *Service) SetAppController(a AppController)

func (*Service) SetDatabaseApp added in v1.10.9

func (s *Service) SetDatabaseApp(d *models.Database, appID *uint, prefix string) error

SetDatabaseApp changes ownership without touching the app's environment: the caller re-injects it.

func (*Service) SetDedicated added in v1.10.28

func (s *Service) SetDedicated(workspaceID, id uint, dedicated bool) (*models.DatabaseInstance, error)

func (*Service) SetEventBus

func (s *Service) SetEventBus(b *eventbus.Bus)

SetEventBus must receive the same bus as the embedded worker so its phase changes reach open streams.

func (*Service) SetEventRecorder added in v1.9.5

func (s *Service) SetEventRecorder(r EventRecorder)

SetEventRecorder wires the timeline recorder (nil-safe: unset means no events).

func (*Service) SetImageResolver

func (s *Service) SetImageResolver(r ImageResolver)

func (*Service) SetLogicalBackup

func (s *Service) SetLogicalBackup(b LogicalBackup)

func (*Service) SetMetadata added in v1.10.28

func (s *Service) SetMetadata(workspaceID, id uint, set map[string]string, drop ...string) (*models.DatabaseInstance, error)

SetMetadata writes the given built-in keys and removes drop, leaving every other key as it is.

func (*Service) SetNetworkProvider

func (s *Service) SetNetworkProvider(p NetworkProvider)

SetNetworkProvider wires workspace networks; when unset, databases fall back to the shared gateway network.

func (*Service) SetNodeGuard

func (s *Service) SetNodeGuard(g NodeGuard)

SetNodeGuard wires the placement guard consulted when provisioning on a node.

func (*Service) SetOwner

func (s *Service) SetOwner(workspaceID, id uint, kind string, ownerID uint, name string) error

Built-in owner keys are authoritative, so this overrides any prior owner.

func (*Service) SetOwnerExister

func (s *Service) SetOwnerExister(fn OwnerExister)

SetOwnerExister wires the owner-existence check used by Delete (nil-safe).

func (*Service) SetQuota

func (s *Service) SetQuota(q *quota.Service)

SetQuota wires the plan/quota enforcer (nil-safe; nil skips checks).

func (*Service) SetSecrets

func (s *Service) SetSecrets(w SecretWriter)

func (*Service) SetServerInfo

func (s *Service) SetServerInfo(si ServerInfo)

func (*Service) SetSizeCatalog added in v1.10.0

func (s *Service) SetSizeCatalog(c SizeCatalog)

SetSizeCatalog wires database sizes (Enterprise). Without it no request may name a size.

func (*Service) SetStorageClasses added in v1.10.4

func (s *Service) SetStorageClasses(p StorageClassPlacer)

func (*Service) SetSwarmNetworks added in v1.10.0

func (s *Service) SetSwarmNetworks(sw SwarmNetworks)

func (*Service) SizesFor added in v1.10.0

func (s *Service) SizesFor(workspaceID uint) (SizeOffer, error)

SizesFor lists the sizes a workspace may give a database. Empty where sizes are not licensed.

func (*Service) Start

func (s *Service) Start(ctx context.Context, inst *models.DatabaseInstance) error

Start (re)starts a stopped instance container and marks it running.

func (*Service) StartStopped added in v1.10.9

func (s *Service) StartStopped(ctx context.Context, inst *models.DatabaseInstance) error

StartStopped starts an instance's existing container again, as a rollback does for the source it left.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context, inst *models.DatabaseInstance) error

Stop stops the container but keeps the data volume and records so the instance can start again.

func (*Service) StopForMove added in v1.10.9

func (s *Service) StopForMove(ctx context.Context, inst *models.DatabaseInstance) error

StopForMove stops the instance's container and keeps it: it is what a rollback starts again.

func (*Service) StreamLogs

func (s *Service) StreamLogs(ctx context.Context, workspaceID, instanceID uint, follow bool, tail string, sink func(docker.LogLine) error) error

StreamLogs follows the container's logs into sink; tail "" uses a default, and follow=false returns after the tail.

func (*Service) StreamStatus

func (s *Service) StreamStatus(ctx context.Context, inst *models.DatabaseInstance, send func(eventbus.Event) error) error

With no bus wired it sends the initial snapshot and holds the connection, leaving the client its REST fallback.

func (*Service) StreamWorkspaceStatus

func (s *Service) StreamWorkspaceStatus(ctx context.Context, workspaceID uint, send func(eventbus.Event) error) error

No snapshot is sent: the list seeds via REST, and falls back to periodic reconcile without a bus.

func (*Service) SyncAllSizes added in v1.8.0

func (s *Service) SyncAllSizes(ctx context.Context) (int, error)

SyncAllSizes exists so databases nobody opens are still measured and usage totals don't drift.

func (*Service) SyncSizes

func (s *Service) SyncSizes(ctx context.Context, inst *models.DatabaseInstance) error

func (*Service) TagDeclared added in v1.10.28

func (s *Service) TagDeclared(d *models.Database, meta models.Metadata)

TagDeclared restores the manifest identity a logical database carried, so a restored workspace still converges.

func (*Service) UniqueDatabaseName

func (s *Service) UniqueDatabaseName(instanceID uint, base string) (string, error)

UniqueDatabaseName appends _2, _3, ... on collision so callers never hit ErrNameTaken.

func (*Service) UnlinkInstance added in v1.10.13

func (s *Service) UnlinkInstance(workspaceID, instanceID, appID uint) (*models.DatabaseInstanceLink, error)

func (*Service) Upgrade

func (s *Service) Upgrade(ctx context.Context, workspaceID, instanceID uint, target string, stopApps bool) (*models.DatabaseInstance, error)

Upgrade enqueues the work on asynq so it survives restarts; stopApps is strongly recommended for majors.

func (*Service) UpgradeOptions

func (s *Service) UpgradeOptions(workspaceID, instanceID uint) (*UpgradeOptions, error)

UpgradeOptions returns the suggested targets and affected apps for an instance.

type SizeCatalog added in v1.10.0

type SizeCatalog interface {
	List() ([]models.DatabaseSize, error)
}

SizeCatalog lists the database sizes a platform offers. Satisfied by the size repository.

type SizeOffer added in v1.10.0

type SizeOffer struct {
	Sizes     []models.DatabaseSize `json:"sizes"`
	DefaultID uint                  `json:"default_id,omitempty"`
	Bound     bool                  `json:"bound"`
}

type StatusEvent

type StatusEvent struct {
	Status  models.DBStatus         `json:"status"`
	Upgrade *models.UpgradeProgress `json:"upgrade,omitempty"`
}

type StorageClassPlacer added in v1.10.4

type StorageClassPlacer interface {
	PlaceVolume(ctx context.Context, workspaceID, serverID uint, requested, dockerName string) (className, devicePath string, err error)
	ReclaimVolumeDir(ctx context.Context, serverID uint, className, dockerName string)
}

type SwarmNetworks added in v1.10.0

type SwarmNetworks interface {
	WorkspaceOverlay(clusterID uint, n models.Network) bool
	EnsureWorkspaceOverlay(ctx context.Context, clusterID uint, n models.Network) error
}

SwarmNetworks creates workspace networks in a remote swarm. Implemented by services/cluster.

type UpgradeOptions

type UpgradeOptions struct {
	CurrentVersion string          `json:"current_version"`
	Engine         models.DBEngine `json:"engine"`
	Suggestions    []string        `json:"suggestions"`      // curated newer versions (hints; any version is accepted)
	AffectedAppIDs []uint          `json:"affected_app_ids"` // apps that would be stopped for a copy upgrade
}

UpgradeOptions describes what an instance can be upgraded to.

type UpgradePlan

type UpgradePlan struct {
	FromVersion    string `json:"from_version"`
	ToVersion      string `json:"to_version"`
	Path           string `json:"path"`  // in-place | dump-restore
	Major          bool   `json:"major"` // crosses a major version
	AffectedAppIDs []uint `json:"affected_app_ids"`
}

UpgradePlan is the resolved effect of upgrading to a specific target version.

type WorkspaceStatusEvent

type WorkspaceStatusEvent struct {
	ID      uint                    `json:"id"`
	Status  models.DBStatus         `json:"status"`
	Upgrade *models.UpgradeProgress `json:"upgrade,omitempty"`
}

Jump to

Keyboard shortcuts

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