Help us shape the future of Go! Take the 2026 Go Developer Survey

ocicontainerinstances

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 38 Imported by: 0

README

OCI Container Instances

Parity grade: B · SDK github.com/oracle/oci-go-sdk/v65@v65.126.2 · last audited 2026-10-31 (433c4a138)

Coverage

Metric Value
PARITY entries audited 18 (16 ok, 2 partial)
Feature families 9 (6 ok, 3 partial)
Known gaps 7
Deferred items 0
Resource leaks unknown
Known gaps
  • Unverified, chosen by the emulator: the 32 container cap; the health check defaults; default memory per OCPU; the E3 limits (mirrors E4, the Oracle shape page lists E4, E5 and A1 only) and all processorDescription strings; ocid kinds computecontainerinstance, computecontainer and computecontainerinstanceworkrequest; 409 IncorrectState when stopping, starting or restarting from the wrong state; UPDATING as the state during stop, start and restart; INACTIVE once all containers have terminated; 409 for RetrieveLogs with the state engine; gracefulShutdownTimeoutInSeconds is accepted without an upper bound.
  • Only one VNIC and no ocicore VNIC resource: vnicId is a generated OCID that OCI Core does not know, no private IP is assigned, isPublicIpAssigned, hostnameLabel, nsgIds and privateIp are accepted but unused, and containers have no network of their own beyond docker's default.
  • OCI_FSS_FILE_SYSTEM volumes are rejected. securityContext is stored and returned but only runAsUser and runAsGroup are enforced; fsGroup, capabilities, isRootFileSystemReadonly and isNonRootUserCheckEnabled are ignored. isResourcePrincipalDisabled is stored, no resource principal is provided to the containers.
  • gracefulShutdownTimeoutInSeconds is not enforced: docker stops use the runtime's fixed timeout. Memory-backed EMPTYDIR volumes use a directory under /dev/shm rather than a per-instance tmpfs.
  • VAULT image pull secrets expect the secret content to be JSON {"username":...,"password":...}; Oracle's exact secret format is unverified. Pull secrets only apply to the registry endpoint they name.
  • Containers are re-created from their image on every start and restart, so a restart policy restart loses the container's filesystem; only the previous run's logs are kept. Docker log files are not rotated per Oracle's 20 MB retention.
  • Compute shape quotas, availability-domain and fault-domain validation, tenancy limits, IAM policies, systemTags and the definedTags namespace check are not applied.

More

Documentation

Index

Constants

View Source
const (
	EngineState  = "state"
	EngineDocker = "docker"
)

Engine modes (--oci-container-instances-engine).

View Source
const DefaultPort = 8167

DefaultPort is the dedicated control-plane listener's default TCP port.

View Source
const (
	// Region is the fixed region baked into emulated OCIDs.
	Region = "iad"
)

Variables

View Source
var ErrNilAppContext = errors.New("ocicontainerinstances: nil app context")

ErrNilAppContext is returned when Init is called with a nil AppContext.

View Source
var ErrSnapshotNull = errors.New("ocicontainerinstances: null entry in snapshot")

ErrSnapshotNull is returned when a snapshot contains a null entry.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code    string
	Message string
	Status  int
}

APIError is an OCI error response: HTTP status plus the `code` and `message` body fields.

func (*APIError) Error

func (e *APIError) Error() string

type ConfigFile

type ConfigFile struct {
	FileName string `json:"fileName"`
	Data     string `json:"data"`
	Path     string `json:"path,omitempty"`
}

ConfigFile is one file of a CONFIGFILE volume; Data is base64.

type ConfigProvider

type ConfigProvider interface {
	GetOCIContainerInstancesSettings() Settings
}

ConfigProvider extracts OCI Container Instances configuration from the AppContext Config.

type Container

