engine

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Overview

Package engine exposes Tako's deployment workflows as a library. The CLI commands in cmd/ are thin adapters over this package: they parse flags into request structs, run the engine, and render the emitted event stream. The engine never prompts, never prints, and never exits the process; progress flows through the events sink and outcomes are returned as typed results and errors.

Index

Constants

View Source
const (
	ActionMaintenanceEnable  = "maintenance.enable"
	ActionMaintenanceDisable = "maintenance.disable"
	ActionCleanup            = "cleanup"
)

Action identifiers carried in ActionResult.Action.

View Source
const (
	ActionOutcomeOK      = "ok"
	ActionOutcomePartial = "partial"
	ActionOutcomeFailed  = "failed"
)

Action outcomes.

View Source
const (
	BackupActionList    = "list"
	BackupActionCreate  = "create"
	BackupActionRestore = "restore"
	BackupActionDelete  = "delete"
	BackupActionCleanup = "cleanup"
)

Backup actions carried in BackupResult.Action.

View Source
const (
	// KindConfigExportResult identifies the machine-readable result document for
	// `tako config export` and `tako config pull`.
	KindConfigExportResult = "ConfigExportResult"
	// ConfigExportPasswordPlaceholder is written to generated configs instead of
	// a caller-provided SSH password.
	ConfigExportPasswordPlaceholder = "${TAKO_SSH_PASSWORD}"
)
View Source
const (
	DestroyModeDecommission = "DECOMMISSION"
	DestroyModePurge        = "PURGE"
)

Destroy modes.

View Source
const (
	DoctorStatusPass = "pass"
	DoctorStatusWarn = "warn"
	DoctorStatusFail = "fail"
	DoctorStatusSkip = "skip"
)

Doctor check statuses.

View Source
const (
	KindDomainsResult      = "DomainsResult"
	KindDomainsHostsResult = "DomainsHostsResult"
)

Kinds of serialized domains result documents.

View Source
const (
	KindJobsResult       = "JobsResult"
	KindJobRunsResult    = "JobRunsResult"
	KindJobTriggerResult = "JobTriggerResult"
)

Kinds of the serialized job result documents.

View Source
const (
	KindSecretsListResult     = "SecretsListResult"
	KindSecretsValidateResult = "SecretsValidateResult"
)

Kinds of serialized secrets result documents.

View Source
const (
	SetupStepOSCheck      = "os-check"
	SetupStepPackages     = "packages"
	SetupStepDocker       = "docker"
	SetupStepWireGuard    = "wireguard"
	SetupStepFirewall     = "firewall"
	SetupStepHardening    = "hardening"
	SetupStepAutoRecovery = "auto-recovery"
	SetupStepDeployUser   = "deploy-user"
	SetupStepMonitorAgent = "monitor-agent"
	SetupStepTakodInstall = "takod-install"
	SetupStepTakodService = "takod-service"
)

Setup step keys carried in SetupStepOutcome.Step and setup.step.* events. Keys are contract-stable; titles are human prose and may change.

View Source
const (
	SetupStepCompleted = "completed"
	SetupStepFailed    = "failed"
	SetupStepSkipped   = "skipped"
)

Setup step statuses carried in SetupStepOutcome.Status.

View Source
const (
	SetupModeFresh    = "fresh"
	SetupModeReapply  = "reapply"
	SetupModeConverge = "converge"
)

Setup modes carried in SetupNodeResult.Mode: fresh provisions a new node, reapply upgrades an older setup version, converge refreshes a node already at the current setup version (only firewall, deploy access, and the takod runtime re-run; other steps report skipped).

View Source
const (
	// KindStateForgetNodeResult identifies a serialized state forget-node result.
	KindStateForgetNodeResult = "StateForgetNodeResult"

	StateForgetNodeStatusSuccess = "success"
	StateForgetNodeStatusFailed  = "failed"
)
View Source
const (
	// KindStateLeaseResult identifies a serialized state lease read result.
	KindStateLeaseResult = "StateLeaseResult"
	// KindStateLeaseReleaseResult identifies a serialized state lease release result.
	KindStateLeaseReleaseResult = "StateLeaseReleaseResult"
)
View Source
const (
	// KindStatePullResult identifies a serialized state pull result document.
	KindStatePullResult = "StatePullResult"

	StatePullStatusSyncedHistory    = "synced_history"
	StatePullStatusRecoveredActual  = "recovered_mesh_actual"
	StatePullStatusRecoveredRunning = "recovered_running_mesh"
	StatePullStatusNoneFound        = "none_found"
)
View Source
const (
	// KindStateRepairResult identifies a serialized state repair result document.
	KindStateRepairResult = "StateRepairResult"

	StateRepairStatusSuccess = "success"
	StateRepairStatusFailed  = "failed"

	StateRepairLocalSyncStatusSkipped = "skipped"
	StateRepairLocalSyncStatusSynced  = "synced"
	StateRepairLocalSyncStatusFailed  = "failed"
)
View Source
const (
	// KindStateStatusResult identifies a serialized state status result document.
	KindStateStatusResult = "StateStatusResult"

	StateStatusLocalMissing    = "missing"
	StateStatusLocalExists     = "exists"
	StateStatusNodeReachable   = "reachable"
	StateStatusNodeUnreachable = "unreachable"
)
View Source
const (
	// KindDeployPlan identifies a serialized deployment plan document.
	KindDeployPlan = "DeployPlan"
	// KindDeployResult identifies a serialized deployment result document.
	KindDeployResult = "DeployResult"
)
View Source
const (
	OutcomeDeployed = "deployed"
	OutcomeWarmed   = "warmed"
	OutcomeRemoved  = "removed"
	OutcomeUpToDate = "up_to_date"
	OutcomeFailed   = "failed"
	OutcomeRan      = "ran"
)

Service outcome actions.

View Source
const (
	UpgradeOutcomeUpgraded          = "upgraded"
	UpgradeOutcomeFailed            = "failed"
	UpgradeOutcomeCurrent           = "current"
	UpgradeOutcomeUpgradeNeeded     = "upgrade-needed"
	UpgradeOutcomeSetupRequired     = "setup-required"
	UpgradeOutcomeStatusUnavailable = "status-unavailable"
	UpgradeOutcomeRolledBack        = "rolled-back"
	UpgradeOutcomeBlocked           = "blocked"
	UpgradeOutcomeDowngradeBlocked  = "downgrade-blocked"
)

Upgrade outcomes carried in UpgradeServersNodeOutcome.Outcome. Apply runs report upgraded/failed; dry runs report the remaining assessments.

View Source
const (
	UpgradeStageCanary     = "worker-canary"
	UpgradeStageWorkers    = "workers"
	UpgradeStageController = "controller-last"
	UpgradeStageLegacy     = "legacy"
)
View Source
const (
	ValidateSeverityError = "error"
	ValidateSeverityWarn  = "warning"
)

Validate finding severities.

View Source
const DefaultExecTimeout = 10 * time.Minute

DefaultExecTimeout bounds a remote exec when the caller sets none.

View Source
const (
	// FailedDeploymentCleanupTimeout bounds best-effort failure-state writes after
	// the operation context has already been cancelled or exceeded its deadline.
	FailedDeploymentCleanupTimeout = 10 * time.Second
)
View Source
const KindAccessResult = "AccessResult"

KindAccessResult identifies a serialized proxy access-log result document.

View Source
const KindActionResult = "ActionResult"

KindActionResult identifies the minimal acknowledgement document emitted by node-fanout maintenance operations (maintenance, live, cleanup).

View Source
const KindBackupResult = "BackupResult"

KindBackupResult identifies a serialized backup result document.

View Source
const KindCertsResult = "CertsResult"
View Source
const KindCloneSetupResult = "CloneSetupResult"

KindCloneSetupResult identifies a serialized clone-setup result document.

View Source
const KindDestroyResult = "DestroyResult"

KindDestroyResult identifies a serialized destroy result document.

View Source
const KindDiscoveryExportsResult = "DiscoveryExportsResult"

KindDiscoveryExportsResult identifies a serialized discovery exports result document.

View Source
const KindDoctorResult = "DoctorResult"

KindDoctorResult identifies a serialized doctor result document.

View Source
const KindDriftResult = "DriftResult"

KindDriftResult identifies a serialized drift result document.

View Source
const KindExecResult = "ExecResult"

KindExecResult identifies a serialized exec result document.

View Source
const KindHistoryResult = "HistoryResult"

KindHistoryResult identifies a serialized deployment history result document.

View Source
const (
	// KindLogsResult identifies a serialized logs result document.
	KindLogsResult = "LogsResult"
)
View Source
const KindMetricsResult = "MetricsResult"

KindMetricsResult identifies a serialized metrics result document.

View Source
const KindPromoteResult = "PromoteResult"

KindPromoteResult identifies a serialized promotion result document.

View Source
const KindProxyHashPasswordResult = "ProxyHashPasswordResult"

KindProxyHashPasswordResult identifies the machine-readable result document for `tako proxy hash-password`.

View Source
const KindRemoveResult = "RemoveResult"

KindRemoveResult identifies a serialized remove result document.

View Source
const KindRollbackResult = "RollbackResult"

KindRollbackResult identifies a serialized rollback result document.

View Source
const KindScaleResult = "ScaleResult"

KindScaleResult identifies a serialized scale result document.

View Source
const KindSetupResult = "SetupResult"

KindSetupResult identifies a serialized setup result document.

View Source
const KindStatsResult = "StatsResult"

KindStatsResult identifies a serialized container-stats result document.

View Source
const KindStatusResult = "StatusResult"
View Source
const KindUpgradeServersResult = "UpgradeServersResult"

KindUpgradeServersResult identifies a serialized server-agent upgrade result document.

View Source
const KindValidateResult = "ValidateResult"

KindValidateResult identifies a serialized validate result document.

View Source
const UpgradeProtocolCurrent = upgradeprotocol.Current

UpgradeProtocolCurrent is the stable node-lifecycle protocol emitted by this CLI. Compatible N/N-1 releases report a range containing this value.

Variables

View Source
var GraceSleep = time.Sleep

GraceSleep pauses blue-green pruning; tests may replace it.

Functions

func ActualSnapshotWithoutNode

func ActualSnapshotWithoutNode(snapshot *takodstate.ActualSnapshot, nodeName string) (*takodstate.ActualSnapshot, bool)

ActualSnapshotWithoutNode returns a copy of snapshot with nodeName removed from target and embedded node lists.

func ActualStateError

func ActualStateError(err error) error

ActualStateError wraps failures to read running state before planning.

func ActualStateViaTakod

func ActualStateViaTakod(client any, cfg *config.Config, environment string) (*takod.ActualStateResponse, error)

ActualStateViaTakod reads the aggregate actual-state endpoint through takod.

func AddPriorDesiredMutationTargets added in v0.10.0

func AddPriorDesiredMutationTargets(cfg *config.Config, current []string, prior *takodstate.DesiredRevision) []string

AddPriorDesiredMutationTargets keeps workers that still own authoritative desired assignments in the fenced observation/cleanup set. This is what lets a full deploy remove the last service from a worker instead of forgetting the worker before its old containers are observed and stopped.

func ApplyArchiveOverride

func ApplyArchiveOverride(service config.ServiceConfig, buildContext string) config.ServiceConfig

ApplyArchiveOverride points a service at an extracted archive build context.

func ApplyImageOverride

func ApplyImageOverride(service config.ServiceConfig, imageRef string) config.ServiceConfig

ApplyImageOverride points a service at a prebuilt image.

func ApplySourceOverride

func ApplySourceOverride(service config.ServiceConfig, source string) config.ServiceConfig

ApplySourceOverride points a service at a local build context.

func ArchiveBuildTag

func ArchiveBuildTag(explicitRevision string, archivePath string) (string, error)

ArchiveBuildTag derives the build tag for an archive deploy from an explicit revision or the archive content hash.

func AttachStatusServiceNodes added in v0.9.1

func AttachStatusServiceNodes(serviceInfos []StatusService, nodeStates []StatusNodeActualState)

AttachStatusServiceNodes fills each container-service row's per-node placement breakdown from the per-node actual state. Job and run rows have no long-running containers and are left untouched.

func AuthoritativeStateServer added in v0.10.0

func AuthoritativeStateServer(cfg *config.Config, fallback []string) (string, error)

AuthoritativeStateServer resolves controller-only state in enrolled mode and retains the legacy local/first preference for unenrolled configurations.

func BuildNodeActualSnapshots

func BuildNodeActualSnapshots(project string, environment string, nodeActualState map[string]map[string]*reconcile.ActualService) map[string]*takodstate.ActualSnapshot

BuildNodeActualSnapshots converts per-node actual state into snapshots.

func BuildRollbackDeployment

func BuildRollbackDeployment(
	cfg *config.Config,
	envName string,
	host string,
	startTime time.Time,
	duration time.Duration,
	targetDeployment *remotestate.DeploymentState,
	serviceName string,
	serviceState remotestate.ServiceState,
	cliVersion string,
	cliCommit string,
) *remotestate.DeploymentState

BuildRollbackDeployment builds the deployment record persisted after a successful rollback.

func BuildScaleDeploymentState

func BuildScaleDeploymentState(
	cfg *config.Config,
	envName string,
	host string,
	startTime time.Time,
	duration time.Duration,
	scaleTargets map[string]int,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	cliVersion string,
	cliCommit string,
) *remotestate.DeploymentState

BuildScaleDeploymentState builds the deployment history record for a successful scale operation.

func CleanConfigExportTargetNodes

func CleanConfigExportTargetNodes(values []string) []string

CleanConfigExportTargetNodes trims, deduplicates, and sorts target node keys.

func CleanupImageRepositories

func CleanupImageRepositories(cfg *config.Config, environment string, services map[string]config.ServiceConfig) []string

CleanupImageRepositories lists the image repositories automatic cleanup should prune for built services.

func CleanupProxyFiles

func CleanupProxyFiles(project string, environment string, services map[string]config.ServiceConfig) []string

CleanupProxyFiles lists the proxy configuration files cleanup must delete for a project/environment, including maintenance-page configs for proxied services.

func CleanupViaTakod

func CleanupViaTakod(client any, cfg *config.Config, request takod.CleanupRequest) (*takod.CleanupResponse, error)

CleanupViaTakod runs post-deploy cleanup on one node through takod.

func CleanupViaTakodContext added in v0.9.0

func CleanupViaTakodContext(ctx context.Context, client any, cfg *config.Config, request takod.CleanupRequest) (*takod.CleanupResponse, error)

CleanupViaTakodContext runs cleanup through takod bounded by ctx.

func CloneServiceMap

func CloneServiceMap(services map[string]config.ServiceConfig) map[string]config.ServiceConfig

CloneServiceMap shallow-copies a service map.

func CloneStatusStringMap

func CloneStatusStringMap(values map[string]string) map[string]string

func CopyActualNodeSnapshots

func CopyActualNodeSnapshots(nodes map[string]takodstate.ActualNodeSnapshot) map[string]takodstate.ActualNodeSnapshot

CopyActualNodeSnapshots copies embedded node snapshots and service maps.

func CopyActualServices

func CopyActualServices(services map[string]takodstate.ActualService) map[string]takodstate.ActualService

CopyActualServices deep-copies service container slices.

func DeployLeaseTargets added in v0.10.0

func DeployLeaseTargets(cfg *config.Config, environmentServers []string, services map[string]config.ServiceConfig) []string

DeployLeaseTargets includes every schedulable environment worker plus any schedulable builder that an auto/remote build may mutate. Setup remains scoped to environment workers; the builder lease protects the later exact image build/transfer operation.

func DeployMutationTargets added in v0.10.0

func DeployMutationTargets(cfg *config.Config, services map[string]config.ServiceConfig, assignments map[string][]scheduler.Assignment) []string

DeployMutationTargets returns only nodes the resolved deploy can mutate: assigned workers, edge nodes, a required builder, and the authoritative state/controller node. An unrelated unavailable worker therefore cannot block an otherwise local operation.

func DeploymentFromHistory

func DeploymentFromHistory(history *remotestate.DeploymentHistory, deploymentID string) (*remotestate.DeploymentState, error)

DeploymentFromHistory finds a deployment by ID in a history document.

func DeploymentSuccessStatus

func DeploymentSuccessStatus(manualPending []string) remotestate.DeploymentStatus

DeploymentSuccessStatus resolves the final status for a successful apply.

func DesiredReplicasForSelection

func DesiredReplicasForSelection(servers map[string]config.ServerConfig, service config.ServiceConfig, envServers []string, selectedServers []string) (int, error)

func DestroyEnvironmentTargets

func DestroyEnvironmentTargets(cfg *config.Config, envName string) (map[string]config.ServerConfig, []string, error)

DestroyEnvironmentTargets resolves the environment's servers into the destroy target set, preserving environment order.

func DestroySingleServerWithHooks

func DestroySingleServerWithHooks(pool SSHClientProvider, serverName string, serverCfg config.ServerConfig, cfg *config.Config, envName string, verbose bool, purgeAll bool, decommission func(*ssh.Client, *config.Config, string, bool) error, purge func(*ssh.Client, *config.Config, string, bool) error) error

