instance

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 56 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package instance assembles and runs one emulator instance: state store, gateway, admin API and the selected services.

Index

Constants

View Source
const (
	EndpointsFile = "endpoints.json"
	PIDFile       = "gcpemu.pid"
	LogFile       = "gcpemu.log"
	StateFile     = "state.db"
	IDFile        = "instance-id"
	// AdminTokenFile holds the Admin token while an Instance bound beyond
	// loopback runs (FR-UI-009); CLI commands read it from there.
	AdminTokenFile = "admin-token"
)

Files written in the instance directory.

View Source
const ADCKeyFile = "adc-key.json"

ADCKeyFile is the key file, in the data directory, that `gcpemu env` points GOOGLE_APPLICATION_CREDENTIALS at when gcloud's application-default credentials would otherwise win over the metadata server (ADR 0010).

View Source
const OwnerLockFile = "gcpemu-test-owner.lock"

OwnerLockFile is the owner lock file in a Test data dir. The test that owns the dir holds an exclusive OS lock on it from before its Instance is created until the Instance's containers, networks and volumes are removed; the OS drops the lock if the test's process dies. So a dir whose lock can be taken belongs to a test that has ended, and ReclaimEnded reclaims it (ADRs 0047, 0057). The name and the locking are a contract between the test processes of every emutest version.

View Source
const SnapshotsDir = "snapshots"

SnapshotsDir is the directory under the instance dir holding State snapshots.

Variables

View Source
var (
	// ErrSnapshotNotFound is returned for a State snapshot name that was never saved.
	ErrSnapshotNotFound = errors.New("State snapshot not found")
	// ErrSnapshotBusy is returned when the Instance cannot be snapshotted
	// right now: it is not ready, an Operation is running, or its state
	// kept changing while it was saved.
	ErrSnapshotBusy = errors.New("Instance busy")
	// ErrSnapshotName is returned for a name that is not a valid State snapshot name.
	ErrSnapshotName = errors.New("invalid State snapshot name")
)
View Source
var ErrShutDown = errors.New("Instance shut down")

ErrShutDown means shutdown has begun, so what was asked of the Instance will not happen: it will not become ready, Seeding will not finish, or it will not connect to the container runtime.

View Source
var Version = "dev"

Version is set at build time.

Functions

func HoldOwnerLock added in v0.14.0

func HoldOwnerLock(dir string) (release func(), err error)

HoldOwnerLock takes the owner lock of the Test data dir dir, an absolute path, creating dir if need be, or another reference to it when this process holds it already. It waits up to ownerLockWait for a reclaim that holds it, then fails: another test process owns dir. release drops the reference, and the lock with the last one.

func PIDScope added in v0.15.0

func PIDScope() string

PIDScope is an opaque value that says where this process's pids mean something: another process can watch a pid only from an equal scope. Linux has a PID namespace per container, and every kernel's first one reads the same, so the boot ID tells apart those of a host and a VM. Every other OS has one scope, its own.

func ProcessAlive added in v0.14.0

func ProcessAlive(pid int) bool

ProcessAlive reports whether a process with pid exists.

func ProductImages added in v0.17.0

func ProductImages() []string