type Container struct {
	Created       time.Time         `json:"timeCreated"`
	Updated       *time.Time        `json:"timeUpdated,omitempty"`
	Terminated    *time.Time        `json:"timeTerminated,omitempty"`
	ExitCode      *int              `json:"exitCode,omitempty"`
	Resource      *ResourceConfig   `json:"resourceConfig,omitempty"`
	Env           map[string]string `json:"environmentVariables,omitempty"`
	Freeform      map[string]string `json:"freeformTags,omitempty"`
	Defined       map[string]any    `json:"definedTags,omitempty"`
	ID            string            `json:"id"`
	DisplayName   string            `json:"displayName"`
	ImageURL      string            `json:"imageUrl"`
	State         string            `json:"lifecycleState"`
	Details       string            `json:"lifecycleDetails,omitempty"`
	WorkingDir    string            `json:"workingDirectory,omitempty"`
	Security      json.RawMessage   `json:"securityContext,omitempty"`
	Command       []string          `json:"command,omitempty"`
	Args          []string          `json:"arguments,omitempty"`
	Mounts        []VolumeMount     `json:"volumeMounts,omitempty"`
	Health        []*HealthCheck    `json:"healthChecks,omitempty"`
	RestartCount  int               `json:"restartCount"`
	NoResourcePrn bool              `json:"isResourcePrincipalDisabled"`
}

Container is one container of a container instance.

type ContainerFilter

type ContainerFilter struct {
	Compartment string
	State       string
	DisplayName string
	InstanceID  string
	AD          string
}

ContainerFilter selects containers in a list.

type Credential

type Credential struct {
	Endpoint string
	Username string
	Password string
}

Credential is a registry login resolved from an image pull secret.

type DNSConfig

type DNSConfig struct {
	Nameservers []string `json:"nameservers,omitempty"`
	Searches    []string `json:"searches,omitempty"`
	Options     []string `json:"options,omitempty"`
}

DNSConfig is a container instance DNS configuration.

type Engine

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

Engine runs container instances in the container runtime.

func NewEngine

func NewEngine(runtime func() (Runtime, error)) *Engine

NewEngine creates an engine; runtime is dialled on first use.

func (*Engine) Close

func (e *Engine) Close()

Close stops every instance and the engine.

func (*Engine) HaltAll

func (e *Engine) HaltAll()

HaltAll stops every instance.

func (*Engine) HaltAsync

func (e *Engine) HaltAsync(instID string, done func())

HaltAsync stops the instance's containers in the background and then calls done.

func (*Engine) Launch

func (e *Engine) Launch(
	inst *Instance, creds func([]PullSecret) ([]Credential, error), done func(error),
)

Launch (re)creates the instance's containers; done gets nil once every container started, or the failure.

func (*Engine) Logs

func (e *Engine) Logs(instID, ctrID string, previous bool) (string, error)

Logs returns the container's stdout and stderr, from the previous run when previous is set.

func (*Engine) Relaunch

func (e *Engine) Relaunch(inst *Instance, creds func([]PullSecret) ([]Credential, error), done func(error))

Relaunch stops the instance's containers and starts them again.

func (*Engine) SetPortPool

func (e *Engine) SetPortPool(p gcpserve.PortPool)

SetPortPool wires the host port source for health check ports.

func (*Engine) SetTiming

func (e *Engine) SetTiming(t Timer, backoff func(int) time.Duration, p Prober)

SetTiming overrides the timer, restart backoff and prober; for tests.

type Handler

type Handler struct {
	Backend *InMemoryBackend

	Port        int
	EnforceAuth bool
	// contains filtered or unexported fields
}

Handler serves OCI Container Instances on its own listener.

func NewHandler

func NewHandler(backend *InMemoryBackend) *Handler

NewHandler creates a Handler; callers override Port and EnforceAuth from Settings.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation returns the operation name for metrics.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource returns the addressed resource id for metrics.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations lists the supported operations.

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler for all OCIContainerInstances requests.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority is irrelevant because RouteMatcher never matches.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all in-memory state.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher never matches: OCIContainerInstances runs on its own listener.