DestroySingleServerWithHooks connects to one node, decommissions the app/stage runtime, and purges app-owned leftovers when requested. Purge never runs after a failed decommission.

func DestroySingleServerWithHooksContext added in v0.9.0

func DestroySingleServerWithHooksContext(ctx context.Context, pool SSHClientProvider, serverName string, serverCfg config.ServerConfig, cfg *config.Config, envName string, verbose bool, purgeAll bool, decommission func(context.Context, *ssh.Client, *config.Config, string, bool) error, purge func(context.Context, *ssh.Client, *config.Config, string, bool) error) error

DestroySingleServerWithHooksContext is the context-aware destroy primitive. It stops before each destructive phase when lease loss or caller cancellation cancels ctx.

func DomainExpectedTargets

func DomainExpectedTargets(cfg *config.Config, envName string, overrides []string) ([]string, error)

DomainExpectedTargets resolves the DNS targets public domains must point at.

func EnsureDeployRuntimeSupported

func EnsureDeployRuntimeSupported(cfg *config.Config) error

EnsureDeployRuntimeSupported validates the runtime/state/mesh combination deploys require.

func ExternalVolumeNamesForEnvironment

func ExternalVolumeNamesForEnvironment(cfg *config.Config, environment string) []string

ExternalVolumeNamesForEnvironment lists external volume names cleanup must never remove.

func ExtractArchive

func ExtractArchive(archivePath string, destDir string) error

ExtractArchive extracts a supported source archive into destDir, rejecting links, absolute paths, and traversal.

func GatherStatusActualState

func GatherStatusActualState(ctx context.Context, cfg *config.Config, envName string, serverNames []string) (map[string]*takod.ActualService, error)

GatherStatusActualState reads and merges actual service state from selected nodes using takod over SSH.

func GatherStatusActualStateWith

func GatherStatusActualStateWith(ctx context.Context, servers map[string]config.ServerConfig, serverNames []string, read StatusActualStateReadFunc) (map[string]*takod.ActualService, error)

GatherStatusActualStateWith fans out actual-state reads concurrently and merges successful node responses in selected server order.

func GitInfoFromCommit

func GitInfoFromCommit(commitInfo *git.CommitInfo) takodstate.GitInfo

GitInfoFromCommit converts optional commit info into takod state git info.

func HasJobServices added in v0.8.0

func HasJobServices(services map[string]config.ServiceConfig) bool

HasJobServices reports whether any service in the map is a kind:job.

func HasRunServices added in v0.9.0

func HasRunServices(services map[string]config.ServiceConfig) bool

func ImageRepositoryFromRef

func ImageRepositoryFromRef(ref string) string

ImageRepositoryFromRef strips tag and digest from an image reference.

func IsSupportedArchive

func IsSupportedArchive(path string) bool

IsSupportedArchive reports whether the path has a supported archive suffix.

func LoadPriorAssignments added in v0.10.0

func LoadPriorAssignments(client any, cfg *config.Config, envName string) (map[string][]scheduler.Assignment, error)

LoadPriorAssignments reads the last authoritative desired revision from the selected runtime node. A new environment has no document and therefore no assignments; all other read failures fail closed.

func LoadPriorPlacementState added in v0.10.0

func LoadPriorPlacementState(client any, cfg *config.Config, envName string) (*takodstate.DesiredRevision, map[string][]scheduler.Assignment, error)

LoadPriorPlacementState returns the full prior desired revision together with validated/adopted assignments. Callers that rewrite desired state use the revision as a baseline so out-of-scope services survive unchanged.

func MaterializeConfigExport

func MaterializeConfigExport(req ConfigExportRequest, docs ConfigExportStateDocs) (*config.Config, []configmaterialize.Warning, error)

MaterializeConfigExport builds a config from already-read takod documents.

func MergeStatusActualStates added in v0.9.1

func MergeStatusActualStates(nodeStates []StatusNodeActualState) map[string]*takod.ActualService

MergeStatusActualStates merges per-node actual state into the mesh-wide view in node order.

func MergeStatusOptionalLabel

func MergeStatusOptionalLabel(existing string, incoming string) string

func MergeStatusRevisionImageMaps

func MergeStatusRevisionImageMaps(existing map[string]string, incoming map[string]string) map[string]string

func MergeStatusRevisionLists

func MergeStatusRevisionLists(existing []string, incoming []string) []string

func NormalizeConfigExportRequest

func NormalizeConfigExportRequest(req *ConfigExportRequest) error

NormalizeConfigExportRequest trims and defaults a config export request.

func ParseScaleTargets

func ParseScaleTargets(args []string) (map[string]int, error)

ParseScaleTargets parses SERVICE=REPLICAS arguments into a target map.

func PersistTakodDesiredIntent added in v0.10.0

func PersistTakodDesiredIntent(
	sshPool *ssh.Pool,
	cfg *config.Config,
	envName string,
	serverNames []string,
	source string,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	assignments map[string][]scheduler.Assignment,
	gitInfo takodstate.GitInfo,
	message string,
	verbose bool,
) error

PersistTakodDesiredIntent writes the exact sticky placement decision before images, containers, schedules, or proxy routes are mutated. A later runtime state write records actual state without changing the chosen assignments.

func PersistTakodDesiredIntentWithPlacementBaseline added in v0.10.0

func PersistTakodDesiredIntentWithPlacementBaseline(
	sshPool *ssh.Pool,
	cfg *config.Config,
	envName string,
	serverNames []string,
	source string,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	assignments map[string][]scheduler.Assignment,
	pendingRemovals map[string]config.ServiceConfig,
	priorDesired *takodstate.DesiredRevision,
	gitInfo takodstate.GitInfo,
	message string,
	verbose bool,
) error

PersistTakodDesiredIntentWithPlacementBaseline preserves prior services that are absent from the current workflow while allowing an owning full deploy to provide explicit removal-pending records.

func PersistTakodDesiredIntentWithRemovals added in v0.10.0

func PersistTakodDesiredIntentWithRemovals(
	sshPool *ssh.Pool,
	cfg *config.Config,
	envName string,
	serverNames []string,
	source string,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	assignments map[string][]scheduler.Assignment,
	pendingRemovals map[string]config.ServiceConfig,
	gitInfo takodstate.GitInfo,
	message string,
	verbose bool,
) error

PersistTakodDesiredIntentWithRemovals keeps services that are about to be deleted in desired state until their cleanup has completed successfully. This preserves their authoritative assignment on a crash and makes the next deploy retry the same removal instead of forgetting where the workload ran.

func PersistTakodRuntimeState

func PersistTakodRuntimeState(
	sshPool *ssh.Pool,
	cfg *config.Config,
	envName string,
	serverNames []string,
	source string,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	actualState map[string]*reconcile.ActualService,
	nodeActualState map[string]map[string]*reconcile.ActualService,
	gitInfo takodstate.GitInfo,
	eventType string,
	message string,
	details map[string]string,
	verbose bool,
) error

PersistTakodRuntimeState writes desired/actual/event state documents to every target node.

func PersistTakodRuntimeStateWithAssignments added in v0.10.0

func PersistTakodRuntimeStateWithAssignments(
	sshPool *ssh.Pool,
	cfg *config.Config,
	envName string,
	serverNames []string,
	source string,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	actualState map[string]*reconcile.ActualService,
	nodeActualState map[string]map[string]*reconcile.ActualService,
	assignments map[string][]scheduler.Assignment,
	gitInfo takodstate.GitInfo,
	eventType string,
	message string,
	details map[string]string,
	verbose bool,
) error

PersistTakodRuntimeStateWithAssignments writes runtime state together with the scheduler's authoritative replica-to-node decisions. Callers that do not perform placement planning may use PersistTakodRuntimeState.

func PersistTakodRuntimeStateWithPlacementBaseline added in v0.10.0

func PersistTakodRuntimeStateWithPlacementBaseline(
	sshPool *ssh.Pool,
	cfg *config.Config,
	envName string,
	serverNames []string,
	source string,
	services map[string]config.ServiceConfig,
	imageRefs map[string]string,
	actualState map[string]*reconcile.ActualService,
	nodeActualState map[string]map[string]*reconcile.ActualService,
	assignments map[string][]scheduler.Assignment,
	priorDesired *takodstate.DesiredRevision,
	gitInfo takodstate.GitInfo,
	eventType string,
	message string,
	details map[string]string,
	verbose bool,
) error

PersistTakodRuntimeStateWithPlacementBaseline records final actual state without dropping prior desired-service records outside this workflow's scope. A full deploy that owns removals passes no baseline after cleanup.

func PreferredRuntimeServer added in v0.10.0

func PreferredRuntimeServer(cfg *config.Config, serverNames []string) (string, error)

PreferredRuntimeServer keeps controller-side operations on the protected local ingress whenever the local enrolled node is mutation-eligible.

func PreviousStableServiceDeploymentFromHistory

func PreviousStableServiceDeploymentFromHistory(history *remotestate.DeploymentHistory, serviceName string, listDeployments ListDeploymentsFunc) (*remotestate.DeploymentState, error)

PreviousStableServiceDeploymentFromHistory finds the most recent stable deployment for a service that precedes its current deployment.

func ReconcileProxy

func ReconcileProxy(deploy ProxyReconciler, services map[string]config.ServiceConfig, activeRevisions map[string]string) error

ReconcileProxy reconciles proxy routes, preferring revision-aware upstreams.

func RecordFailedDeploymentState

func RecordFailedDeploymentState(
	remoteSaver RemoteDeploymentSaver,
	localSaver LocalDeploymentSaver,
	deployment *remotestate.DeploymentState,
	cfg *config.Config,
	envName string,
	serverNames []string,
	commitInfo *git.CommitInfo,
	startTime time.Time,
	deploymentErr error,
) error

RecordFailedDeploymentState marks a deployment failed and persists it to remote (and optionally local) state.

func RecordFailedDeploymentStateContext

func RecordFailedDeploymentStateContext(
	ctx context.Context,
	remoteSaver RemoteDeploymentSaver,
	localSaver LocalDeploymentSaver,
	deployment *remotestate.DeploymentState,
	cfg *config.Config,
	envName string,
	serverNames []string,
	commitInfo *git.CommitInfo,
	startTime time.Time,
	deploymentErr error,
) error

RecordFailedDeploymentStateContext marks a deployment failed and persists it to remote (and optionally local) state bounded by ctx for remote writes.

func RecordStartedDeploymentState

func RecordStartedDeploymentState(
	remoteSaver RemoteDeploymentSaver,
	deployment *remotestate.DeploymentState,
) error

RecordStartedDeploymentState marks a deployment in progress and persists it to remote state before any deployment mutations start.

func RecordStartedDeploymentStateContext

func RecordStartedDeploymentStateContext(
	ctx context.Context,
	remoteSaver RemoteDeploymentSaver,
	deployment *remotestate.DeploymentState,
) error

RecordStartedDeploymentStateContext marks a deployment in progress and persists it to remote state before any deployment mutations start, bounded by ctx. Unlike failed-state cleanup, this helper honors cancellation directly so a canceled operation fails before mutating remote services.

func RedactedEnvKeys

func RedactedEnvKeys(env map[string]string) map[string]string

RedactedEnvKeys replaces env values with a redaction marker, keeping keys.

func ReleaseStateLeaseByID

func ReleaseStateLeaseByID(nodes []StateLeaseNodeResult, leaseID string, force bool, now time.Time) ([]string, error)

ReleaseStateLeaseByID releases a matching lease ID from already-collected nodes.

func ReleaseStateLeaseByIDContext

func ReleaseStateLeaseByIDContext(ctx context.Context, nodes []StateLeaseNodeResult, leaseID string, force bool, now time.Time) ([]string, error)

ReleaseStateLeaseByIDContext releases a matching lease ID from already-collected nodes bounded by ctx.

func RemoteConfigExportTargetNodes

func RemoteConfigExportTargetNodes(docs ConfigExportStateDocs) []string

RemoteConfigExportTargetNodes returns the clean sorted target node list from desired state, or actual state when desired has no targets.

func RemoteHistoryError

func RemoteHistoryError(err error) error

RemoteHistoryError wraps failures to persist history after a successful deploy.

func RemoveActualEmbeddedNode

func RemoveActualEmbeddedNode(nodes map[string]takodstate.ActualNodeSnapshot, nodeName string) (map[string]takodstate.ActualNodeSnapshot, bool)

RemoveActualEmbeddedNode returns a copy of nodes without nodeName.

func RemoveCleanupRequest

func RemoveCleanupRequest(cfg *config.Config, envName string, services map[string]config.ServiceConfig) takod.CleanupRequest