ProductImages lists the image of every Managed emulator, for the weekly image report (#1165).

func ReadID added in v0.15.0

func ReadID(dir string) string

ReadID returns the Instance ID that dir holds, or "".

func ReclaimEnded added in v0.14.0

func ReclaimEnded(ctx context.Context, cl *runtime.Client, a Tagged, dir string) (reclaimed bool, err error)

ReclaimEnded prunes a and removes dir if dir is a Test data dir holding a's ID whose test has ended, which taking its owner lock proves. An Instance process that still serves dir is stopped first. Any other dir is left alone, and reclaimed is false.

func ReclaimEndedDir added in v0.14.0

func ReclaimEndedDir(ctx context.Context, cl *runtime.Client, dir string) (reclaimed bool, err error)

ReclaimEndedDir reclaims dir as ReclaimEnded does, for the Instance ID that dir holds and whatever it tags on the runtime, so it also serves a dir that no object records, such as one whose Instance made none (#921). A dir that holds no ID is left alone.

func ReclaimEndedUnder added in v0.15.0

func ReclaimEndedUnder(ctx context.Context, root string, cls []*runtime.Client) error

ReclaimEndedUnder is a run-start reclaim (ADRs 0057, 0077): it reclaims every Test data dir whose test has ended that an object on one of cls records, then each dir directly under root that none records, such as one whose Instance made no object (#921). A nil client is a runtime that did not answer; while there is one, or a runtime fails to list its objects, the dirs that no object records are kept: their objects may be there, and only their dir records whose they are.

Types

type Abandoned added in v0.6.0

type Abandoned struct {
	Tagged
	// Unverified: none of its objects records its data dir (LabelDir), so
	// only the dirs under StateHome were searched for one holding the ID;
	// a --data-dir Instance elsewhere may still own it.
	Unverified bool
	// EndedTestDirs are the Test data dirs whose test has ended that hold
	// the ID; Reclaim removes them too. Its containers may still run.
	EndedTestDirs []string
}

Abandoned is an Abandoned Instance ID: one that still tags containers, networks or volumes but that no data dir holds, or that only Test data dirs whose test has ended hold, so no future Instance reclaims them (#192, #914).

func FindAbandoned added in v0.6.0

func FindAbandoned(ctx context.Context, cl *runtime.Client, stateHome string) ([]Abandoned, error)

FindAbandoned returns the Abandoned Instance IDs on the runtime, sorted. An ID that a dir its objects record, or a dir under stateHome, holds in its instance-id file is Abandoned only when every such dir is a Test data dir whose owner lock is free: its test has ended, even if its containers still run (ADR 0057). Any other ID is never Abandoned while any of its containers runs. A dir that looks missing may be on an unmounted disk or inside a container, so callers confirm before pruning.

func (Abandoned) EndedTest added in v0.14.0

func (a Abandoned) EndedTest() bool

EndedTest reports whether only Test data dirs whose test has ended hold the ID.

func (Abandoned) Reclaim added in v0.14.0

func (a Abandoned) Reclaim(ctx context.Context, cl *runtime.Client) (reclaimed bool, err error)

Reclaim removes a's containers, networks and volumes, and its ended Test data dirs as ReclaimEnded does. It reports false when it removed nothing because a test owns the dirs again or another reclaim has them.

type ClockState added in v0.16.0

type ClockState struct {
	// Now is the emulator time.
	Now time.Time
	// Offset is how far `gcpemu time advance` has moved it past its base:
	// real time, or a Deterministic Instance's own clock.
	Offset time.Duration
}

ClockState is the emulator clock as GET /_emu/v1/time reports it.

type ContainerInfo

type ContainerInfo struct {
	Name     string `json:"name"`
	Service  string `json:"service,omitempty"`
	Resource string `json:"resource,omitempty"`
	Role     string `json:"role,omitempty"`
	Image    string `json:"image"`
	State    string `json:"state"`
}

ContainerInfo describes one container the instance owns (admin API, `gcpemu status`).

type ExternalStatus added in v0.12.0

type ExternalStatus struct {
	gateway.DelegatedAPI
	Reachable bool   `json:"reachable"`
	Error     string `json:"error,omitempty"`
}

ExternalStatus is a Delegated API and whether its External emulator accepts connections.

type Factory

type Factory func(env *emu.Env) emu.Service

Factory builds a service for an environment.

type Instance

type Instance struct {
	Config *config.Config
	Env    *emu.Env
	Log    *reqlog.Log
	// Events is the change feed served at /_emu/v1/events.
	Events *events.Hub
	ID     string
	Dir    string
	// contains filtered or unexported fields
}

Instance is a running emulator.

func New

func New(cfg *config.Config, factories map[string]Factory, logOut io.Writer) (_ *Instance, err error)

New builds an instance from cfg using factories for available services. When it fails, it has closed the state store and removed the temp dir and Admin token file it made (#872).

func (*Instance) AdminToken added in v0.6.0

func (in *Instance) AdminToken() string

AdminToken returns the Admin token, or "" when the gateway is bound to loopback and none is needed (FR-UI-009).

func (*Instance) AdvanceClock

func (in *Instance) AdvanceClock(ctx context.Context, d time.Duration) error

AdvanceClock moves the emulator clock forward (FR-GCS-008). It holds stateMu, so a Reset or time reset cannot land between the move and the ClockObservers' sweeps, or undo the reset (#1172).

func (*Instance) ApplySeed

func (in *Instance) ApplySeed(ctx context.Context, path string) error

ApplySeed applies a seed file (FR-CORE-011). Top-level keys are service names; each section is handed to that service's Seeder. Once shutdown has begun it returns ErrShutDown, however Seeding ended.

func (*Instance) ApplySeedData added in v0.6.0

func (in *Instance) ApplySeedData(ctx context.Context, b []byte, base string) error

ApplySeedData applies a seed file's contents (an uploaded seed file); relative paths in it resolve against base. Once shutdown has begun it returns ErrShutDown, however Seeding ended.

func (*Instance) Clock added in v0.16.0

func (in *Instance) Clock() ClockState

Clock reads the emulator clock. Unlike AdvanceClock it does not move the clock or run any ClockObserver (#1172).

func (*Instance) ConsoleServed added in v0.6.0

func (in *Instance) ConsoleServed() bool

ConsoleServed reports whether the gateway serves the Web console.

func (*Instance) Containers

func (in *Instance) Containers(ctx context.Context) ([]ContainerInfo, error)

Containers lists the instance's containers (see containers.list).

func (*Instance) DeleteSnapshot added in v0.6.0

func (in *Instance) DeleteSnapshot(name string) error

DeleteSnapshot removes the State snapshot name.

func (*Instance) Done

func (in *Instance) Done() <-chan struct{}

Done is closed when Shutdown completes.

func (*Instance) EnvVars

func (in *Instance) EnvVars() map[string]string

EnvVars collects client environment variables from all services, and the Load balancing frontends of the Linked Instances it delegates to.

func (*Instance) ExportSeed added in v0.6.0

func (in *Instance) ExportSeed(ctx context.Context) ([]byte, error)

ExportSeed writes the Instance's resources as a seed file (FR-CORE-013): its Projects, every SeedExporter's section in Service start order, and its Fault rules. Applying it to an empty Instance recreates them.

func (*Instance) External added in v0.12.0

func (in *Instance) External(ctx context.Context) []ExternalStatus

External returns each Delegated API, sorted by API name, with whether its External emulator accepts a TCP connection now. A Managed emulator has no address clients could dial, so none is reported for it.

func (*Instance) Faults

func (in *Instance) Faults() *fault.Set

Faults returns the fault-injection rule set.

func (*Instance) FrontendHosts

func (in *Instance) FrontendHosts() []string

FrontendHosts returns the real hostnames the Google frontend serves.

func (*Instance) HoldReady

func (in *Instance) HoldReady(name, reason string) (release func())

HoldReady keeps the instance not ready, with name and reason reported by Readiness, until release is called. The CLI holds it while the startup seed is applied, so that "ready" means seeded (FR-CI-001).

func (*Instance) HostMode

func (in *Instance) HostMode() hostmode.Status

HostMode returns host mode's status (State "disabled" when off).

func (*Instance) Operations added in v0.2.0

func (in *Instance) Operations(service, project string) []emu.OperationInfo

Operations returns the Operations of every service, or of service and project when they are set, newest first.

func (*Instance) Readiness

func (in *Instance) Readiness() map[string]error

Readiness reports each service's readiness, and any readiness holds: nil error means ready.

func (*Instance) Ready

func (in *Instance) Ready() bool

Ready reports whether every service is ready.

func (*Instance) RequestShutdown

func (in *Instance) RequestShutdown()

RequestShutdown begins shutdown at once and does the rest of Shutdown asynchronously (used by the admin API), with separate limits so that a slow Start can't use up Teardown's time, and Done closes by requestCleanupBy after it begins. It also logs each error, such as a container it could not remove, before Done closes: it has no caller to return them to, and the process may exit as soon as Done closes (#920).

func (*Instance) Reset

func (in *Instance) Reset(ctx context.Context) error

Reset wipes all state but keeps configuration (FR-CORE-002).

func (*Instance) ResetClock added in v0.16.0

func (in *Instance) ResetClock() ClockState

ResetClock sets the emulator clock's offset back to zero, so it reads its base again (#1172). It only moves the clock: it runs no ClockObserver, and what an earlier AdvanceClock set off (lifecycle deletions, expired TTLs, retention) stays done.

func (*Instance) RestoreSnapshot added in v0.6.0

func (in *Instance) RestoreSnapshot(ctx context.Context, name string) error

RestoreSnapshot replaces all of the Instance's state with the State snapshot name: it resets the Instance, loads the snapshot's Store and lets each Snapshotter restore what it saved. Configuration, Fault rules and the Emulator clock, offset and all, are kept.

func (*Instance) RuntimeStatus added in v0.2.0

func (in *Instance) RuntimeStatus(ctx context.Context) RuntimeStatus

RuntimeStatus reports the container runtime the instance uses, or would use. It starts a probe if its last answer is old, waits at most runtimeStatusWait for it, and returns the latest answer: the runtime cannot hold it up, and the probe is every caller's, so one going away does not cut it short.

func (*Instance) SaveSnapshot added in v0.6.0

func (in *Instance) SaveSnapshot(ctx context.Context, name string) (*SnapshotInfo, error)

SaveSnapshot saves all of the Instance's state as the State snapshot name, replacing one saved under that name before. The Instance must be ready with no Operation running, so that no resource is half made.

func (*Instance) Services

func (in *Instance) Services() []emu.Service

Services returns the configured services in start order.

func (*Instance) Shutdown

func (in *Instance) Shutdown(ctx context.Context) error

Shutdown begins shutdown at once, waits for a Start in progress to return, then stops services in reverse order, closes the store and removes runtime files (FR-CORE-006). ctx also limits that wait: when ctx ends first, it logs a warning and carries on with Start still running (ADR 0065). Removing the Instance's containers has a limit of its own, cleanupTime, so Shutdown can run past ctx by up to that (ADR 0078).

func (*Instance) Snapshots added in v0.6.0

func (in *Instance) Snapshots() ([]SnapshotInfo, error)

Snapshots lists the saved State snapshots by name.

func (*Instance) Start

func (in *Instance) Start(ctx context.Context) error

Start registers routes, starts the gateway and every service, and writes endpoints.json. A failing service is reported not-ready rather than stopping the others (NFR-REL-003). Once shutdown has begun it returns ErrShutDown, however starting ended: it does nothing if shutdown began first, and otherwise starts nothing more from the next check on. Teardown waits for it to return (ADR 0065).

func (*Instance) WaitReady

func (in *Instance) WaitReady(ctx context.Context) error

WaitReady blocks until all services are ready or ctx ends. It returns ErrShutDown once shutdown has begun, as the Instance can no longer become ready, whatever its services report and however ctx ended.

func (*Instance) WriteCABundle

func (in *Instance) WriteCABundle() (string, error)

WriteCABundle (re)writes <instance-dir>/ca-bundle.pem: the host's system roots plus the instance CA, for SSL_CERT_FILE.

type RegistryRelayState added in v0.13.0

type RegistryRelayState string

RegistryRelayState is the Registry relay's state, as GET /_emu/v1/registry-relay reports it.

const (
	RegistryRelayOff      RegistryRelayState = "off"
	RegistryRelayStarting RegistryRelayState = "starting"
	RegistryRelayRunning  RegistryRelayState = "running"
	// RegistryRelaySkipped: the port is taken inside the VM.
	RegistryRelaySkipped RegistryRelayState = "skipped"
	RegistryRelayFailed  RegistryRelayState = "failed"
)

type RegistryRelayStatus added in v0.13.0

type RegistryRelayStatus struct {
	State RegistryRelayState `json:"state"`
	// Reason says why it is off, skipped or failed.
	Reason string `json:"reason,omitempty"`
	// Listen is the address it listens on inside the runtime's VM.
	Listen string `json:"listen,omitempty"`
	// Fix is what the user can do when it is skipped.
	Fix string `json:"fix,omitempty"`
	// Podman is the step Podman users take, as Podman does not treat
	// localhost registries as insecure.
	Podman string `json:"podman,omitempty"`
}

RegistryRelayStatus is what GET /_emu/v1/registry-relay reports.

type RuntimeStatus added in v0.2.0

type RuntimeStatus struct {
	Kind      string `json:"kind"` // docker, podman, none or unknown
	Version   string `json:"version,omitempty"`
	Reachable bool   `json:"reachable"`
	Error     string `json:"error,omitempty"`
}

RuntimeStatus describes the container runtime (admin API /info).

type SnapshotInfo added in v0.6.0

type SnapshotInfo struct {
	Name string `json:"name"`
	// CreateTime is the host's wall-clock time of the save, not the Emulator clock.
	CreateTime time.Time `json:"createTime"`
	// Services are the Services the Instance ran when it was saved.
	Services []string `json:"services"`
	// SizeBytes is the size of the snapshot's files on disk.
	SizeBytes int64 `json:"sizeBytes"`
}

SnapshotInfo describes a saved State snapshot.

type Stopping added in v0.15.0

type Stopping struct {
	ID       string `json:"id"`
	Pid      int    `json:"pid"`
	PIDScope string `json:"pidScope"`
}

Stopping is the Instance that accepted a shutdown, as it reported itself.

func AskShutdown added in v0.15.0

func AskShutdown(call func(method, path string) (int, []byte, error), id string, pid int) (Stopping, error)

AskShutdown asks the Instance that call reaches to shut down, if Identify finds it is the Instance id in process pid.

func Identify added in v0.15.0

func Identify(call func(method, path string) (int, []byte, error), id string, pid int) (Stopping, error)

Identify asks the Instance that call reaches which one it is. JSON with no ID, when there is one to compare, is not an Instance's answer. It fails unless that is the Instance id, when id is not "", and in process pid, when pid is not 0. The Instance has to say because the files in a data dir may be a crashed Instance's: their port may have another Instance on it, and their pid may be dead. call makes an Admin API request, returning the status and body.

func (Stopping) Watchable added in v0.15.0

func (s Stopping) Watchable() bool

Watchable reports whether this process can tell when the Instance's process exits. A Containerized Instance's pid means nothing here: it may be missing or name an unrelated process (ADR 0064). So may the pid of an Instance too old to report its scope. Pid 1 in this process's own scope is the container this process runs in, which it cannot outlive.

type Tagged added in v0.13.0

type Tagged struct {
	ID string
	// Dirs are the data dirs its objects record.
	Dirs       []string
	Containers []runtime.Container
	Networks   []runtime.Network
	Volumes    []runtime.Volume
}

Tagged is an Instance ID with the containers, networks and volumes it tags on the runtime.

func FindTagged added in v0.13.0

func FindTagged(ctx context.Context, cl *runtime.Client) ([]Tagged, error)

FindTagged returns every Instance ID that tags containers, networks or volumes on the runtime, sorted. Unlike FindAbandoned it keeps the IDs that are still live, so the caller decides which to Prune.

func (Tagged) Prune added in v0.13.0

func (a Tagged) Prune(ctx context.Context, cl *runtime.Client) error

Prune removes the ID's containers, then its networks, then its volumes, in the order an Instance cleans up after itself.

type UnidentifiedError added in v0.15.0

type UnidentifiedError struct {
	Code int
	Body []byte
}

UnidentifiedError is Identify's error when the API gateway answered without saying which Instance it serves.

func (*UnidentifiedError) Error added in v0.15.0

func (e *UnidentifiedError) Error() string

Jump to

Keyboard shortcuts

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