func (*Handler) Shutdown

func (h *Handler) Shutdown(ctx context.Context)

Shutdown stops the listener and the sweeper.

func (*Handler) StartWorker

func (h *Handler) StartWorker(ctx context.Context) error

StartWorker binds the dedicated listener synchronously so a port conflict is returned to the caller.

func (*Handler) Trusted

func (h *Handler) Trusted() echo.HandlerFunc

Trusted returns a handler that skips request-signature verification, for the in-process dashboard proxy.

type HealthCheck

type HealthCheck struct {
	LastChecked   *time.Time     `json:"lastChecked,omitempty"`
	Name          string         `json:"name,omitempty"`
	Type          string         `json:"type"`
	Path          string         `json:"path,omitempty"`
	Status        string         `json:"status"`
	StatusDetails string         `json:"statusDetails,omitempty"`
	FailureAction string         `json:"failureAction"`
	Headers       []HealthHeader `json:"headers,omitempty"`
	Port          int            `json:"port"`
	InitialDelay  int            `json:"initialDelayInSeconds"`
	Interval      int            `json:"intervalInSeconds"`
	FailureThresh int            `json:"failureThreshold"`
	SuccessThresh int            `json:"successThreshold"`
	Timeout       int            `json:"timeoutInSeconds"`
}

HealthCheck is a container health check and its observed status.

type HealthHeader

type HealthHeader struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

HealthHeader is an HTTP health check header.

type InMemoryBackend

type InMemoryBackend struct {
	Auth *ociauth.Registry
	// contains filtered or unexported fields
}

InMemoryBackend holds every container instance and work request under one lock.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates an empty backend running in state-only mode.

func (*InMemoryBackend) ChangeCompartment

func (b *InMemoryBackend) ChangeCompartment(id, ifMatch, compartment string) (string, error)

ChangeCompartment moves the instance to another compartment.

func (*InMemoryBackend) Close

func (b *InMemoryBackend) Close()

Close stops every running container.

func (*InMemoryBackend) Compartments

func (b *InMemoryBackend) Compartments() []string

Compartments lists the distinct compartments that hold container instances.

func (*InMemoryBackend) CreateInstance

func (b *InMemoryBackend) CreateInstance(in createIn, token string) (instanceWire, string, string, error)

CreateInstance registers a container instance and starts its work request.

func (*InMemoryBackend) DeleteInstance

func (b *InMemoryBackend) DeleteInstance(id, ifMatch string) (string, error)

DeleteInstance deletes a container instance.

func (*InMemoryBackend) EngineMode

func (b *InMemoryBackend) EngineMode() string

EngineMode reports the active engine: EngineDocker or EngineState.

func (*InMemoryBackend) GetContainer

func (b *InMemoryBackend) GetContainer(id string) (containerWire, error)

GetContainer returns one container.

func (*InMemoryBackend) GetInstance

func (b *InMemoryBackend) GetInstance(id string) (instanceWire, string, error)

GetInstance returns one container instance with its etag.

func (*InMemoryBackend) GetWorkRequest

func (b *InMemoryBackend) GetWorkRequest(id string) (WorkRequestWire, error)

GetWorkRequest returns one work request.

func (*InMemoryBackend) ListContainers

func (b *InMemoryBackend) ListContainers(f ContainerFilter, o ListOpts) (page.Page[containerSummaryWire], error)

ListContainers lists containers of a compartment.

func (*InMemoryBackend) ListInstances

func (b *InMemoryBackend) ListInstances(f InstanceFilter, o ListOpts) (page.Page[instanceSummaryWire], error)

ListInstances lists container instances of a compartment.

func (*InMemoryBackend) ListShapes

func (b *InMemoryBackend) ListShapes(compartment string, o ListOpts) (page.Page[ShapeWire], error)

ListShapes lists the container instance shapes.