RemoveCleanupRequest builds the full app/stage takod cleanup request that remove (and destroy's decommission step) issues on each node.

func RemoveStateNodeName

func RemoveStateNodeName(nodes []string, nodeName string) ([]string, bool)

RemoveStateNodeName returns a copy of nodes without nodeName.

func RequireTakodRuntime

func RequireTakodRuntime(cfg *config.Config) error

RequireTakodRuntime rejects configs that do not use the takod runtime.

func ResolveCommitInfo

func ResolveCommitInfo(gitClient GitReader, allowDirty bool) (*git.CommitInfo, string, error)

ResolveCommitInfo reads HEAD commit info, enforcing a clean worktree unless allowDirty is set.

func ResolveLogTargetServers

func ResolveLogTargetServers(cfg *config.Config, envName, requestedServer string) (map[string]config.ServerConfig, error)

ResolveLogTargetServers resolves the logs --server selection against the configured environment nodes.

func ResolveRemoveTargetServers

func ResolveRemoveTargetServers(envName string, environmentServers []string, selected []string) ([]string, error)

ResolveRemoveTargetServers filters the --server selections against the environment's servers, preserving environment order and de-duplicating.

func ResolveStateLeaseTargetServerNames

func ResolveStateLeaseTargetServerNames(cfg *config.Config, envName string, requestedServer string) ([]string, error)

ResolveStateLeaseTargetServerNames resolves state lease --server selection against configured environment nodes.

func ResolveStatusTargetServerNames

func ResolveStatusTargetServerNames(cfg *config.Config, envName string, requestedServer string) ([]string, error)

ResolveStatusTargetServerNames resolves the status --server selection against the configured environment nodes.

func RetiredDeploymentServers

func RetiredDeploymentServers(previous []string, current []string) []string

RetiredDeploymentServers lists servers present in a previous deployment but absent from the current target set.

func RollbackNeedsTargetWorktree

func RollbackNeedsTargetWorktree(service config.ServiceConfig, targetDeployment *remotestate.DeploymentState) bool

RollbackNeedsTargetWorktree reports whether a rollback must rebuild the service image from the target deployment's git commit.

func RollbackProxyInputs

func RollbackProxyInputs(
	cfg *config.Config,
	envName string,
	services map[string]config.ServiceConfig,
	rollbackService string,
	serviceState remotestate.ServiceState,
	actualState map[string]*reconcile.ActualService,
) (map[string]config.ServiceConfig, map[string]string, map[string]string)

RollbackProxyInputs derives the desired services, image refs, and active revisions used to reconcile the proxy after a rollback.

func RollbackRemoteHistoryError

func RollbackRemoteHistoryError(err error) error

RollbackRemoteHistoryError wraps failures to persist history after the runtime mutation already succeeded.

func RollbackTargetCommit

func RollbackTargetCommit(targetDeployment *remotestate.DeploymentState) string

RollbackTargetCommit resolves the git commit recorded with the rollback target, preferring the full hash over the short form.

func RunDeploymentPlan

func RunDeploymentPlan(cfg *config.Config, envName string, serviceName string, service config.ServiceConfig, actualState map[string]*reconcile.ActualService) (map[string]config.ServiceConfig, *reconcile.ReconciliationPlan)

RunDeploymentPlan computes the single-service reconciliation plan for a configless run.

func SanitizeConfigExportServerName

func SanitizeConfigExportServerName(value string) string

SanitizeConfigExportServerName converts a host or supplied name into a valid generated server key. IP hosts get an "ip-" prefix because server keys must start with a lowercase letter — 203.0.113.10 derives "ip-203-0-113-10", so each address keeps a stable, unique key instead of collapsing to "server".

func ScaleTargetServers

func ScaleTargetServers(cfg *config.Config, envName string) ([]string, error)

ScaleTargetServers lists the environment's takod nodes in sorted order.

func ScaleTargetSummary

func ScaleTargetSummary(targets map[string]int) string

ScaleTargetSummary renders scale targets as a deterministic "service=replicas" list.

func SelectPromotionRevision

func SelectPromotionRevision(actual *reconcile.ActualService, requested string) (string, error)

SelectPromotionRevision resolves which warmed revision a promotion targets: the requested revision (full value or unique prefix) when given, otherwise the single warmed candidate.

func SelectRollbackTargetFromHistory

func SelectRollbackTargetFromHistory(history *remotestate.DeploymentHistory, deploymentID string, serviceName string, listDeployments ListDeploymentsFunc) (*remotestate.DeploymentState, error)

SelectRollbackTargetFromHistory resolves the rollback target: the requested deployment when an ID is given, otherwise the previous stable deployment for the service.

func ServicePorts

func ServicePorts(service config.ServiceConfig, internal bool, running int) string

func ServiceStatus

func ServiceStatus(running int, desired int) string

func ShortStatusRevision

func ShortStatusRevision(revision string) string

func ShouldReplicateDeploymentHistory added in v0.10.0

func ShouldReplicateDeploymentHistory(cfg *config.Config) bool

ShouldReplicateDeploymentHistory preserves legacy mesh replication while keeping enrolled platform state single-writer on the controller.

func SortedLogServerNames

func SortedLogServerNames(servers map[string]config.ServerConfig) []string

SortedLogServerNames returns server map keys in deterministic order.

func SourceLabelForArchive

func SourceLabelForArchive(archivePath string) string

SourceLabelForArchive returns the state source label for an --archive deploy.

func SourceLabelForImageOverride

func SourceLabelForImageOverride(source string, imageRef string) string

SourceLabelForImageOverride returns the state source label for an --image deploy.

func StartNotificationMessage

func StartNotificationMessage(project string, version string, envName string, revisionLabel string, revisionValue string, commitMessage string) string

StartNotificationMessage builds the deploy-start notification text.

func StateAuthorityTargets added in v0.10.0

func StateAuthorityTargets(cfg *config.Config, fallback []string) []string

StateAuthorityTargets keeps legacy replicated state unchanged while making enrolled clusters explicitly single-writer on the control-plane node.

func StateForgetNodeWarnings

func StateForgetNodeWarnings(results []StateForgetNodeNodeResult) []string

StateForgetNodeWarnings flattens per-node warnings with node prefixes.

func StateNodeNameInList

func StateNodeNameInList(nodes []string, nodeName string) bool

StateNodeNameInList reports whether nodeName appears in nodes.

func StateRepairWriteWarnings

func StateRepairWriteWarnings(results []StateRepairNodeWriteResult) []string

StateRepairWriteWarnings flattens and sorts per-node write warnings.

func StateStatusNoReachableMessage

func StateStatusNoReachableMessage(envName string, nodes []StateStatusRemoteNodeInput) string

StateStatusNoReachableMessage formats the fail-closed no-reachable-nodes error.

func StateStatusReachableCount

func StateStatusReachableCount(nodes []StateStatusRemoteNodeInput) int

StateStatusReachableCount returns the number of reachable remote nodes.

func StateStatusSyncRecommendation

func StateStatusSyncRecommendation(localExists bool, localCurrent *localstate.DeploymentState, bestHistory StateStatusHistoryCandidate, hasRemoteHistory bool, unreachableCount int) []string

StateStatusSyncRecommendation returns human-readable sync guidance used by both text rendering and machine result documents.

func StateStatusUnreachableCount

func StateStatusUnreachableCount(nodes []StateStatusRemoteNodeInput) int

StateStatusUnreachableCount returns the number of unreachable remote nodes.

func StateStatusUnreachableGuidance

func StateStatusUnreachableGuidance(nodes []StateStatusRemoteNodeInput) []string

StateStatusUnreachableGuidance returns operator guidance for unreachable nodes.

func SummarizeLogStreamResults

func SummarizeLogStreamResults(results []LogNodeResult) error

SummarizeLogStreamResults returns the historical aggregate error message for failed node streams.

func TakodSocketFromConfig

func TakodSocketFromConfig(cfg *config.Config) string

TakodSocketFromConfig resolves the takod unix socket path for a config.

func ValidateArchiveOptions

func ValidateArchiveOptions(serviceName string, archivePath string, source string, imageRef string) (string, error)

ValidateArchiveOptions validates the --archive deploy override.

func ValidateImageOptions

func ValidateImageOptions(serviceName string, imageRef string, source string) (string, error)

ValidateImageOptions validates the --image deploy override.

func ValidatePriorDesiredServices added in v0.10.0

func ValidatePriorDesiredServices(prior *takodstate.DesiredRevision, current map[string]config.ServiceConfig) error

ValidatePriorDesiredServices prevents a narrow workflow from hiding a persistent workload that was removed from configuration. Stateless and job records remain preserved until a full deploy owns their cleanup.

func ValidateStateForgetNodeName

func ValidateStateForgetNodeName(nodeName string) error

ValidateStateForgetNodeName validates node names used in state document keys.

func ValidateUpgradeCompatibility added in v0.10.0

func ValidateUpgradeCompatibility(version string, protocol int, minimum int) error

ValidateUpgradeCompatibility enforces the N/N-1 rolling-upgrade window. Protocol zero is the pre-protocol status shape and is treated as N-1 only.

func WithWorkingDirectory

func WithWorkingDirectory(dir string, fn func() error) error

WithWorkingDirectory runs fn from dir, restoring the original working directory afterwards.

Types

type AccessNodeResult added in v0.9.1

type AccessNodeResult struct {
	Name   string `json:"name"`
	Host   string `json:"host,omitempty"`
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

AccessNodeResult is the serializable outcome for one streamed proxy node.

type AccessResult added in v0.9.1

type AccessResult struct {
	APIVersion  string             `json:"apiVersion"`
	Kind        string             `json:"kind"`
	Project     string             `json:"project"`
	Environment string             `json:"environment"`
	Service     string             `json:"service,omitempty"`
	Tail        int                `json:"tail"`
	Follow      bool               `json:"follow"`
	Status      string             `json:"status"`
	Nodes       []AccessNodeResult `json:"nodes"`
	StartedAt   time.Time          `json:"startedAt"`
	Duration    float64            `json:"durationSeconds"`
	Message     string             `json:"message,omitempty"`
	Error       string             `json:"error,omitempty"`
}

AccessResult is the serializable outcome of streaming proxy access logs; the entries themselves stream as access.line events.

func NewAccessResult added in v0.9.1

func NewAccessResult(project string, environment string, service string, tail int, follow bool, startedAt time.Time, nodes []AccessNodeResult, summaryErr error) AccessResult

NewAccessResult assembles the access result document from per-node stream outcomes and the aggregate summary error, mirroring LogsResult semantics.

type ActionNodeOutcome added in v0.8.0

type ActionNodeOutcome struct {
	Server   string   `json:"server"`
	Host     string   `json:"host,omitempty"`
	Done     bool     `json:"done"`
	Error    string   `json:"error,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

ActionNodeOutcome reports one node's result for a fanout action.

type ActionResult added in v0.8.0

type ActionResult struct {
	APIVersion  string              `json:"apiVersion"`
	Kind        string              `json:"kind"`
	Project     string              `json:"project"`
	Environment string              `json:"environment"`
	Action      string              `json:"action"`
	Service     string              `json:"service,omitempty"`
	Outcome     string              `json:"outcome"`
	Servers     []ActionNodeOutcome `json:"servers"`
	Error       string              `json:"error,omitempty"`
}

ActionResult is the serializable acknowledgement of maintenance, live, and cleanup: what action ran, on which service, and per-node outcomes.

type AttentionError

type AttentionError struct {
	Err error
}

AttentionError marks a partial success that needs operator follow-up.

func (*AttentionError) Error

func (e *AttentionError) Error() string

func (*AttentionError) Unwrap

func (e *AttentionError) Unwrap() error

type BackupNodeOutcome added in v0.8.0

type BackupNodeOutcome struct {
	Server  string             `json:"server"`
	Host    string             `json:"host,omitempty"`
	Backups []takod.BackupInfo `json:"backups,omitempty"`
	// Deleted counts removed backups for delete/cleanup actions.
	Deleted int `json:"deleted,omitempty"`
	// Skipped lists volumes not present on this node during create.
	Skipped []string `json:"skipped,omitempty"`
	Error   string   `json:"error,omitempty"`
}

BackupNodeOutcome reports one node's backup-operation result. Backups reuses the takod backup schema (`id`, `volume`, `size`, `createdAt`, `path`, `compression`, `remote`, `warnings`).

type BackupResult added in v0.8.0

type BackupResult struct {
	APIVersion  string              `json:"apiVersion"`
	Kind        string              `json:"kind"`
	Project     string              `json:"project"`
	Environment string              `json:"environment"`
	Action      string              `json:"action"`
	Volume      string              `json:"volume,omitempty"`
	BackupID    string              `json:"backupId,omitempty"`
	Nodes       []BackupNodeOutcome `json:"nodes"`
	Error       string              `json:"error,omitempty"`
}

BackupResult is the serializable outcome of every `tako backup` action: list, create (single volume or --all), restore, delete, and cleanup.

type CertsNodeResult added in v0.9.2

type CertsNodeResult struct {
	Server       string                           `json:"server"`
	Host         string                           `json:"host,omitempty"`
	Certificates []takod.ProxyCertificateMetadata `json:"certificates"`
	Error        string                           `json:"error,omitempty"`
}

type CertsResult added in v0.9.2

type CertsResult struct {
	APIVersion  string            `json:"apiVersion"`
	Kind        string            `json:"kind"`
	Project     string            `json:"project"`
	Environment string            `json:"environment"`
	Action      string            `json:"action"`
	Domain      string            `json:"domain,omitempty"`
	Nodes       []CertsNodeResult `json:"nodes"`
	StartedAt   time.Time         `json:"startedAt"`
	Duration    float64           `json:"durationSeconds"`
	Error       string            `json:"error,omitempty"`
}

type Class

type Class int

Class categorizes engine errors for machine consumers. The CLI maps classes to process exit codes; see docs/MACHINE-INTERFACE.md.

const (
	// ClassNone means no error.
	ClassNone Class = 0
	// ClassFailed is an operation that ran and failed (deploy error).
	ClassFailed Class = 1
	// ClassInvalid is a rejected request: bad flags, config, or state.
	ClassInvalid Class = 2
	// ClassLocked means a concurrent operation holds the lock or lease.
	ClassLocked Class = 3
	// ClassConnectivity is an SSH or node connectivity failure.
	ClassConnectivity Class = 4
	// ClassCancelled means the context was cancelled mid-operation.
	ClassCancelled Class = 5
	// ClassAttention is a partial success needing operator attention.
	ClassAttention Class = 6
)

func Classify

func Classify(err error) Class

Classify maps an error to its Class for exit-code selection.

type CloneSetupResult added in v0.8.0

type CloneSetupResult struct {
	APIVersion  string        `json:"apiVersion"`
	Kind        string        `json:"kind"`
	Project     string        `json:"project,omitempty"`
	Environment string        `json:"environment,omitempty"`
	Status      string        `json:"status"`
	Checks      []DoctorCheck `json:"checks"`
	Passed      int           `json:"passed"`
	Warned      int           `json:"warned"`
	Failed      int           `json:"failed"`
}

CloneSetupResult is the serializable outcome of `tako clone-setup`: the guided post-clone walkthrough (config, .env, SSH, env bundle, state, secrets). Checks reuse the doctor check shape; Name carries the step the human output prints as a `=== Step N: Title ===` heading. Status is "ok" when no check failed and "attention" otherwise (exit code 6). Machine modes skip the interactive fix-up prompts and only report.

type ConfigExportDocuments

type ConfigExportDocuments struct {
	Desired bool `json:"desired"`
	Actual  bool `json:"actual"`
	History bool `json:"history"`
}

ConfigExportDocuments reports which takod state documents were present.

type ConfigExportRequest

type ConfigExportRequest struct {
	Project     string
	Environment string
	Server      string
	ServerName  string
	User        string
	SSHPort     int
	SSHKey      string
	Password    string
	Socket      string
	NoValidate  bool
}

ConfigExportRequest describes a config materialization operation against a remote takod node. File writing is intentionally not part of the request; CLI and SDK adapters decide where to persist or render the returned config.

type ConfigExportResult

type ConfigExportResult struct {
	APIVersion       string                `json:"apiVersion"`
	Kind             string                `json:"kind"`
	Project          string                `json:"project"`
	Environment      string                `json:"environment"`
	Source           ConfigExportSource    `json:"source"`
	TargetNodes      []string              `json:"targetNodes,omitempty"`
	Servers          []ConfigExportServer  `json:"servers"`
	Documents        ConfigExportDocuments `json:"documents"`
	Warnings         []ConfigExportWarning `json:"warnings,omitempty"`
	PasswordRedacted bool                  `json:"passwordRedacted,omitempty"`
	OutputPath       string                `json:"outputPath,omitempty"`
	Config           *config.Config        `json:"config,omitempty"`
	YAML             string                `json:"yaml,omitempty"`
}

ConfigExportResult is the machine-readable outcome of config export/pull. Config always contains the materialized data. YAML contains the generated YAML text; CLI adapters omit it from machine results when an output file was written, so stdout never carries raw YAML outside a JSON/NDJSON envelope.

type ConfigExportServer

type ConfigExportServer struct {
	Name             string `json:"name"`
	Host             string `json:"host"`
	User             string `json:"user"`
	Port             int    `json:"port,omitempty"`
	SSHKey           string `json:"sshKey,omitempty"`
	PasswordRedacted bool   `json:"passwordRedacted,omitempty"`
}

ConfigExportServer describes the connection details attached to one generated server entry. Passwords are never returned; PasswordRedacted reports whether a placeholder was written to the config.

type ConfigExportSource

type ConfigExportSource struct {
	Host                string `json:"host"`
	User                string `json:"user"`
	Port                int    `json:"port,omitempty"`
	Socket              string `json:"socket,omitempty"`
	RequestedServerName string `json:"requestedServerName,omitempty"`
}

ConfigExportSource describes the remote state source node supplied by the caller.

type ConfigExportStateDocs

type ConfigExportStateDocs struct {
	Desired *takoapi.DesiredStateDocument
	Actual  *takoapi.ActualStateDocument
	History *takoapi.DeploymentHistoryDocument
}

ConfigExportStateDocs groups the remote takod documents used to materialize a config. Desired and actual may be independently absent, but not both.

func ReadConfigExportState

func ReadConfigExportState(reader ConfigExportStateReader, project, environment string) (ConfigExportStateDocs, error)

ReadConfigExportState reads desired, actual, and history documents, treating individual not-found responses as absent and requiring desired or actual.

type ConfigExportStateReader

type ConfigExportStateReader interface {
	ReadDesired(project, environment string) (*takoapi.DesiredStateDocument, error)
	ReadActual(project, environment string) (*takoapi.ActualStateDocument, error)
	ReadHistory(project, environment string) (*takoapi.DeploymentHistoryDocument, error)
}

ConfigExportStateReader is the subset of stateclient.Client used by config export. Tests and SDK users can provide fakes without opening SSH sessions.

type ConfigExportWarning

type ConfigExportWarning struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Service string `json:"service,omitempty"`
	Server  string `json:"server,omitempty"`
}

ConfigExportWarning is a JSON-tagged warning for machine result documents.

type ConfirmationRequiredError

type ConfirmationRequiredError struct {
	Reason string
}

ConfirmationRequiredError is returned by non-interactive apply paths when the computed plan needs explicit approval.

func (*ConfirmationRequiredError) Error

func (e *ConfirmationRequiredError) Error() string

type ConnectivityError

type ConnectivityError struct {
	Server string
	Err    error
}

ConnectivityError wraps SSH/node connection failures.

func (*ConnectivityError) Error

func (e *ConnectivityError) Error() string

func (*ConnectivityError) Unwrap

func (e *ConnectivityError) Unwrap() error

type DeployPlan

type DeployPlan struct {
	APIVersion   string            `json:"apiVersion"`
	Kind         string            `json:"kind"`
	Project      string            `json:"project"`
	Environment  string            `json:"environment"`
	Revision     string            `json:"revision"`
	Source       string            `json:"source"`
	Git          *GitInfo          `json:"git,omitempty"`
	Servers      []string          `json:"servers"`
	Services     []string          `json:"services"`
	Changes      []PlanChange      `json:"changes"`
	SharedBuilds []PlanSharedBuild `json:"sharedBuilds,omitempty"`
	Destructive  bool              `json:"destructive"`
	Empty        bool              `json:"empty"`

	// HumanText is reconcile plan text exactly as the CLI displays it.
	// Excluded from the plan hash.
	HumanText string `json:"humanText,omitempty"`
}

DeployPlan is the serializable outcome of PlanDeploy: what would change, whether that needs confirmation, and the identity of what would deploy. It feeds confirmation screens and the --plan-only machine output.

func (*DeployPlan) Hash

func (p *DeployPlan) Hash() string

Hash returns a stable fingerprint of the plan's decision-relevant fields, used to detect drift between a reviewed plan and a later apply.

type DeployRequest

type DeployRequest struct {
	Config      *config.Config
	Environment string
	// WorkDir is the project directory for git metadata and local state.
	// Empty means the current directory.
	WorkDir string

	Service  string
	Image    string
	Source   string
	Archive  string
	Revision string

	BuildStrategy string
	SkipBuild     bool
	AllowDirty    bool
	Force         bool
	// Verbose enables detailed progress from the deployer and dependency
	// resolver; debug-level events are emitted regardless and filtered by
	// renderers.
	Verbose bool

	SkipDomainCheck bool
	StrictDomains   bool
	DomainTimeout   time.Duration
	DomainTargets   []string
}

DeployRequest describes one deploy operation. Config must be loaded and validated; Environment must be resolved. All fields mirror the CLI flags.

type DeployResult

type DeployResult struct {
	APIVersion  string                   `json:"apiVersion"`
	Kind        string                   `json:"kind"`
	Project     string                   `json:"project"`
	Environment string                   `json:"environment"`
	Status      takoapi.DeploymentStatus `json:"status"`
	Revision    string                   `json:"revision,omitempty"`
	Git         *GitInfo                 `json:"git,omitempty"`
	Services    []ServiceOutcome         `json:"services"`
	// ManualPending lists services warmed for manual promotion.
	ManualPending []string  `json:"manualPending,omitempty"`
	URLs          []string  `json:"urls,omitempty"`
	InternalURLs  []string  `json:"internalUrls,omitempty"`
	StartedAt     time.Time `json:"startedAt"`
	Duration      float64   `json:"durationSeconds"`
	PlanHash      string    `json:"planHash,omitempty"`
	Message       string    `json:"message,omitempty"`
	Error         string    `json:"error,omitempty"`
}

DeployResult is the serializable outcome of ApplyDeploy.

type DeploySession

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

DeploySession carries an in-flight deploy between Plan and Apply. It holds the local state lock, remote leases, and SSH pool for the operation; Close releases them. A session must be closed exactly once, after Apply or after the caller abandons the plan.

func (*DeploySession) Apply

func (s *DeploySession) Apply(ctx context.Context) (*DeployResult, error)

Apply executes a planned deployment. The caller is responsible for confirmation gating; Apply runs the plan unconditionally.

func (*DeploySession) Close

func (s *DeploySession) Close()

Close releases the session's resources: temp build contexts, remote leases, SSH connections, and the local state lock. Idempotent.

func (*DeploySession) NeedsConfirmation

func (s *DeploySession) NeedsConfirmation() bool

NeedsConfirmation reports whether the plan includes destructive changes that need explicit approval before Apply.

func (*DeploySession) Plan

func (s *DeploySession) Plan() DeployPlan

Plan returns the serializable plan document for confirmation screens and machine output.

type DestroyRequest

type DestroyRequest struct {
	Config      *config.Config `json:"-"`
	Environment string         `json:"environment"`
	// PurgeAll also prunes app-owned leftovers after decommission.
	PurgeAll bool `json:"purgeAll,omitempty"`
	// Force mirrors the --force flag; it suppresses the production-server
	// warning that precedes the caller's confirmation prompt.
	Force   bool `json:"force,omitempty"`
	Verbose bool `json:"verbose,omitempty"`
}

DestroyRequest describes one destroy operation: decommission this app/stage's runtime on every environment node, optionally purging app-owned leftovers. Config must be loaded and validated; Environment must be resolved.

type DestroyResult

type DestroyResult struct {
	APIVersion  string                 `json:"apiVersion"`
	Kind        string                 `json:"kind"`
	Project     string                 `json:"project"`
	Environment string                 `json:"environment"`
	Mode        string                 `json:"mode"`
	PurgeAll    bool                   `json:"purgeAll,omitempty"`
	Servers     []DestroyServerOutcome `json:"servers"`
	StartedAt   time.Time              `json:"startedAt"`
	Duration    float64                `json:"durationSeconds"`
	Message     string                 `json:"message,omitempty"`
	Error       string                 `json:"error,omitempty"`
}

DestroyResult is the serializable outcome of DestroySession.Apply.

type DestroyServerOutcome

type DestroyServerOutcome struct {
	Name      string `json:"name"`
	Host      string `json:"host,omitempty"`
	Destroyed bool   `json:"destroyed"`
	Error     string `json:"error,omitempty"`
}

DestroyServerOutcome reports what happened on one node during destroy.

type DestroySession

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

DestroySession carries an in-flight destroy between Plan and Apply. Plan acquires the local state lock and announces what destruction will do; the caller gates the confirmation prompt and calls Apply to execute. Close releases the state lock.

func (*DestroySession) Apply

func (s *DestroySession) Apply(ctx context.Context) (*DestroyResult, error)

Apply executes the planned destroy. The caller gates confirmation.

func (*DestroySession) Close

func (s *DestroySession) Close()

Close releases the local state lock. Idempotent.

func (*DestroySession) Environment

func (s *DestroySession) Environment() string

Environment returns the resolved target environment.

func (*DestroySession) HasProduction

func (s *DestroySession) HasProduction() bool

HasProduction reports whether any target server name looks like a production node.

func (*DestroySession) ProjectName

func (s *DestroySession) ProjectName() string

ProjectName exposes the project name the confirmation prompt asks for.

func (*DestroySession) ServerNames

func (s *DestroySession) ServerNames() []string

ServerNames returns the environment servers destruction targets.

type DiscoveryExportsResult added in v0.8.0

type DiscoveryExportsResult struct {
	APIVersion string `json:"apiVersion"`
	Kind       string `json:"kind"`
	// Environment is empty when --all-environments was requested.
	Environment     string                 `json:"environment,omitempty"`
	AllEnvironments bool                   `json:"allEnvironments,omitempty"`
	Nodes           []DiscoveryNodeExports `json:"nodes"`
	Error           string                 `json:"error,omitempty"`
}

DiscoveryExportsResult is the serializable outcome of `tako discovery exports`. All nodes failing exits 1; a partial read exits 6; both still emit the document.

type DiscoveryNodeExports added in v0.8.0

type DiscoveryNodeExports struct {
	Server  string                        `json:"server"`
	Host    string                        `json:"host,omitempty"`
	Exports []takod.ExportDiscoveryRecord `json:"exports,omitempty"`
	Error   string                        `json:"error,omitempty"`
}

DiscoveryNodeExports is one node's exported service discovery records. Exports reuses the takod export-discovery record schema.

type DoctorCheck added in v0.8.0

type DoctorCheck struct {
	Name        string `json:"name"`
	Status      string `json:"status"`
	Detail      string `json:"detail"`
	Remediation string `json:"remediation,omitempty"`
}

DoctorCheck is one health-check outcome. Name is the check section the human output prints as a `=== Section ===` heading; a section may emit several checks.

type DoctorResult added in v0.8.0

type DoctorResult struct {
	APIVersion  string        `json:"apiVersion"`
	Kind        string        `json:"kind"`
	Project     string        `json:"project,omitempty"`
	Environment string        `json:"environment,omitempty"`
	SkipRemote  bool          `json:"skipRemote,omitempty"`
	Status      string        `json:"status"`
	Checks      []DoctorCheck `json:"checks"`
	Passed      int           `json:"passed"`
	Warned      int           `json:"warned"`
	Failed      int           `json:"failed"`
}

DoctorResult is the serializable outcome of `tako doctor`. Status is "ok" when no check failed and "attention" otherwise (exit code 6). Doctor is populated cmd-local: its checks mix pure-local reads with direct SSH probes that predate the engine.

type DomainStatusEntry added in v0.8.0

type DomainStatusEntry struct {
	Service string `json:"service"`
	Domain  string `json:"domain"`
	// Role is "serving", "redirect", or "ad-hoc".
	Role        string   `json:"role"`
	State       string   `json:"state"`
	DNS         string   `json:"dns"`
	TLS         string   `json:"tls"`
	ResolvedIPs []string `json:"resolvedIps,omitempty"`
	CNAME       string   `json:"cname,omitempty"`
	CDN         string   `json:"cdn,omitempty"`
	Message     string   `json:"message,omitempty"`
	Warning     string   `json:"warning,omitempty"`
	DNSError    string   `json:"dnsError,omitempty"`
	TLSError    string   `json:"tlsError,omitempty"`
}

DomainStatusEntry is one public domain's DNS/TLS readiness.

type DomainStatusOptions

type DomainStatusOptions struct {
	Timeout         time.Duration
	Strict          bool
	ExpectedTargets []string
}

DomainStatusOptions controls domain readiness monitoring.

type DomainStatusSpec

type DomainStatusSpec struct {
	Service                     string
	Domain                      string
	Role                        string
	CDN                         string
	WarnUntrustedAccessControls bool
}

DomainStatusSpec identifies one public domain to check.

func CollectConfiguredDomainSpecs

func CollectConfiguredDomainSpecs(services map[string]config.ServiceConfig, serviceFilter string) []DomainStatusSpec

CollectConfiguredDomainSpecs lists the public domains configured on services, optionally filtered to one service.

type DomainsHostsResult added in v0.8.0

type DomainsHostsResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	// Service is the --service filter; AddressMode mirrors --address.
	Service     string              `json:"service,omitempty"`
	AddressMode string              `json:"addressMode,omitempty"`
	Entries     []InternalHostEntry `json:"entries"`
}

DomainsHostsResult is the serializable outcome of `tako domains hosts`.

type DomainsResult added in v0.8.0

type DomainsResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	// Service is the --service filter when one was requested.
	Service         string              `json:"service,omitempty"`
	ExpectedTargets []string            `json:"expectedTargets,omitempty"`
	AllActive       bool                `json:"allActive"`
	Domains         []DomainStatusEntry `json:"domains"`
}

DomainsResult is the serializable outcome of `tako domains status`. With --strict, pending domains exit 6 and still emit the document.

type DriftEntry added in v0.8.0

type DriftEntry struct {
	Service  string            `json:"service"`
	Type     string            `json:"type"`
	Severity string            `json:"severity"`
	Expected string            `json:"expected"`
	Actual   string            `json:"actual"`
	Details  map[string]string `json:"details,omitempty"`
}

DriftEntry is one detected desired-vs-actual difference.

type DriftResult added in v0.8.0

type DriftResult struct {
	APIVersion  string       `json:"apiVersion"`
	Kind        string       `json:"kind"`
	Project     string       `json:"project"`
	Environment string       `json:"environment"`
	Drifted     bool         `json:"drifted"`
	Drifts      []DriftEntry `json:"drifts,omitempty"`
	ServicesOK  []string     `json:"servicesOk,omitempty"`
	CheckedAt   time.Time    `json:"checkedAt"`
	Duration    float64      `json:"durationSeconds"`
}

DriftResult is the serializable outcome of a single-shot `tako drift` check. Drifted mirrors exit code 6; watch mode is interactive-only and never emits this document.

type Engine

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

Engine runs Tako operations against configured servers.

func New

func New(opts Options) *Engine

New constructs an Engine. Every emitted event passes through a secrets redactor; operations register sensitive values (service env values, SSH passwords) before emitting anything that could contain them.

func (*Engine) ApplyPlacementMovement added in v0.10.0

func (e *Engine) ApplyPlacementMovement(ctx context.Context, req PlacementApplyRequest) (*PlacementApplyResult, error)

func (*Engine) ApplyRemovals

func (e *Engine) ApplyRemovals(remover ServiceRemover, plan *reconcile.ReconciliationPlan) error

ApplyRemovals removes services the plan marks for removal.

func (*Engine) EventStream

func (e *Engine) EventStream() *events.Stream

EventStream exposes the engine's stamped, redacting event stream so adapters can bridge auxiliary output (for example build logs) into it.

func (*Engine) Exec added in v0.8.0

func (e *Engine) Exec(ctx context.Context, req ExecRequest) (*ExecResult, error)

Exec resolves placement, opens the SSH stream to takod's /v1/exec, and forwards output as exec.* events until the terminal exit frame.

func (*Engine) ExecInteractive added in v0.8.1

func (e *Engine) ExecInteractive(ctx context.Context, req ExecRequest, terminal ExecTerminal) (*ExecResult, error)

ExecInteractive runs a command in a service's context with stdin attached over a full-duplex frame stream (SSH direct-streamlocal to the takod socket — no remote curl). With terminal.TTY the remote process runs under a pseudo-terminal that follows local resizes. Raw terminal bytes flow through terminal.Stdin/Stdout, not events; interactive exec is rejected in machine output modes at the command layer.

func (*Engine) ExportConfig

func (e *Engine) ExportConfig(ctx context.Context, req ConfigExportRequest) (*ConfigExportResult, error)

ExportConfig reads replicated takod state over SSH and materializes it into a Tako config. The engine does not print or write files.

func (*Engine) History

func (e *Engine) History(ctx context.Context, req HistoryRequest) (*HistoryResult, error)

History returns deployment history rows selected from the freshest reachable mesh history source. It performs no rendering or prompting.

func (*Engine) JobRuns added in v0.8.0

func (e *Engine) JobRuns(ctx context.Context, req JobRunsRequest) (*JobRunsResult, error)

JobRuns reads run history across the environment's nodes, newest first.

func (*Engine) Jobs added in v0.8.0

func (e *Engine) Jobs(ctx context.Context, req JobsRequest) (*JobsResult, error)

Jobs lists the environment's scheduled jobs across its nodes.

func (*Engine) MonitorDomainStatuses

func (e *Engine) MonitorDomainStatuses(ctx context.Context, checker *health.HealthChecker, specs []DomainStatusSpec, options DomainStatusOptions) ([]health.DomainStatus, error)

MonitorDomainStatuses polls DNS/TLS readiness for the given domains until all are active or the timeout elapses, emitting progress events.

func (*Engine) PlanDeploy

func (e *Engine) PlanDeploy(ctx context.Context, req DeployRequest) (*DeploySession, error)

PlanDeploy validates the request, acquires the local lock and remote leases, gathers running state, and computes the reconciliation plan. The returned session must be Closed; call Apply to execute the plan.

func (*Engine) PlanDestroy

func (e *Engine) PlanDestroy(ctx context.Context, req DestroyRequest) (*DestroySession, error)

PlanDestroy validates the destroy targets, acquires the local state lock, and emits the warning summary of what destruction will do. The returned session must be Closed; call Apply to execute the plan.

func (*Engine) PlanPlacementMovement added in v0.10.0

func (e *Engine) PlanPlacementMovement(ctx context.Context, req PlacementPlanRequest) (*scheduler.MovementPlan, error)

PlanPlacementMovement reads the current authoritative desired revision and returns a digest-bound proposal. It is read-only: applying movement remains a separately authorized operation and persistent moves always require a dedicated data-migration strategy.

func (*Engine) PlanRemove

func (e *Engine) PlanRemove(ctx context.Context, req RemoveRequest) (*RemoveSession, error)

PlanRemove validates the remove targets and emits the warning summary of what removal will and will not do. The returned session holds no remote resources; Apply acquires leases and executes the cleanup.

func (*Engine) PlanRun

func (e *Engine) PlanRun(ctx context.Context, req RunRequest) (*RunSession, error)

PlanRun connects to the target node, sets up the takod runtime, gathers running state, and computes the reconciliation plan for a configless run.

func (*Engine) Promote

func (e *Engine) Promote(ctx context.Context, req PromoteRequest) (*PromoteResult, error)

Promote switches proxy routes to a warmed blue-green revision, prunes stale revisions, and persists the promoted state. Promotion has no interactive confirmation, so it runs as a single method rather than a plan/apply session.

func (*Engine) PruneRevisionsAfterGrace

func (e *Engine) PruneRevisionsAfterGrace(pruner RevisionPruner, services map[string]config.ServiceConfig, keepRevisions map[string]string, sleep func(time.Duration)) error

PruneRevisionsAfterGrace prunes stale revisions after the blue-green grace period, using the supplied sleep function.

func (*Engine) RedactSensitive added in v0.9.2

func (e *Engine) RedactSensitive(value string) string

RedactSensitive applies the same registered-secret redaction used by the event stream to adapter-owned result and error fields.

func (*Engine) RegisterACMEDNSSecrets added in v0.9.3

func (e *Engine) RegisterACMEDNSSecrets(cfg *config.Config)

RegisterACMEDNSSecrets adds environment-scoped DNS provider credentials to the same redactor used for event streams, progress output, and result docs.

func (*Engine) RegisterRegistrySecrets added in v0.8.0

func (e *Engine) RegisterRegistrySecrets(cfg *config.Config)

RegisterRegistrySecrets adds every configured registry credential to the event redactor so pull/build output and result docs never carry them.

func (*Engine) RegisterSecret

func (e *Engine) RegisterSecret(value string)

RegisterSecret adds a value to the event redactor.

func (*Engine) ReleaseStateLease

func (e *Engine) ReleaseStateLease(ctx context.Context, req StateLeaseReleaseRequest) (*StateLeaseReleaseResult, error)

ReleaseStateLease reads current leases and releases the exact matching ID on every selected reachable node. Active leases require Force.

func (*Engine) Rollback

func (e *Engine) Rollback(ctx context.Context, req RollbackRequest) (*RollbackResult, error)

Rollback re-deploys a service from a recorded deployment state, reconciles the proxy, and persists the rolled-back state across the mesh. Rollback has no interactive confirmation, so it runs as a single method rather than a plan/apply session.

func (*Engine) Scale

func (e *Engine) Scale(ctx context.Context, req ScaleRequest) (*ScaleResult, error)

Scale reconciles running takod services to the requested replica counts without rebuilding images, then persists runtime state and deployment history. Scale has no confirmation step, so it runs as a single call.

func (*Engine) StateForgetNode

func (e *Engine) StateForgetNode(ctx context.Context, req StateForgetNodeRequest) (*StateForgetNodeResult, error)

StateForgetNode removes a retired node from aggregate and per-node actual runtime state across already-collected reachable nodes. It never prompts or renders output; adapters own confirmation, lease acquisition, and rendering.

func (*Engine) StateLease

func (e *Engine) StateLease(ctx context.Context, req StateLeaseRequest) (*StateLeaseResult, error)

StateLease reads current remote operation leases from the selected nodes.

func (*Engine) StatePull

func (e *Engine) StatePull(ctx context.Context, req StatePullRequest) (*StatePullResult, error)

StatePull refreshes local deployment state from the best remote deployment history, falling back to runtime-state recovery. It never renders output; adapters provide all I/O through seams and render the returned result.

func (*Engine) StateRepair

func (e *Engine) StateRepair(ctx context.Context, req StateRepairRequest) (*StateRepairResult, error)

StateRepair selects the freshest collected repair sources and writes them to already-collected reachable nodes. It never dials SSH, acquires leases, prompts, or renders output; adapters own those responsibilities.

func (*Engine) StateStatus

func (e *Engine) StateStatus(ctx context.Context, req StateStatusRequest) (*StateStatusResult, error)

StateStatus builds a machine-readable status result from adapter-collected local and remote state. It never prints or performs network I/O.

func (*Engine) Status

func (e *Engine) Status(ctx context.Context, req StatusRequest) (*StatusResult, error)

Status returns the takod mesh status for configured services.

func (*Engine) StreamLogs

func (e *Engine) StreamLogs(ctx context.Context, req LogsRequest) (*LogsResult, error)

StreamLogs streams service logs from the selected takod nodes. Human output is emitted only as events; the returned result is suitable for machine output documents.

func (*Engine) TriggerJob added in v0.8.0

func (e *Engine) TriggerJob(ctx context.Context, req JobTriggerRequest) (*JobTriggerResult, error)

TriggerJob runs a scheduled job now on the node holding its schedule, streaming output as jobs.trigger.* events until the exit frame.

type ExecRequest added in v0.8.0

type ExecRequest struct {
	Config      *config.Config
	Environment string
	Service     string
	// Server pins the target node; empty resolves to the first node where
	// the service is deployed.
	Server string
	// Replica selects the 1-based running replica in attach mode.
	Replica int
	// OneOff runs the command in a fresh container from the service's
	// current image with its env/secrets and network instead of attaching
	// to a running replica.
	OneOff  bool
	Timeout time.Duration
	Command []string
}

ExecRequest runs a command in a service's context on one node.

type ExecResult added in v0.8.0

type ExecResult struct {
	APIVersion  string   `json:"apiVersion"`
	Kind        string   `json:"kind"`
	Project     string   `json:"project"`
	Environment string   `json:"environment"`
	Service     string   `json:"service"`
	Server      string   `json:"server"`
	Host        string   `json:"host,omitempty"`
	Container   string   `json:"container,omitempty"`
	Mode        string   `json:"mode"`
	Command     []string `json:"command"`
	ExitCode    int      `json:"exitCode"`
	DurationMs  int64    `json:"durationMs"`
	Error       string   `json:"error,omitempty"`
}

ExecResult is the serializable outcome of `tako exec`. ExitCode is the remote command's code; the tako process itself reports success when the exec ran to completion (human mode mirrors ExitCode for scripting).

type ExecTerminal added in v0.8.1

type ExecTerminal struct {
	Stdin  io.Reader
	Stdout io.Writer
	// TTY requests a server-side pseudo-terminal (docker exec -t).
	TTY bool
	// InitialSize seeds the remote PTY; zero fields use server defaults.
	InitialSize ptystream.Winsize
	// Resize delivers live terminal size changes (SIGWINCH). Optional.
	Resize <-chan ptystream.Winsize
}

ExecTerminal carries the local terminal endpoints for an interactive exec session. The caller owns raw-mode setup and restoration.

type GitInfo

type GitInfo struct {
	Commit      string `json:"commit,omitempty"`
	CommitShort string `json:"commitShort,omitempty"`
	Branch      string `json:"branch,omitempty"`
	Message     string `json:"message,omitempty"`
	Author      string `json:"author,omitempty"`
	Dirty       bool   `json:"dirty,omitempty"`
}

GitInfo captures the source commit recorded with a deployment.

type GitReader

type GitReader interface {
	IsRepository() bool
	HasUncommittedChanges() (bool, error)
	GetStatus() (string, error)
	GetCommitInfo(string) (*git.CommitInfo, error)
}

GitReader is the git metadata surface the engine needs from a repository.

type GitStrings

type GitStrings struct {
	Hash      string
	ShortHash string
	Branch    string
	Message   string
	Author    string
}

GitStrings are the commit fields recorded with a deployment, empty-safe.

func GitStringsFromCommit

func GitStringsFromCommit(commitInfo *git.CommitInfo) GitStrings

GitStringsFromCommit flattens optional commit info into GitStrings.

type HistoryDeployment

type HistoryDeployment struct {
	ID              string                       `json:"id"`
	DisplayID       string                       `json:"displayId,omitempty"`
	Commit          string                       `json:"commit,omitempty"`
	Timestamp       time.Time                    `json:"timestamp"`
	Version         string                       `json:"version,omitempty"`
	Status          remotestate.DeploymentStatus `json:"status"`
	DurationSeconds float64                      `json:"durationSeconds"`
	Duration        string                       `json:"duration,omitempty"`
	Message         string                       `json:"message,omitempty"`
	Error           string                       `json:"error,omitempty"`
}

HistoryDeployment is one deployment row in a HistoryResult.

type HistoryRequest

type HistoryRequest struct {
	Config      *config.Config
	Environment string
	// Server is the optional requested server filter from --server.
	Server string
	Limit  int
	// Status is the optional requested deployment status filter from --status.
	Status        string
	IncludeFailed bool

	// HistorySource and ListDeployments are seams for history helpers shared
	// with cmd/state.go and rollback; see the type docs in rollback.go.
	HistorySource   RollbackHistorySourceFunc
	ListDeployments ListDeploymentsFunc
}

HistoryRequest describes one deployment-history read operation. Config must be loaded and Environment must be resolved by the adapter.

type HistoryResult

type HistoryResult struct {
	APIVersion    string              `json:"apiVersion"`
	Kind          string              `json:"kind"`
	Project       string              `json:"project"`
	Environment   string              `json:"environment"`
	SourceServer  string              `json:"sourceServer,omitempty"`
	Server        string              `json:"server,omitempty"`
	Status        string              `json:"status,omitempty"`
	Limit         int                 `json:"limit,omitempty"`
	IncludeFailed bool                `json:"includeFailed"`
	Deployments   []HistoryDeployment `json:"deployments"`
}

HistoryResult is the serializable outcome of History.

type InternalHostEntry added in v0.8.0

type InternalHostEntry struct {
	Service string `json:"service"`
	Host    string `json:"host"`
	Address string `json:"address"`
	Server  string `json:"server,omitempty"`
	Source  string `json:"source,omitempty"`
}

InternalHostEntry is one /etc/hosts mapping for an internal proxy route.

type InvalidRequestError

type InvalidRequestError struct {
	Err error
}

InvalidRequestError rejects a request before any mutation happens.

func (*InvalidRequestError) Error

func (e *InvalidRequestError) Error() string

func (*InvalidRequestError) Unwrap

func (e *InvalidRequestError) Unwrap() error

type JobInfo added in v0.8.0

type JobInfo struct {
	Name           string      `json:"name"`
	Server         string      `json:"server"`
	Schedule       string      `json:"schedule"`
	Timezone       string      `json:"timezone,omitempty"`
	Image          string      `json:"image,omitempty"`
	Command        []string    `json:"command,omitempty"`
	TimeoutSeconds int         `json:"timeoutSeconds,omitempty"`
	NextRun        *time.Time  `json:"nextRun,omitempty"`
	LastRun        *JobRunInfo `json:"lastRun,omitempty"`
}

JobInfo is one scheduled job as reported by its owning node.

type JobRunInfo added in v0.8.0

type JobRunInfo struct {
	Job        string    `json:"job"`
	Server     string    `json:"server"`
	Trigger    string    `json:"trigger"`
	Container  string    `json:"container,omitempty"`
	StartedAt  time.Time `json:"startedAt"`
	FinishedAt time.Time `json:"finishedAt"`
	DurationMs int64     `json:"durationMs"`
	ExitCode   int       `json:"exitCode"`
	Status     string    `json:"status"`
	Output     string    `json:"output,omitempty"`
}

JobRunInfo is one recorded job run.

type JobRunsRequest added in v0.8.0

type JobRunsRequest struct {
	Config      *config.Config
	Environment string
	Job         string
	Server      string
}

JobRunsRequest reads run history for one job or every job.

type JobRunsResult added in v0.8.0

type JobRunsResult struct {
	APIVersion  string       `json:"apiVersion"`
	Kind        string       `json:"kind"`
	Project     string       `json:"project"`
	Environment string       `json:"environment"`
	Job         string       `json:"job,omitempty"`
	Runs        []JobRunInfo `json:"runs"`
}

JobRunsResult is the serializable outcome of `tako jobs runs`.

type JobTriggerRequest added in v0.8.0

type JobTriggerRequest struct {
	Config      *config.Config
	Environment string
	Job         string
	Server      string
}

JobTriggerRequest runs a scheduled job immediately on its owning node.

type JobTriggerResult added in v0.8.0

type JobTriggerResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Job         string `json:"job"`
	Server      string `json:"server"`
	Container   string `json:"container,omitempty"`
	ExitCode    int    `json:"exitCode"`
	DurationMs  int64  `json:"durationMs"`
	Error       string `json:"error,omitempty"`
}

JobTriggerResult is the serializable outcome of `tako jobs trigger`. ExitCode is the job command's code; the tako process itself reports success when the run completed (human mode mirrors ExitCode).

type JobsRequest added in v0.8.0

type JobsRequest struct {
	Config      *config.Config
	Environment string
	Server      string
}

JobsRequest lists scheduled jobs for an environment.

type JobsResult added in v0.8.0

type JobsResult struct {
	APIVersion  string    `json:"apiVersion"`
	Kind        string    `json:"kind"`
	Project     string    `json:"project"`
	Environment string    `json:"environment"`
	Jobs        []JobInfo `json:"jobs"`
}

JobsResult is the serializable outcome of `tako jobs`.

type ListDeploymentsFunc

type ListDeploymentsFunc func(history *remotestate.DeploymentHistory, opts *remotestate.HistoryOptions) []*remotestate.DeploymentState

ListDeploymentsFunc filters and orders deployments from a history document. The cmd layer supplies it because the shared listing helper is also used by `tako history` and stays in cmd.

type LocalDeploymentSaver

type LocalDeploymentSaver interface {
	SaveDeployment(*localstate.DeploymentState) error
}

LocalDeploymentSaver persists deployment records to local .tako state.

type LockedError

type LockedError struct {
	Operation string
	Holder    string
	Err       error
}

LockedError means the local state lock or a remote lease is held by another operation. Holder describes the owner when known.

func (*LockedError) Error

func (e *LockedError) Error() string

func (*LockedError) Unwrap

func (e *LockedError) Unwrap() error

type LogNodeResult

type LogNodeResult struct {
	Index      int
	ServerName string
	Host       string
	Err        error
}

LogNodeResult captures one node's fan-out outcome for log streaming.

func StreamLogNodesWith

func StreamLogNodesWith(ctx context.Context, servers map[string]config.ServerConfig, stream LogNodeStreamFunc) []LogNodeResult

StreamLogNodesWith fans log streaming out to the selected nodes concurrently and returns results in deterministic server-name order.

type LogNodeStreamFunc

type LogNodeStreamFunc func(serverName string, server config.ServerConfig, prefix bool) error

LogNodeStreamFunc streams one node. prefix reports whether human log lines should be node-prefixed because more than one node is selected.

type LogsNodeResult

type LogsNodeResult struct {
	Name   string `json:"name"`
	Host   string `json:"host,omitempty"`
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

LogsNodeResult is the serializable outcome for one streamed takod node.

type LogsRequest

type LogsRequest struct {
	Config      *config.Config
	Environment string
	Service     string
	Server      string
	Tail        int
	Follow      bool
}

LogsRequest describes one logs streaming operation. Config must be loaded and validated; Environment must be resolved.

type LogsResult

type LogsResult struct {
	APIVersion  string           `json:"apiVersion"`
	Kind        string           `json:"kind"`
	Project     string           `json:"project"`
	Environment string           `json:"environment"`
	Service     string           `json:"service"`
	Tail        int              `json:"tail"`
	Follow      bool             `json:"follow"`
	Status      string           `json:"status"`
	Nodes       []LogsNodeResult `json:"nodes"`
	StartedAt   time.Time        `json:"startedAt"`
	Duration    float64          `json:"durationSeconds"`
	Message     string           `json:"message,omitempty"`
	Error       string           `json:"error,omitempty"`
}

LogsResult is the serializable outcome of StreamLogs.

type MetricsNodeSample added in v0.8.0

type MetricsNodeSample struct {
	Server  string          `json:"server"`
	Host    string          `json:"host,omitempty"`
	Metrics json.RawMessage `json:"metrics,omitempty"`
	Error   string          `json:"error,omitempty"`
}

MetricsNodeSample is one node's metrics read. Metrics carries the takod `/v1/metrics` document verbatim (the monitoring agent's schema, e.g. `cpu_percent`, `memory`, `disk`, `load_average`); it is empty when the read failed and Error says why.

type MetricsResult added in v0.8.0

type MetricsResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	// Server is the --server filter when one was requested.
	Server      string              `json:"server,omitempty"`
	CollectedAt time.Time           `json:"collectedAt"`
	Nodes       []MetricsNodeSample `json:"nodes"`
	Error       string              `json:"error,omitempty"`
}

MetricsResult is the serializable outcome of a single-shot `tako metrics`. All nodes failing exits 1; a partial read exits 6; live mode is interactive-only and never emits this document.

type Options

type Options struct {
	// CLIVersion and CLICommit stamp deployment state records.
	CLIVersion string
	CLICommit  string
	// Sink receives the operation event stream. Nil discards events.
	Sink events.Sink
	// StateAutoSync optionally refreshes local deployment state from the
	// remote mesh before planning; errors are non-fatal.
	StateAutoSync StateAutoSyncFunc
	// BuildOutput redirects deployer build/progress output. Nil keeps the
	// deployer's default (stdout); machine-output modes route this to
	// stderr so stdout stays parseable.
	BuildOutput io.Writer
}

Options configures an Engine.

type PlacementApplyRequest added in v0.10.0

type PlacementApplyRequest struct {
	Config      *config.Config
	Environment string
	Plan        scheduler.MovementPlan
	PlanID      string
	Verbose     bool
}

type PlacementApplyResult added in v0.10.0

type PlacementApplyResult struct {
	APIVersion  string    `json:"apiVersion"`
	Kind        string    `json:"kind"`
	Project     string    `json:"project"`
	Environment string    `json:"environment"`
	PlanID      string    `json:"planId"`
	Moves       int       `json:"moves"`
	Status      string    `json:"status"`
	CompletedAt time.Time `json:"completedAt"`
}

type PlacementPlanRequest added in v0.10.0

type PlacementPlanRequest struct {
	Config      *config.Config
	Environment string
	Mode        string
	TargetNode  string
}

type PlanChange

type PlanChange struct {
	Type    string   `json:"type"`
	Service string   `json:"service"`
	Reasons []string `json:"reasons,omitempty"`
	// ReleaseCommand surfaces the service's deploy.release command that
	// will run before cutover when this change applies.
	ReleaseCommand []string `json:"releaseCommand,omitempty"`
	RunCommand     []string `json:"runCommand,omitempty"`
}

PlanChange is one service-level change in a deployment plan.

type PlanSharedBuild added in v0.9.0

type PlanSharedBuild struct {
	Key       string   `json:"key"`
	Image     string   `json:"image"`
	Consumers []string `json:"consumers"`
}

type PromoteRequest

type PromoteRequest struct {
	Config      *config.Config
	Environment string
	// ServiceName is the positional SERVICE argument.
	ServiceName string
	// Revision is the --revision flag: a full warmed revision ID or a unique
	// prefix. Empty selects the single warmed revision.
	Revision string
	Verbose  bool
	// ShortRevision formats revision IDs for display in the final success
	// message. The cmd layer injects its shared shortRevision helper (also
	// used by `tako ps`, so it stays in cmd); nil leaves revisions unshortened.
	ShortRevision func(string) string
}

PromoteRequest describes one manual blue-green promotion. Config must be loaded and validated; Environment must be resolved.

type PromoteResult

type PromoteResult struct {
	APIVersion  string                   `json:"apiVersion"`
	Kind        string                   `json:"kind"`
	Project     string                   `json:"project"`
	Environment string                   `json:"environment"`
	Service     string                   `json:"service"`
	Revision    string                   `json:"revision"`
	Image       string                   `json:"image,omitempty"`
	Status      takoapi.DeploymentStatus `json:"status"`
	StartedAt   time.Time                `json:"startedAt"`
	Duration    float64                  `json:"durationSeconds"`
}

PromoteResult is the serializable outcome of Promote.

type ProxyHashPasswordResult added in v0.8.1

type ProxyHashPasswordResult struct {
	APIVersion string `json:"apiVersion"`
	Kind       string `json:"kind"`
	Cost       int    `json:"cost"`
	Hash       string `json:"hash"`
}

ProxyHashPasswordResult carries the bcrypt hash minted for proxy.basicAuth.passwordBcrypt. The plaintext password is never included.

type ProxyReconciler

type ProxyReconciler interface {
	ReconcileTakodProxyWithActiveRevisions(services map[string]config.ServiceConfig, activeRevisions map[string]string) error
	ReconcileTakodProxy(services map[string]config.ServiceConfig) error
}

ProxyReconciler reconciles proxy routes for services.

type ReleaseOutcome added in v0.8.0

type ReleaseOutcome struct {
	Command    []string `json:"command"`
	Server     string   `json:"server,omitempty"`
	Image      string   `json:"image,omitempty"`
	ExitCode   int      `json:"exitCode"`
	DurationMs int64    `json:"durationMs"`
}

ReleaseOutcome reports the service's release command run: executed once per applied deploy from the new image, before traffic cutover.

type RemoteDeploymentContextSaver

type RemoteDeploymentContextSaver interface {
	SaveDeploymentContext(context.Context, *remotestate.DeploymentState) error
}

RemoteDeploymentContextSaver persists deployment records to remote state with cancellation.

type RemoteDeploymentSaver

type RemoteDeploymentSaver interface {
	SaveDeployment(*remotestate.DeploymentState) error
}

RemoteDeploymentSaver persists deployment records to remote state.

type RemoteExitError added in v0.8.0

type RemoteExitError struct {
	Code int
}

RemoteExitError carries a remote command's non-zero exit code so the CLI process can mirror it in human mode.

func (*RemoteExitError) Error added in v0.8.0

func (e *RemoteExitError) Error() string

type RemoteLease

type RemoteLease struct {
	ServerName string
	Manager    RemoteLeaseManager
	Lease      *remotestate.LeaseInfo
}

RemoteLease is one acquired lease on one node.

type RemoteLeaseAcquireContextFunc

type RemoteLeaseAcquireContextFunc func(ctx context.Context, serverName string, server config.ServerConfig) (RemoteLease, error)

RemoteLeaseAcquireContextFunc acquires one node's lease with cancellation.

type RemoteLeaseAcquireFunc

type RemoteLeaseAcquireFunc func(serverName string, server config.ServerConfig) (RemoteLease, error)

RemoteLeaseAcquireFunc acquires one node's lease.

type RemoteLeaseContextManager

type RemoteLeaseContextManager interface {
	ReleaseLeaseContext(context.Context, *remotestate.LeaseInfo) error
}

RemoteLeaseContextManager releases remote operation leases with cancellation.

type RemoteLeaseManager

type RemoteLeaseManager interface {
	ReleaseLease(*remotestate.LeaseInfo) error
}

RemoteLeaseManager releases remote operation leases.

type RemoteLeaseRenewContextManager added in v0.9.0

type RemoteLeaseRenewContextManager interface {
	RenewLeaseContext(context.Context, *remotestate.LeaseInfo, time.Duration) (*remotestate.LeaseInfo, error)
}

RemoteLeaseRenewContextManager renews a remote lease using its existing ID holder token. StateManager implements this optional interface.

type RemoteLeaseSet

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

RemoteLeaseSet holds the leases acquired for one operation across nodes.

func AcquireRemoteOperationLeases

func AcquireRemoteOperationLeases(pool *ssh.Pool, cfg *config.Config, envName string, serverNames []string, operation string) (*RemoteLeaseSet, error)

AcquireRemoteOperationLeases acquires the per-node operation leases that serialize mutations for one app/stage across the target mesh nodes.

func AcquireRemoteOperationLeasesContext

func AcquireRemoteOperationLeasesContext(ctx context.Context, pool *ssh.Pool, cfg *config.Config, envName string, serverNames []string, operation string) (*RemoteLeaseSet, error)

AcquireRemoteOperationLeasesContext acquires the per-node operation leases and returns promptly when ctx is cancelled. In-flight SSH/takod calls may not be interruptible, so leases acquired after cancellation are released by a best-effort cleanup path.

func AcquireRemoteOperationLeasesWith

func AcquireRemoteOperationLeasesWith(servers map[string]config.ServerConfig, serverNames []string, operation string, acquire RemoteLeaseAcquireFunc) (*RemoteLeaseSet, error)

AcquireRemoteOperationLeasesWith fans lease acquisition out across nodes, releasing every acquired lease when any node fails.

func AcquireRemoteOperationLeasesWithContext

func AcquireRemoteOperationLeasesWithContext(ctx context.Context, servers map[string]config.ServerConfig, serverNames []string, operation string, acquire RemoteLeaseAcquireContextFunc) (*RemoteLeaseSet, error)

AcquireRemoteOperationLeasesWithContext fans lease acquisition out across nodes, returns on context cancellation, and releases every acquired lease when any node fails or cancellation wins the fan-out race.

func NewRemoteLeaseSet

func NewRemoteLeaseSet(operation string, leases []RemoteLease) *RemoteLeaseSet

NewRemoteLeaseSet assembles a lease set from already-acquired leases; used by callers that stub lease acquisition.

func (*RemoteLeaseSet) BindContext added in v0.9.0

func (s *RemoteLeaseSet) BindContext(parent context.Context) (context.Context, context.CancelFunc)

BindContext returns a child canceled when lease ownership is lost or the set is released. Callers must invoke the returned cancel function.

func (*RemoteLeaseSet) Err added in v0.9.0

func (s *RemoteLeaseSet) Err() error

Err returns the terminal renewal error, if continued ownership could no longer be proven.

func (*RemoteLeaseSet) OperationFence added in v0.10.0

func (s *RemoteLeaseSet) OperationFence() *nodeidentity.OperationFence

OperationFence returns the latest controller-renewed fence for request headers. It satisfies takodclient.OperationFenceSource.

func (*RemoteLeaseSet) OperationHolderToken added in v0.10.0

func (s *RemoteLeaseSet) OperationHolderToken() string

func (*RemoteLeaseSet) Release

func (s *RemoteLeaseSet) Release()

Release releases held leases in reverse order. Failures route to the warning consumer; release is best-effort by design.

func (*RemoteLeaseSet) SetWarnFunc

func (s *RemoteLeaseSet) SetWarnFunc(warn func(message string))

SetWarnFunc routes non-fatal lease release failures to a warning consumer.

func (*RemoteLeaseSet) Summary

func (s *RemoteLeaseSet) Summary() string

Summary lists the held leases as "server:leaseID" pairs.

type RemoveRequest

type RemoveRequest struct {
	Config      *config.Config `json:"-"`
	Environment string         `json:"environment"`
	// Servers optionally scopes removal to the named environment servers
	// (the --server flag). Empty targets every environment server.
	Servers []string `json:"servers,omitempty"`
	Verbose bool     `json:"verbose,omitempty"`
}

RemoveRequest describes one remove operation: tear down this project's services on the environment mesh while preserving server setup. Config must be loaded and validated; Environment must be resolved.

type RemoveResult

type RemoveResult struct {
	APIVersion  string                `json:"apiVersion"`
	Kind        string                `json:"kind"`
	Project     string                `json:"project"`
	Environment string                `json:"environment"`
	Scoped      bool                  `json:"scoped,omitempty"`
	Servers     []RemoveServerOutcome `json:"servers"`
	StartedAt   time.Time             `json:"startedAt"`
	Duration    float64               `json:"durationSeconds"`
	Message     string                `json:"message,omitempty"`
	Error       string                `json:"error,omitempty"`
}

RemoveResult is the serializable outcome of RemoveSession.Apply.

type RemoveServerOutcome

type RemoveServerOutcome struct {
	Name    string `json:"name"`
	Host    string `json:"host,omitempty"`
	Removed bool   `json:"removed"`
	Error   string `json:"error,omitempty"`
}

RemoveServerOutcome reports what happened on one node during remove.

type RemoveSession

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

RemoveSession carries an in-flight remove between Plan and Apply. Plan validates targets and announces what removal will do; the caller gates the confirmation prompt and calls Apply to execute.

func (*RemoveSession) Apply

func (s *RemoveSession) Apply(ctx context.Context) (*RemoveResult, error)

Apply executes the planned remove. The caller gates confirmation.

func (*RemoveSession) Close

func (s *RemoveSession) Close()

Close releases the session. Remove acquires its remote resources inside Apply, so Close only invalidates the session. Idempotent.

func (*RemoveSession) Environment

func (s *RemoveSession) Environment() string

Environment returns the resolved target environment.

func (*RemoveSession) ProjectName

func (s *RemoveSession) ProjectName() string

ProjectName exposes the project name the confirmation prompt asks for.

func (*RemoveSession) ServerNames

func (s *RemoveSession) ServerNames() []string

ServerNames returns the environment servers removal targets.

type RevisionPruner

type RevisionPruner interface {
	PruneTakodServiceRevisions(services map[string]config.ServiceConfig, keepRevisions map[string]string) error
}

RevisionPruner prunes stale service revisions.

type RollbackHistorySourceFunc

type RollbackHistorySourceFunc func() (source string, history *remotestate.DeploymentHistory, err error)

RollbackHistorySourceFunc selects the freshest reachable deployment history from the mesh, returning the source node name and its history document. The cmd layer supplies it because the shared mesh-history collection helpers (collectStateDeploymentHistories, bestDeploymentHistory) live in cmd.

type RollbackRequest

type RollbackRequest struct {
	Config      *config.Config
	Environment string
	// Service is the --service flag (required).
	Service string
	// DeploymentID is the optional positional deployment-id argument; empty
	// rolls back to the previous stable deployment for the service.
	DeploymentID string
	Verbose      bool

	// HistorySource and ListDeployments are seams for history helpers shared
	// with other cmd files; see the type docs.
	HistorySource   RollbackHistorySourceFunc
	ListDeployments ListDeploymentsFunc
}

RollbackRequest describes one rollback operation. Config must be loaded and validated; Environment must be resolved.

type RollbackResult

type RollbackResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Service     string `json:"service"`
	// DeploymentID is the target deployment the service was rolled back to.
	DeploymentID string                   `json:"deploymentId"`
	Version      string                   `json:"version,omitempty"`
	Status       takoapi.DeploymentStatus `json:"status"`
	StartedAt    time.Time                `json:"startedAt"`
	Duration     float64                  `json:"durationSeconds"`
	Message      string                   `json:"message,omitempty"`
}

RollbackResult is the serializable outcome of Rollback.

type RunOutcome added in v0.9.0

type RunOutcome struct {
	Command    []string `json:"command"`
	Server     string   `json:"server"`
	Image      string   `json:"image"`
	ExitCode   int      `json:"exitCode"`
	DurationMs int64    `json:"durationMs"`
}

type RunRequest

type RunRequest struct {
	// Config is the synthesized, validated configuration.
	Config      *config.Config
	Environment string
	ServiceName string
	Service     config.ServiceConfig
	ImageRef    string
	// ServerName is the generated config server key; ServerDisplay is the
	// operator-facing SSH host used in progress messages.
	ServerName    string
	ServerDisplay string
	EnvVars       map[string]string
	Verbose       bool
}

RunRequest deploys one public image to one existing takod node using a synthesized single-service config (the configless `tako run` path).

type RunSession

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

RunSession carries an in-flight configless run between Plan and Apply.

func (*RunSession) Apply

func (s *RunSession) Apply(ctx context.Context) (*DeployResult, error)

Apply executes the planned configless run. The caller gates confirmation.

func (*RunSession) Close

func (s *RunSession) Close()

Close releases leases and SSH connections. Idempotent.

func (*RunSession) NeedsConfirmation

func (s *RunSession) NeedsConfirmation() bool

NeedsConfirmation reports whether the plan mutates an existing service.

func (*RunSession) Plan

func (s *RunSession) Plan() DeployPlan

Plan returns the serializable plan document.

type SSHClientProvider

type SSHClientProvider interface {
	GetOrCreateWithAuth(host string, port int, user string, keyPath string, password string) (*ssh.Client, error)
}

SSHClientProvider supplies pooled SSH clients; *ssh.Pool implements it.

type ScaleRequest

type ScaleRequest struct {
	Config      *config.Config
	Environment string
	// Targets maps service name to the desired replica count, as parsed from
	// SERVICE=REPLICAS arguments (see ParseScaleTargets).
	Targets map[string]int
	// Verbose enables detailed progress from the deployer and state
	// replicator; debug-level events are emitted regardless and filtered by
	// renderers.
	Verbose bool
}

ScaleRequest describes one scale operation. Config must be loaded and validated; Environment must be resolved.

type ScaleResult

type ScaleResult struct {
	APIVersion  string                   `json:"apiVersion"`
	Kind        string                   `json:"kind"`
	Project     string                   `json:"project"`
	Environment string                   `json:"environment"`
	Status      takoapi.DeploymentStatus `json:"status"`
	Services    []ServiceOutcome         `json:"services"`
	StartedAt   time.Time                `json:"startedAt"`
	Duration    float64                  `json:"durationSeconds"`
	Message     string                   `json:"message,omitempty"`
	Error       string                   `json:"error,omitempty"`
}

ScaleResult is the serializable outcome of Scale.

type SecretsListResult added in v0.8.0

type SecretsListResult struct {
	APIVersion string `json:"apiVersion"`
	Kind       string `json:"kind"`
	// Environment is the --env filter; empty means all environments.
	Environment string   `json:"environment,omitempty"`
	Keys        []string `json:"keys"`
	Count       int      `json:"count"`
}

SecretsListResult is the serializable outcome of `tako secrets list`. It carries secret KEYS only — values never appear in any machine output (test-enforced alongside the event redaction tests).

type SecretsValidateResult added in v0.8.0

type SecretsValidateResult struct {
	APIVersion  string   `json:"apiVersion"`
	Kind        string   `json:"kind"`
	Project     string   `json:"project,omitempty"`
	Environment string   `json:"environment,omitempty"`
	Valid       bool     `json:"valid"`
	Required    []string `json:"required"`
	Missing     []string `json:"missing,omitempty"`
}

SecretsValidateResult is the serializable outcome of `tako secrets validate`: whether every secret referenced by the environment's services is configured. Names only — never values.

type ServiceOutcome

type ServiceOutcome struct {
	Name     string          `json:"name"`
	Image    string          `json:"image,omitempty"`
	Action   string          `json:"action"`
	Replicas int             `json:"replicas,omitempty"`
	Release  *ReleaseOutcome `json:"release,omitempty"`
	Run      *RunOutcome     `json:"run,omitempty"`
	Error    string          `json:"error,omitempty"`
}

ServiceOutcome reports what happened to one service during apply.

type ServiceRemover

type ServiceRemover interface {
	RemoveServiceTakod(serviceName string) error
}

ServiceRemover removes services from the runtime during reconciliation.

type SetupHostKey added in v0.8.0

type SetupHostKey struct {
	Type        string `json:"type"`
	Key         string `json:"key"`
	Fingerprint string `json:"fingerprint"`
}

SetupHostKey is the SSH host key recorded for the node during setup so callers can pin it (feeds --host-key-mode strict). Key is the base64-encoded public key; Fingerprint is its SHA256 form.

type SetupNodeResult added in v0.8.0

type SetupNodeResult struct {
	Server        string             `json:"server"`
	Host          string             `json:"host,omitempty"`
	Mode          string             `json:"mode,omitempty"`
	OS            string             `json:"os,omitempty"`
	DockerVersion string             `json:"dockerVersion,omitempty"`
	TakodVersion  string             `json:"takodVersion,omitempty"`
	SetupVersion  string             `json:"setupVersion,omitempty"`
	FirewallPorts []string           `json:"firewallPorts,omitempty"`
	HostKey       *SetupHostKey      `json:"hostKey,omitempty"`
	Steps         []SetupStepOutcome `json:"steps,omitempty"`
	Error         string             `json:"error,omitempty"`
}

SetupNodeResult reports one node's provisioning outcome, including the facts a control plane needs to adopt the node: detected OS, installed docker/takod versions, firewall allowances, and the recorded host key.

type SetupResult added in v0.8.0

type SetupResult struct {
	APIVersion  string            `json:"apiVersion"`
	Kind        string            `json:"kind"`
	Project     string            `json:"project"`
	Environment string            `json:"environment"`
	Nodes       []SetupNodeResult `json:"nodes"`
	Error       string            `json:"error,omitempty"`
}

SetupResult is the serializable outcome of `tako setup`. Setup aborts on the first failing node, so Nodes lists only the nodes attempted.

type SetupStepOutcome added in v0.8.0

type SetupStepOutcome struct {
	Step   string `json:"step"`
	Title  string `json:"title"`
	Status string `json:"status"`
	Error  string `json:"error,omitempty"`
}

SetupStepOutcome reports one provisioning step on one node.

type SourceInfo

type SourceInfo struct {
	CommitInfo    *git.CommitInfo
	DirtyStatus   string
	BuildImageTag string
	StateSource   string
	SourceMode    bool
}

SourceInfo describes the source identity of a deployment: either a git commit or an explicit source/revision label.

func ResolveSourceInfo

func ResolveSourceInfo(gitClient GitReader, allowDirty bool, source string, revision string, imageRef string, now time.Time) (SourceInfo, error)

ResolveSourceInfo determines deployment source identity. Default mode requires git; source mode skips git validation.

type StateAutoSyncFunc

type StateAutoSyncFunc func(pool *ssh.Pool, cfg *config.Config, envName string) error

StateAutoSyncFunc refreshes local deployment state from the remote mesh before planning. Errors are non-fatal by contract.

type StateForgetNodeNode

type StateForgetNodeNode struct {
	Name    string                        `json:"name"`
	Runtime StateForgetNodeRuntimeManager `json:"-"`
}

StateForgetNodeNode is one already-collected reachable node. The CLI builds these from the state-repair inventory seam so the engine does not own the broader repair inventory flow.

type StateForgetNodeNodeResult

type StateForgetNodeNodeResult struct {
	Name              string   `json:"name"`
	NodeActualExisted bool     `json:"nodeActualExisted"`
	AggregatePruned   bool     `json:"aggregatePruned"`
	Warnings          []string `json:"warnings,omitempty"`
	Error             string   `json:"error,omitempty"`

	Err error `json:"-"`
}

StateForgetNodeNodeResult is one node's cleanup outcome.

func ForgetNodeFromRuntimeNodes

func ForgetNodeFromRuntimeNodes(nodes []StateForgetNodeNode, project string, envName string, nodeName string) ([]StateForgetNodeNodeResult, error)

ForgetNodeFromRuntimeNodes removes nodeName from already-collected runtime managers.

func ForgetNodeFromRuntimeNodesContext

func ForgetNodeFromRuntimeNodesContext(ctx context.Context, nodes []StateForgetNodeNode, project string, envName string, nodeName string) ([]StateForgetNodeNodeResult, error)

ForgetNodeFromRuntimeNodesContext removes nodeName from already-collected runtime managers bounded by ctx.

func ForgetNodeOnRuntimeNode

func ForgetNodeOnRuntimeNode(ctx context.Context, node StateForgetNodeNode, project string, envName string, nodeName string) StateForgetNodeNodeResult

ForgetNodeOnRuntimeNode removes nodeName from one runtime manager.

type StateForgetNodeRequest

type StateForgetNodeRequest struct {
	Config      *config.Config        `json:"-"`
	Environment string                `json:"environment"`
	Server      string                `json:"server,omitempty"`
	NodeName    string                `json:"node"`
	Force       bool                  `json:"force,omitempty"`
	Nodes       []StateForgetNodeNode `json:"-"`
}

StateForgetNodeRequest describes one runtime-state cleanup operation.

type StateForgetNodeResult

type StateForgetNodeResult struct {
	APIVersion  string                       `json:"apiVersion"`
	Kind        string                       `json:"kind"`
	Project     string                       `json:"project"`
	Environment string                       `json:"environment"`
	Server      string                       `json:"server,omitempty"`
	Servers     []string                     `json:"servers"`
	RetiredNode string                       `json:"retiredNode"`
	Force       bool                         `json:"force,omitempty"`
	Status      string                       `json:"status"`
	Nodes       []StateForgetNodeNodeResult  `json:"nodes"`
	Summary     StateForgetNodeResultSummary `json:"summary"`
	Warnings    []string                     `json:"warnings,omitempty"`
	Error       string                       `json:"error,omitempty"`
}

StateForgetNodeResult is the serializable outcome of StateForgetNode.

type StateForgetNodeResultSummary

type StateForgetNodeResultSummary struct {
	ReachableNodes              int `json:"reachableNodes"`
	StandaloneSnapshotsFound    int `json:"standaloneSnapshotsFound"`
	AggregateActualStatesPruned int `json:"aggregateActualStatesPruned"`
}

StateForgetNodeResultSummary aggregates per-node cleanup outcomes.

func SummarizeStateForgetNodeResults

func SummarizeStateForgetNodeResults(results []StateForgetNodeNodeResult) StateForgetNodeResultSummary

SummarizeStateForgetNodeResults aggregates per-node cleanup outcomes.

type StateForgetNodeRuntimeManager

type StateForgetNodeRuntimeManager interface {
	ReadActual() (*takodstate.ActualSnapshot, error)
	ReadNodeActual(string) (*takodstate.ActualSnapshot, error)
	WriteActual(*takodstate.ActualSnapshot) error
	DeleteNodeActual(string) error
	AppendEvent(takodstate.Event) error
}

StateForgetNodeRuntimeManager is the runtime-state subset needed to remove a retired node from replicated takod state.

type StateLeaseNodeResult

type StateLeaseNodeResult struct {
	Name  string                 `json:"name"`
	Host  string                 `json:"host,omitempty"`
	Lease *remotestate.LeaseInfo `json:"lease,omitempty"`
	Error string                 `json:"error,omitempty"`

	Manager RemoteLeaseManager `json:"-"`
	Err     error              `json:"-"`
}

StateLeaseNodeResult is one node's current remote lease status.

func CollectStateLeaseNodes

func CollectStateLeaseNodes(ctx context.Context, pool *ssh.Pool, cfg *config.Config, envName string, serverNames []string) ([]StateLeaseNodeResult, error)

CollectStateLeaseNodes reads current leases from serverNames, preserving order.

type StateLeaseReleaseRequest

type StateLeaseReleaseRequest struct {
	Config      *config.Config `json:"-"`
	Environment string         `json:"environment"`
	// Server is the optional requested server filter from --server.
	Server string `json:"server,omitempty"`
	ID     string `json:"id"`
	Force  bool   `json:"force,omitempty"`
	// Now is a test seam. Zero uses time.Now().UTC().
	Now time.Time `json:"-"`
	// SSHPool optionally supplies the SSH pool to use. Nil creates and owns one.
	SSHPool *ssh.Pool `json:"-"`
}

StateLeaseReleaseRequest describes a forced/unlock-style exact-ID lease release.

type StateLeaseReleaseResult

type StateLeaseReleaseResult struct {
	APIVersion    string                 `json:"apiVersion"`
	Kind          string                 `json:"kind"`
	Project       string                 `json:"project"`
	Environment   string                 `json:"environment"`
	Server        string                 `json:"server,omitempty"`
	Servers       []string               `json:"servers"`
	LeaseID       string                 `json:"leaseId"`
	Force         bool                   `json:"force,omitempty"`
	Released      []string               `json:"releasedNodes"`
	ReleasedCount int                    `json:"releasedCount"`
	Nodes         []StateLeaseNodeResult `json:"nodes"`
}

StateLeaseReleaseResult is the serializable outcome of ReleaseStateLease.

type StateLeaseRequest

type StateLeaseRequest struct {
	Config      *config.Config `json:"-"`
	Environment string         `json:"environment"`
	// Server is the optional requested server filter from --server.
	Server string `json:"server,omitempty"`
	// SSHPool optionally supplies the SSH pool to use. Nil creates and owns one.
	SSHPool *ssh.Pool `json:"-"`
}

StateLeaseRequest describes one remote lease inspection operation.

type StateLeaseResult

type StateLeaseResult struct {
	APIVersion  string                 `json:"apiVersion"`
	Kind        string                 `json:"kind"`
	Project     string                 `json:"project"`
	Environment string                 `json:"environment"`
	Server      string                 `json:"server,omitempty"`
	Servers     []string               `json:"servers"`
	Nodes       []StateLeaseNodeResult `json:"nodes"`
}

StateLeaseResult is the serializable outcome of StateLease.

type StatePullHistorySourceFunc

type StatePullHistorySourceFunc func() (source string, history *remotestate.DeploymentHistory, err error)

StatePullHistorySourceFunc supplies the selected deployment history source.

type StatePullLatestDeployment

type StatePullLatestDeployment struct {
	ID        string                       `json:"id"`
	DisplayID string                       `json:"displayId,omitempty"`
	Status    remotestate.DeploymentStatus `json:"status"`
	Timestamp time.Time                    `json:"timestamp"`
	User      string                       `json:"user,omitempty"`
	Commit    string                       `json:"commit,omitempty"`
}

StatePullLatestDeployment is the JSON-friendly latest deployment summary.

type StatePullRecoverFunc

type StatePullRecoverFunc func() (StatePullRecoveryResult, error)

StatePullRecoverFunc attempts one runtime-state recovery path and returns the number of services in the recovered local deployment when available.

type StatePullRecoveryResult

type StatePullRecoveryResult struct {
	ServiceCount int `json:"serviceCount,omitempty"`
}

StatePullRecoveryResult summarizes a successful recovery seam.

type StatePullRequest

type StatePullRequest struct {
	Config      *config.Config `json:"-"`
	Environment string         `json:"environment"`
	// Server is the optional requested server filter from --server.
	Server string `json:"server,omitempty"`

	HistorySource          StatePullHistorySourceFunc   `json:"-"`
	SyncDeployments        StatePullSyncDeploymentsFunc `json:"-"`
	RecoverFromMeshActual  StatePullRecoverFunc         `json:"-"`
	RecoverFromRunningMesh StatePullRecoverFunc         `json:"-"`
}

StatePullRequest describes one state pull orchestration. Config must be loaded and Environment must be resolved by the adapter.

type StatePullResult

type StatePullResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Server      string `json:"server,omitempty"`

	Status       string                     `json:"status"`
	SourceServer string                     `json:"sourceServer,omitempty"`
	SyncedCount  int                        `json:"syncedCount,omitempty"`
	Recovered    *StatePullRecoveryResult   `json:"recovered,omitempty"`
	Latest       *StatePullLatestDeployment `json:"latestDeployment,omitempty"`

	Warnings         []string `json:"warnings,omitempty"`
	MeshActualError  string   `json:"meshActualError,omitempty"`
	RunningMeshError string   `json:"runningMeshError,omitempty"`
}

StatePullResult is the serializable outcome of StatePull.

type StatePullSyncDeploymentsFunc

type StatePullSyncDeploymentsFunc func([]*remotestate.DeploymentState) (int, error)

StatePullSyncDeploymentsFunc persists remote deployment records locally.

type StateRepairActualCandidate

type StateRepairActualCandidate struct {
	Source string
	Actual *takodstate.ActualSnapshot
}

StateRepairActualCandidate is an adapter-collected aggregate actual runtime candidate.

type StateRepairActualSource

type StateRepairActualSource struct {
	Source       string    `json:"source"`
	ServiceCount int       `json:"serviceCount"`
	Freshness    time.Time `json:"freshness"`
}

type StateRepairBeforeWriteFunc

type StateRepairBeforeWriteFunc func(context.Context, *StateRepairResult) error

StateRepairBeforeWriteFunc is called after source selection and before any repair document writes. CLI adapters use this seam to render selected sources and acquire/release leases without making the engine own those protocols.

type StateRepairCounts

type StateRepairCounts struct {
	ReachableNodes int `json:"reachableNodes"`
}

StateRepairCounts summarizes node reachability for repair.

type StateRepairDesiredCandidate

type StateRepairDesiredCandidate struct {
	Source  string
	Desired *takodstate.DesiredRevision
}

StateRepairDesiredCandidate is an adapter-collected desired runtime candidate.

type StateRepairDesiredSource

type StateRepairDesiredSource struct {
	Source     string    `json:"source"`
	RevisionID string    `json:"revisionId"`
	Freshness  time.Time `json:"freshness"`
}

type StateRepairHistoryCandidate

type StateRepairHistoryCandidate struct {
	Source  string
	History *remotestate.DeploymentHistory
}

StateRepairHistoryCandidate is an adapter-collected deployment-history candidate.

type StateRepairHistoryManager

type StateRepairHistoryManager interface {
	SaveHistory(*remotestate.DeploymentHistory) error
}

StateRepairHistoryManager is the deployment-history write subset needed by state repair.

type StateRepairHistorySource

type StateRepairHistorySource struct {
	Source    string    `json:"source"`
	Count     int       `json:"count"`
	Freshness time.Time `json:"freshness"`
}

type StateRepairLocalSync

type StateRepairLocalSync struct {
	Status string `json:"status"`
	Count  int    `json:"count,omitempty"`
	Error  string `json:"error,omitempty"`
}

StateRepairLocalSync summarizes the optional local .tako refresh performed by adapters.

type StateRepairNode

type StateRepairNode struct {
	Name           string                    `json:"name"`
	HistoryManager StateRepairHistoryManager `json:"-"`
	Runtime        StateRepairRuntimeManager `json:"-"`
}

StateRepairNode is one already-collected reachable node. Adapters own SSH dialing, inventory collection, and lease handling.

type StateRepairNodeActualCandidate

type StateRepairNodeActualCandidate struct {
	Source string
	Node   string
	Actual *takodstate.ActualSnapshot
}

StateRepairNodeActualCandidate is an adapter-collected per-node actual runtime candidate.

type StateRepairNodeActualSource

type StateRepairNodeActualSource struct {
	Node         string    `json:"node"`
	Source       string    `json:"source"`
	ServiceCount int       `json:"serviceCount"`
	Freshness    time.Time `json:"freshness"`
}

type StateRepairNodeWriteResult

type StateRepairNodeWriteResult struct {
	Name     string                 `json:"name"`
	Counts   StateRepairWriteCounts `json:"counts"`
	Warnings []string               `json:"warnings,omitempty"`
	Error    string                 `json:"error,omitempty"`

	Err error `json:"-"`
}

StateRepairNodeWriteResult summarizes writes attempted on one reachable node.

type StateRepairRequest

type StateRepairRequest struct {
	Config      *config.Config `json:"-"`
	Environment string         `json:"environment"`
	Server      string         `json:"server,omitempty"`

	Nodes      []StateRepairNode                `json:"-"`
	Histories  []StateRepairHistoryCandidate    `json:"-"`
	Desired    []StateRepairDesiredCandidate    `json:"-"`
	Actual     []StateRepairActualCandidate     `json:"-"`
	NodeActual []StateRepairNodeActualCandidate `json:"-"`

	BeforeWrite StateRepairBeforeWriteFunc `json:"-"`
}

StateRepairRequest describes one state repair operation over already-collected state.

type StateRepairResult

type StateRepairResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Server      string `json:"server,omitempty"`
	Status      string `json:"status"`

	Servers []string               `json:"servers"`
	Counts  StateRepairCounts      `json:"counts"`
	Sources StateRepairSources     `json:"selectedSources"`
	Writes  StateRepairWriteResult `json:"writes"`
	Local   StateRepairLocalSync   `json:"localSync"`

	Warnings []string `json:"warnings,omitempty"`
	Error    string   `json:"error,omitempty"`

	SelectedHistory *remotestate.DeploymentHistory `json:"-"`
}

StateRepairResult is the machine-readable outcome of state repair.

type StateRepairRuntimeManager

type StateRepairRuntimeManager interface {
	WriteDesired(*takodstate.DesiredRevision) error
	ReadActual() (*takodstate.ActualSnapshot, error)
	WriteActual(*takodstate.ActualSnapshot) error
	WriteNodeActual(string, *takodstate.ActualSnapshot) error
	DeleteNodeActual(string) error
}

StateRepairRuntimeManager is the runtime-state write subset needed by state repair.

type StateRepairSources

type StateRepairSources struct {
	HasHistory    bool                          `json:"hasHistory"`
	HasDesired    bool                          `json:"hasDesired"`
	HasActual     bool                          `json:"hasActual"`
	HasNodeActual bool                          `json:"hasNodeActual"`
	History       *StateRepairHistorySource     `json:"history,omitempty"`
	Desired       *StateRepairDesiredSource     `json:"desired,omitempty"`
	Actual        *StateRepairActualSource      `json:"actual,omitempty"`
	NodeActual    []StateRepairNodeActualSource `json:"nodeActual,omitempty"`
}

StateRepairSources summarizes the selected repair source documents.

type StateRepairWriteCounts

type StateRepairWriteCounts struct {
	History    int `json:"history"`
	Desired    int `json:"desired"`
	Actual     int `json:"actual"`
	NodeActual int `json:"nodeActual"`
}

StateRepairWriteCounts aggregates writes by document type.

func SummarizeStateRepairWriteCounts

func SummarizeStateRepairWriteCounts(results []StateRepairNodeWriteResult) StateRepairWriteCounts

SummarizeStateRepairWriteCounts aggregates per-node write counts.

type StateRepairWriteResult

type StateRepairWriteResult struct {
	Counts StateRepairWriteCounts       `json:"counts"`
	Nodes  []StateRepairNodeWriteResult `json:"nodes"`
}

StateRepairWriteResult summarizes all remote document writes.

type StateStatusActualSummary

type StateStatusActualSummary struct {
	Recorded        bool      `json:"recorded"`
	ServiceCount    int       `json:"serviceCount,omitempty"`
	Freshness       time.Time `json:"freshness,omitempty"`
	NodeActualCount int       `json:"nodeActualCount,omitempty"`
	Error           string    `json:"error,omitempty"`
}

type StateStatusAgentSummary

type StateStatusAgentSummary struct {
	Runtime   string    `json:"runtime,omitempty"`
	Version   string    `json:"version,omitempty"`
	Hostname  string    `json:"hostname,omitempty"`
	Socket    string    `json:"socket,omitempty"`
	DataDir   string    `json:"dataDir,omitempty"`
	StartedAt time.Time `json:"startedAt,omitempty"`
	Now       time.Time `json:"now,omitempty"`
	Error     string    `json:"error,omitempty"`
}

StateStatusAgentSummary is a JSON-friendly takod agent status.

type StateStatusBestActual

type StateStatusBestActual struct {
	Source       string    `json:"source"`
	ServiceCount int       `json:"serviceCount"`
	Freshness    time.Time `json:"freshness"`
}

type StateStatusBestDesired

type StateStatusBestDesired struct {
	Source     string    `json:"source"`
	RevisionID string    `json:"revisionId"`
	Freshness  time.Time `json:"freshness"`
}

type StateStatusBestHistory

type StateStatusBestHistory struct {
	Source    string                       `json:"source"`
	Count     int                          `json:"count"`
	Freshness time.Time                    `json:"freshness"`
	Latest    *StateStatusRemoteDeployment `json:"latest,omitempty"`
}

type StateStatusBestKnown

type StateStatusBestKnown struct {
	History    *StateStatusBestHistory     `json:"history,omitempty"`
	Desired    *StateStatusBestDesired     `json:"desired,omitempty"`
	Actual     *StateStatusBestActual      `json:"actual,omitempty"`
	NodeActual []StateStatusBestNodeActual `json:"nodeActual,omitempty"`
}

type StateStatusBestNodeActual

type StateStatusBestNodeActual struct {
	Node      string    `json:"node"`
	Source    string    `json:"source"`
	Freshness time.Time `json:"freshness"`
}

type StateStatusCounts

type StateStatusCounts struct {
	ConfiguredNodes    int `json:"configuredNodes"`
	ReachableNodes     int `json:"reachableNodes"`
	UnreachableNodes   int `json:"unreachableNodes"`
	RemoteHistoryNodes int `json:"remoteHistoryNodes"`
	DesiredNodes       int `json:"desiredNodes"`
	ActualNodes        int `json:"actualNodes"`
}

type StateStatusDesiredSummary

type StateStatusDesiredSummary struct {
	Recorded     bool      `json:"recorded"`
	RevisionID   string    `json:"revisionId,omitempty"`
	ServiceCount int       `json:"serviceCount,omitempty"`
	Freshness    time.Time `json:"freshness,omitempty"`
	Error        string    `json:"error,omitempty"`
}

type StateStatusHistoryCandidate

type StateStatusHistoryCandidate struct {
	Source  string
	History *remotestate.DeploymentHistory
}

StateStatusHistoryCandidate is a candidate remote deployment history source.

type StateStatusHistorySummary

type StateStatusHistorySummary struct {
	Recorded  bool                         `json:"recorded"`
	Missing   bool                         `json:"missing,omitempty"`
	Count     int                          `json:"count,omitempty"`
	Freshness time.Time                    `json:"freshness,omitempty"`
	Latest    *StateStatusRemoteDeployment `json:"latest,omitempty"`
	Error     string                       `json:"error,omitempty"`
}

type StateStatusLeaseSummary

type StateStatusLeaseSummary struct {
	Status string                 `json:"status"`
	Lease  *remotestate.LeaseInfo `json:"lease,omitempty"`
	Error  string                 `json:"error,omitempty"`
}

type StateStatusLocalDeployment

type StateStatusLocalDeployment struct {
	ID        string    `json:"id"`
	Timestamp time.Time `json:"timestamp"`
	Status    string    `json:"status,omitempty"`
	Commit    string    `json:"commit,omitempty"`
}

type StateStatusLocalInput

type StateStatusLocalInput struct {
	Path    string                      `json:"path,omitempty"`
	Exists  bool                        `json:"exists"`
	Current *localstate.DeploymentState `json:"-"`
	Error   string                      `json:"error,omitempty"`
}

StateStatusLocalInput is the adapter-provided local .tako state summary.

type StateStatusLocalSummary

type StateStatusLocalSummary struct {
	Path           string                      `json:"path"`
	Exists         bool                        `json:"exists"`
	Status         string                      `json:"status"`
	Error          string                      `json:"error,omitempty"`
	LastDeployment *StateStatusLocalDeployment `json:"lastDeployment,omitempty"`
}

type StateStatusMeshSummary

type StateStatusMeshSummary struct {
	Interface  string `json:"interface,omitempty"`
	Up         bool   `json:"up"`
	ListenPort string `json:"listenPort,omitempty"`
	Peers      int    `json:"peers"`
	PublicKey  string `json:"publicKey,omitempty"`
	Error      string `json:"error,omitempty"`
}

StateStatusMeshSummary is a JSON-friendly WireGuard mesh status.

type StateStatusNodeActualCandidate

type StateStatusNodeActualCandidate struct {
	Source string
	Node   string
	Actual *takodstate.ActualSnapshot
}

StateStatusNodeActualCandidate is a candidate per-node actual state source.

type StateStatusNodeResult

type StateStatusNodeResult struct {
	Name      string `json:"name"`
	Host      string `json:"host,omitempty"`
	Status    string `json:"status"`
	Reachable bool   `json:"reachable"`
	Error     string `json:"error,omitempty"`

	Agent   *StateStatusAgentSummary  `json:"agent,omitempty"`
	Mesh    *StateStatusMeshSummary   `json:"mesh,omitempty"`
	History StateStatusHistorySummary `json:"history"`
	Desired StateStatusDesiredSummary `json:"desired"`
	Actual  StateStatusActualSummary  `json:"actual"`
	Lease   StateStatusLeaseSummary   `json:"lease"`
}

type StateStatusRemoteDeployment

type StateStatusRemoteDeployment struct {
	ID        string                       `json:"id"`
	DisplayID string                       `json:"displayId,omitempty"`
	Status    remotestate.DeploymentStatus `json:"status,omitempty"`
	Timestamp time.Time                    `json:"timestamp"`
	User      string                       `json:"user,omitempty"`
	Commit    string                       `json:"commit,omitempty"`
}

type StateStatusRemoteNodeInput

type StateStatusRemoteNodeInput struct {
	Name       string
	Host       string
	EnvNodes   []string
	ConnectErr error

	History    *remotestate.DeploymentHistory
	HistoryErr error
	Desired    *takodstate.DesiredRevision
	DesiredErr error
	Actual     *takodstate.ActualSnapshot
	ActualErr  error
	NodeActual []StateStatusNodeActualCandidate

	Agent    *StateStatusAgentSummary
	AgentErr error
	Mesh     *StateStatusMeshSummary
	MeshErr  error
	Lease    *remotestate.LeaseInfo
	LeaseErr error
}

StateStatusRemoteNodeInput is the adapter-provided remote node inventory.

type StateStatusRemoteSummary

type StateStatusRemoteSummary struct {
	Title               string                  `json:"title"`
	Nodes               []StateStatusNodeResult `json:"nodes"`
	UnreachableGuidance []string                `json:"unreachableGuidance,omitempty"`
}

type StateStatusRequest

type StateStatusRequest struct {
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Server      string `json:"server,omitempty"`

	Local StateStatusLocalInput        `json:"-"`
	Nodes []StateStatusRemoteNodeInput `json:"-"`
}

StateStatusRequest describes a state status summarization. Adapters own all I/O and pass already-collected local and remote state into the engine.

type StateStatusResult

type StateStatusResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	Server      string `json:"server,omitempty"`

	Local     StateStatusLocalSummary  `json:"local"`
	Remote    StateStatusRemoteSummary `json:"remote"`
	BestKnown StateStatusBestKnown     `json:"bestKnown"`
	Sync      StateStatusSyncSummary   `json:"sync"`
	Counts    StateStatusCounts        `json:"counts"`
	Error     string                   `json:"error,omitempty"`
}

StateStatusResult is the machine-readable result for `tako state status`.

type StateStatusSyncSummary

type StateStatusSyncSummary struct {
	Recommendations []string `json:"recommendations"`
}

type StatsNodeSample added in v0.8.0

type StatsNodeSample struct {
	Server     string                `json:"server"`
	Host       string                `json:"host,omitempty"`
	Containers []takod.ContainerStat `json:"containers,omitempty"`
	Error      string                `json:"error,omitempty"`
}

StatsNodeSample is one node's point-in-time container stats. Containers reuses the takod stats schema (`name`, `cpuPercent`, `memUsage`, `memPercent`, `netIO`, `blockIO`, `pids`); it is empty when the read failed and Error says why.

type StatsResult added in v0.8.0

type StatsResult struct {
	APIVersion  string `json:"apiVersion"`
	Kind        string `json:"kind"`
	Project     string `json:"project"`
	Environment string `json:"environment"`
	// Service is the --service filter when one was requested; All mirrors
	// --all (include containers beyond this project).
	Service     string            `json:"service,omitempty"`
	All         bool              `json:"all,omitempty"`
	CollectedAt time.Time         `json:"collectedAt"`
	Nodes       []StatsNodeSample `json:"nodes"`
	Error       string            `json:"error,omitempty"`
}

StatsResult is the serializable outcome of a point-in-time `tako stats`. All nodes failing exits 1; a partial read exits 6. `--follow` streams the same node samples as `stats.sample` events instead; `--live` is interactive-only and never emits this document.

type StatusActualStateReadFunc

type StatusActualStateReadFunc func(serverName string, server config.ServerConfig) (map[string]*takod.ActualService, error)

StatusActualStateReadFunc reads actual service state for one server.

type StatusActualStateReadResult

type StatusActualStateReadResult struct {
	Index      int
	ServerName string
	Services   map[string]*takod.ActualService
	Err        error
}

StatusActualStateReadResult captures one node's actual-state read result.

type StatusNodeActualState added in v0.9.1

type StatusNodeActualState struct {
	Server   string
	Services map[string]*takod.ActualService
}

StatusNodeActualState is one node's actual-state read, used for per-node status breakdowns before the mesh-wide merge.

func GatherStatusActualStateByNode added in v0.9.1

func GatherStatusActualStateByNode(ctx context.Context, cfg *config.Config, envName string, serverNames []string) ([]StatusNodeActualState, error)

GatherStatusActualStateByNode reads actual service state from the selected nodes using takod over SSH, preserving per-node attribution.

func GatherStatusActualStateByNodeWith added in v0.9.1

func GatherStatusActualStateByNodeWith(ctx context.Context, servers map[string]config.ServerConfig, serverNames []string, read StatusActualStateReadFunc) ([]StatusNodeActualState, error)

GatherStatusActualStateByNodeWith fans out actual-state reads concurrently and returns per-node responses in selected server order.

type StatusRequest

type StatusRequest struct {
	Config      *config.Config
	Environment string
	Service     string
	Server      string
}

StatusRequest describes one status/ps read operation. Config must be loaded and Environment must be resolved by the adapter.

type StatusResult

type StatusResult struct {
	APIVersion  string          `json:"apiVersion"`
	Kind        string          `json:"kind"`
	Project     string          `json:"project"`
	Environment string          `json:"environment"`
	Server      string          `json:"server,omitempty"`
	Servers     []string        `json:"servers"`
	Service     string          `json:"service,omitempty"`
	Services    []StatusService `json:"services"`
}

StatusResult is the serializable outcome of Status.

type StatusService

type StatusService struct {
	Name     string `json:"name"`
	Desired  int    `json:"desired"`
	Running  int    `json:"running"`
	Status   string `json:"status"`
	Ports    string `json:"ports"`
	Revision string `json:"revision,omitempty"`
	Warming  int    `json:"warming,omitempty"`
	Internal bool   `json:"internal"`
	// Image is the running image reference; empty when the selected nodes
	// disagree. Strategy is the recorded deploy strategy label.
	Image    string `json:"image,omitempty"`
	Strategy string `json:"strategy,omitempty"`
	// Health aggregates docker health-check state across the service's
	// active containers (worst wins: unhealthy > starting > healthy).
	// Empty when no container defines a health check or the node agent
	// predates health capture.
	Health string `json:"health,omitempty"`
	// Nodes breaks the replica placement down per selected node; nodes not
	// running the service are omitted.
	Nodes []StatusServiceNode `json:"nodes,omitempty"`
	// Job fields: kind is "job" for scheduled jobs, lastRun carries the most
	// recent run's status, nextRun the owning node's next fire time.
	Kind     string     `json:"kind,omitempty"`
	Schedule string     `json:"schedule,omitempty"`
	LastRun  string     `json:"lastRun,omitempty"`
	NextRun  *time.Time `json:"nextRun,omitempty"`
}

StatusService is one service row in the status/ps result.

func BuildStatusServiceInfo

func BuildStatusServiceInfo(
	servers map[string]config.ServerConfig,
	services map[string]config.ServiceConfig,
	actualServices map[string]*takod.ActualService,
	jobStatuses map[string]*takod.JobStatus,
	envServers []string,
	selectedServers []string,
	filterService string,
) ([]StatusService, error)

type StatusServiceNode added in v0.9.1

type StatusServiceNode struct {
	Name    string `json:"name"`
	Running int    `json:"running"`
	Warming int    `json:"warming,omitempty"`
	Health  string `json:"health,omitempty"`
}

StatusServiceNode is one node's share of a service row.

type UpgradeNode added in v0.10.0

type UpgradeNode struct {
	Name  string
	Roles []string
}

type UpgradePlanNode added in v0.10.0

type UpgradePlanNode struct {
	Name  string
	Stage string
}

func PlanNodeUpgrade added in v0.10.0

func PlanNodeUpgrade(nodes []UpgradeNode) ([]UpgradePlanNode, error)

PlanNodeUpgrade returns a deterministic worker-first, controller-last plan. A full enrolled-cluster plan accepts at most one selected controller; targeted worker-only plans contain none. Legacy configs have no platform-owned roles and retain their configured ordering.

type UpgradeServersNodeOutcome added in v0.8.0

type UpgradeServersNodeOutcome struct {
	Server      string `json:"server"`
	Host        string `json:"host,omitempty"`
	FromVersion string `json:"fromVersion,omitempty"`
	ToVersion   string `json:"toVersion,omitempty"`
	Stage       string `json:"stage,omitempty"`
	Protocol    int    `json:"protocol,omitempty"`
	RolledBack  bool   `json:"rolledBack,omitempty"`
	Outcome     string `json:"outcome"`
	Error       string `json:"error,omitempty"`
}

UpgradeServersNodeOutcome reports one node's takod agent upgrade or dry-run assessment.

type UpgradeServersResult added in v0.8.0

type UpgradeServersResult struct {
	APIVersion    string                      `json:"apiVersion"`
	Kind          string                      `json:"kind"`
	Project       string                      `json:"project"`
	Environment   string                      `json:"environment"`
	TargetVersion string                      `json:"targetVersion"`
	DryRun        bool                        `json:"dryRun,omitempty"`
	Nodes         []UpgradeServersNodeOutcome `json:"nodes"`
	Error         string                      `json:"error,omitempty"`
}

UpgradeServersResult is the serializable outcome of `tako upgrade servers`.

type ValidateFinding added in v0.8.0

type ValidateFinding struct {
	Severity string `json:"severity"`
	Path     string `json:"path,omitempty"`
	Field    string `json:"field,omitempty"`
	Message  string `json:"message"`
}

ValidateFinding is one problem found while validating a configuration. Field is the dotted config field when the validator can attribute the problem to one; the schema carries it so attribution can be added without a breaking change.

type ValidateResult added in v0.8.0

type ValidateResult struct {
	APIVersion  string            `json:"apiVersion"`
	Kind        string            `json:"kind"`
	ConfigPath  string            `json:"configPath"`
	Project     string            `json:"project,omitempty"`
	Environment string            `json:"environment,omitempty"`
	Valid       bool              `json:"valid"`
	Findings    []ValidateFinding `json:"findings,omitempty"`

	// Summary of the validated environment; set only when Valid.
	Runtime         string `json:"runtime,omitempty"`
	StateBackend    string `json:"stateBackend,omitempty"`
	Consistency     string `json:"consistency,omitempty"`
	MeshEnabled     bool   `json:"meshEnabled,omitempty"`
	MeshNetworkCIDR string `json:"meshNetworkCIDR,omitempty"`
	MeshInterface   string `json:"meshInterface,omitempty"`
	Servers         int    `json:"servers,omitempty"`
	Services        int    `json:"services,omitempty"`
}

ValidateResult is the serializable outcome of `tako validate`: the strict preflight verdict for a config plus the resolved-environment summary the human output prints. Validation is a pure-local read, so the cmd layer populates this document directly; it lives here because pkg/engine is the source of truth for machine-facing documents.

Jump to

Keyboard shortcuts

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