func (*InMemoryBackend) ListWorkRequests

ListWorkRequests lists the work requests of a compartment, newest first.

func (*InMemoryBackend) Mutate

func (b *InMemoryBackend) Mutate(id string, fn func(*Instance))

Mutate runs fn on the instance under the write lock (Sink).

func (*InMemoryBackend) Now

func (b *InMemoryBackend) Now() time.Time

Now returns the backend clock (Sink).

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all state and stops every running container.

func (*InMemoryBackend) Restart

func (b *InMemoryBackend) Restart(id, ifMatch string) (string, error)

Restart restarts a running container instance.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state. Containers do not survive a restart: instances that were running come back INACTIVE.

func (*InMemoryBackend) RetrieveLogs

func (b *InMemoryBackend) RetrieveLogs(id string, previous bool) (string, error)

RetrieveLogs returns the container's stdout and stderr.

func (*InMemoryBackend) SetClock

func (b *InMemoryBackend) SetClock(now func() time.Time)

SetClock injects the time source used for lifecycle transitions.

func (*InMemoryBackend) SetCompartmentChecker

func (b *InMemoryBackend) SetCompartmentChecker(fn func(string) bool)

SetCompartmentChecker validates compartmentId arguments against another service (OCI Identity).

func (*InMemoryBackend) SetEngine

func (b *InMemoryBackend) SetEngine(e *Engine)

SetEngine switches the backend to docker mode.

func (*InMemoryBackend) SetSecretReader

func (b *InMemoryBackend) SetSecretReader(fn SecretReader)

SetSecretReader resolves VAULT image pull secrets through OCI Vault.

func (*InMemoryBackend) SetSubnetChecker

func (b *InMemoryBackend) SetSubnetChecker(fn func(string) bool)

SetSubnetChecker validates VNIC subnetIds against another service (OCI Core).

func (*InMemoryBackend) SetTransition

func (b *InMemoryBackend) SetTransition(d time.Duration)

SetTransition sets how long asynchronous state-only operations take to complete.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state, including registered API keys and image pull secrets.

func (*InMemoryBackend) Start

func (b *InMemoryBackend) Start(id, ifMatch string) (string, error)

Start starts a stopped container instance.

func (*InMemoryBackend) Stop

func (b *InMemoryBackend) Stop(id, ifMatch string) (string, error)

Stop stops a running container instance.

func (*InMemoryBackend) Sweep

func (b *InMemoryBackend) Sweep()

Sweep applies due time-based transitions against the backend clock.

func (*InMemoryBackend) UpdateContainer

func (b *InMemoryBackend) UpdateContainer(id, ifMatch string, u updateIn) (string, error)

UpdateContainer changes a container's display name and tags.

func (*InMemoryBackend) UpdateInstance

func (b *InMemoryBackend) UpdateInstance(id, ifMatch string, u updateIn) (string, error)

UpdateInstance changes the display name and tags.

func (*InMemoryBackend) WorkRequestErrors

func (b *InMemoryBackend) WorkRequestErrors(id string, o ListOpts) (page.Page[wrErrorWire], error)

WorkRequestErrors lists the errors of a failed work request.

func (*InMemoryBackend) WorkRequestLogs

func (b *InMemoryBackend) WorkRequestLogs(id string, o ListOpts) (page.Page[wrLogWire], error)

WorkRequestLogs lists the progress log of a work request, oldest first.

type Instance

type Instance struct {
	Created      time.Time         `json:"timeCreated"`
	Updated      *time.Time        `json:"timeUpdated,omitempty"`
	TransitionAt *time.Time        `json:"transitionAt,omitempty"`
	Graceful     *int64            `json:"gracefulShutdownTimeoutInSeconds,omitempty"`
	DNS          *DNSConfig        `json:"dnsConfig,omitempty"`
	Freeform     map[string]string `json:"freeformTags,omitempty"`
	Defined      map[string]any    `json:"definedTags,omitempty"`
	FaultDomain  string            `json:"faultDomain,omitempty"`
	RetryToken   string            `json:"retryToken,omitempty"`
	DisplayName  string            `json:"displayName"`
	Compartment  string            `json:"compartmentId"`
	AD           string            `json:"availabilityDomain"`
	ID           string            `json:"id"`
	State        string            `json:"lifecycleState"`
	Details      string            `json:"lifecycleDetails,omitempty"`
	Shape        string            `json:"shape"`
	Restart      string            `json:"containerRestartPolicy"`
	Etag         string            `json:"etag"`
	Target       string            `json:"target,omitempty"`
	Security     json.RawMessage   `json:"securityContext,omitempty"`
	Containers   []*Container      `json:"containers"`
	Volumes      []Volume          `json:"volumes,omitempty"`
	Vnics        []Vnic            `json:"vnics"`
	PullSecrets  []PullSecret      `json:"imagePullSecrets,omitempty"`
	ShapeConfig  ShapeConfig       `json:"shapeConfig"`
}

Instance is a container instance.

type InstanceFilter

type InstanceFilter struct {
	Compartment string
	State       string
	DisplayName string
	AD          string
}

InstanceFilter selects container instances in a list.

type ListOpts

type ListOpts struct {
	SortBy string
	Order  string
	Page   string
	Limit  int
}

ListOpts carries the shared list query parameters.

type Prober

type Prober func(ctx context.Context, hc HealthCheck, hostPort int) error

Prober checks one health check against the container's loopback-published port.

type Provider

type Provider struct{}

Provider implements service.Provider for OCI Container Instances. It runs on its own listener (see Handler.StartWorker) and never matches on the shared AWS router.

func (*Provider) Init

Init creates the backend and handler; the port is bound in StartWorker.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the service provider name.

type PullSecret

type PullSecret struct {
	Type     string `json:"type"`
	Endpoint string `json:"registryEndpoint"`
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	SecretID string `json:"secretId,omitempty"`
}

PullSecret is an image pull secret; BASIC credentials never leave the backend.

type ResourceConfig

type ResourceConfig struct {
	VcpusLimit       *float32 `json:"vcpusLimit,omitempty"`
	MemoryLimitInGBs *float32 `json:"memoryLimitInGBs,omitempty"`
}

ResourceConfig caps a container's resources.

type Runtime

type Runtime interface {
	// Pull fetches ref when it is absent locally or when cred is set.
	Pull(ctx context.Context, ref string, cred *Credential) error
	Start(ctx context.Context, spec container.Spec) (string, error)
	// Wait blocks until the container exits and returns its exit code.
	Wait(ctx context.Context, id string) (int, error)
	Logs(ctx context.Context, id string) (string, error)
	// Kill stops the container but keeps it, so Wait reports its exit code and logs stay readable.
	Kill(ctx context.Context, id string) error
	Remove(ctx context.Context, id string) error
}

Runtime is the slice of the container runtime Container Instances need.

func NewDockerRuntime

func NewDockerRuntime(r gcpserve.Runner) Runtime

NewDockerRuntime wraps a pkgs/container runtime.

type SecretReader

type SecretReader func(secretID string) (string, error)

SecretReader returns the decoded content of a Vault secret.

type Settings

type Settings struct {
	Engine string `` //nolint:lll // config struct tags are intentionally verbose
	/* 294-byte string literal not displayed */
	Port int `` //nolint:lll // config struct tags are intentionally verbose
	/* 231-byte string literal not displayed */
	EnforceAuth bool `` //nolint:lll // config struct tags are intentionally verbose
	/* 274-byte string literal not displayed */
}

Settings holds service-level configuration, embedded in the root CLI as CLI.OCIContainerInstances.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings returns the settings used when no ConfigProvider is available.

type ShapeConfig

type ShapeConfig struct {
	Processor string  `json:"processorDescription"`
	Ocpus     float32 `json:"ocpus"`
	Memory    float32 `json:"memoryInGBs"`
	Bandwidth float32 `json:"networkingBandwidthInGbps"`
}

ShapeConfig is the compute size of an instance.

type ShapeWire

type ShapeWire struct {
	Name      string `json:"name"`
	Processor string `json:"processorDescription"`
	Ocpu      struct {
		Min float32 `json:"min"`
		Max float32 `json:"max"`
	} `json:"ocpuOptions"`
	Memory struct {
		MinInGBs   float32 `json:"minInGBs"`
		MaxInGBs   float32 `json:"maxInGBs"`
		DefPerOcpu float32 `json:"defaultPerOcpuInGBs"`
		MinPerOcpu float32 `json:"minPerOcpuInGBs"`
		MaxPerOcpu float32 `json:"maxPerOcpuInGBs"`
	} `json:"memoryOptions"`
	Bandwidth struct {
		Min        float32 `json:"minInGbps"`
		Max        float32 `json:"maxInGbps"`
		DefPerOcpu float32 `json:"defaultPerOcpuInGbps"`
	} `json:"networkingBandwidthOptions"`
}

ShapeWire is the wire form of a container instance shape.

type Sink

type Sink interface {
	Mutate(instID string, fn func(*Instance))
	Now() time.Time
}

Sink is the backend side the engine reports container state to.

type Timer

type Timer func(d time.Duration) (<-chan time.Time, func())

Timer returns a channel that fires after d and a function that releases it.

type Vnic

type Vnic struct {
	VnicID   string `json:"vnicId"`
	SubnetID string `json:"subnetId"`
}

Vnic is a container instance VNIC.

type Volume

type Volume struct {
	Name         string       `json:"name"`
	Type         string       `json:"type"`
	BackingStore string       `json:"backingStore,omitempty"`
	Configs      []ConfigFile `json:"configs,omitempty"`
}

Volume is a container instance volume.

type VolumeMount

type VolumeMount struct {
	ReadOnly   *bool  `json:"isReadOnly,omitempty"`
	Partition  *int   `json:"partition,omitempty"`
	MountPath  string `json:"mountPath"`
	VolumeName string `json:"volumeName"`
	SubPath    string `json:"subPath,omitempty"`
}

VolumeMount mounts a volume into a container.

type WorkRequest

type WorkRequest struct {
	Accepted     time.Time  `json:"timeAccepted"`
	FinishAt     *time.Time `json:"finishAt,omitempty"`
	FinishedAt   *time.Time `json:"timeFinished,omitempty"`
	ID           string     `json:"id"`
	Type         string     `json:"operationType"`
	Compartment  string     `json:"compartmentId"`
	ResourceID   string     `json:"resourceId"`
	ResourceType string     `json:"resourceType"`
	Action       string     `json:"actionType"`
	Status       string     `json:"status"`
	ErrCode      string     `json:"errorCode,omitempty"`
	ErrMsg       string     `json:"errorMessage,omitempty"`
	Seq          int64      `json:"seq"`
}

WorkRequest is an asynchronous operation record.

type WorkRequestFilter

type WorkRequestFilter struct {
	Compartment string
	ID          string
	Status      string
	ResourceID  string
	AD          string
}

WorkRequestFilter selects work requests in a list.

type WorkRequestWire

type WorkRequestWire struct {
	TimeAccepted time.Time        `json:"timeAccepted"`
	TimeStarted  time.Time        `json:"timeStarted"`
	TimeFinished *time.Time       `json:"timeFinished,omitempty"`
	Type         string           `json:"operationType"`
	Status       string           `json:"status"`
	ID           string           `json:"id"`
	Compartment  string           `json:"compartmentId"`
	Resources    []wrResourceWire `json:"resources"`
	Percent      float32          `json:"percentComplete"`
}

WorkRequestWire is the wire form of a work request.

Jump to

Keyboard shortcuts

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