container

package
v0.18.3 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: Apache-2.0 Imports: 69 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DOCKER_COMMAND = "docker"
	PODMAN_COMMAND = "podman"
)
View Source
const (
	DockerLocalhostBindingHostname = "host.docker.internal"
	OtherLocalhostBindingHostname  = "host.containers.internal"
)
View Source
const (
	OPENRUN_FIELD_MANAGER = "openrun"
	KUBERNETES_NAME_MAX   = 63

	// Ownership labels used to identify objects (Secrets/ConfigMaps) generated
	// by OpenRun for a specific container, so snapshot/restore only ever lists,
	// overwrites, or deletes OpenRun-managed objects and never an unrelated
	// object that merely shares the common "app" label.
	MANAGED_BY_LABEL = "app.kubernetes.io/managed-by"
	INSTANCE_LABEL   = "app.kubernetes.io/instance"
	MANAGED_BY_VALUE = "openrun"
)
View Source
const IMAGE_NAME_PREFIX = "cli-"
View Source
const LABEL_PREFIX = "dev.openrun."
View Source
const UNNAMED_VOLUME = "<UNNAMED>"
View Source
const VERSION_HASH_LABEL = LABEL_PREFIX + "version.hash"

Variables

View Source
var (
	KNOWN_OPTIONS = []string{"cpus", "memory", "min_replicas", "max_replicas"}
)

Functions

func BuildHTTPTransport

func BuildHTTPTransport(r *types.RegistryConfig) (*http.Transport, error)

func BytesString added in v0.16.0

func BytesString(s string) (string, error)

BytesString parses s and returns bytes as a base-10 integer string.

Rules: 1) If already an integer string (bytes), return as-is. 2) If docker-like (e.g., 512m, 1g), parse via Docker and return bytes. 3) Otherwise parse as k8s Quantity (e.g., 512Mi, 1Gi, 500M) and return bytes.

func CPUString added in v0.16.0

func CPUString(s string, targetIsDocker bool) (string, error)

CPUString converts CPU from either docker-like ("0.5", "2") or k8s-like ("500m", "1") into a string that "makes sense" for the target.

  • targetIsDocker=true => return cores as decimal string (e.g. "0.5", "2")
  • targetIsDocker=false => return millicores as integer string (e.g. "500", "2000")

Notes:

  • Bare "1" is treated as 1 core (not 1 millicore).
  • For millicores input, use "m" suffix: "500m".

func ClusterRollbackClean added in v0.18.3

func ClusterRollbackClean(err error) bool

func CommandOptionArgs added in v0.17.0

func CommandOptionArgs(options CommandOptions, allowedContainerArgs map[string]string) ([]string, error)

CommandOptionArgs converts parsed container options into CLI args. Built-in OpenRun options are parsed explicitly. Any remaining Docker/Podman flags must be listed in allowedContainerArgs before they are emitted.

func ContextWithDeployTxn added in v0.18.3

func ContextWithDeployTxn(ctx context.Context, d *DeployTxn) context.Context

func CreateOrUpdateSecret

func CreateOrUpdateSecret(ctx context.Context, cs kubernetes.Interface, ns, name string, data map[string][]byte, typ corev1.SecretType) error

func DelegateHandler

func DelegateHandler(r *http.Request, config *types.ServerConfig, logger *types.Logger) (any, error)

DelegateHandler is the handler for the delegated build API

func DigestPinned added in v0.17.3

func DigestPinned(image, digest string) string

DigestPinned returns image with the given digest appended, replacing any existing @digest suffix. For example:

("mycompany/jp-app:latest",          "sha256:abc") -> "mycompany/jp-app:latest@sha256:abc"
("mycompany/jp-app@sha256:old",      "sha256:new") -> "mycompany/jp-app@sha256:new"
("mycompany/jp-app:v1@sha256:old",   "sha256:new") -> "mycompany/jp-app:v1@sha256:new"
("mycompany/jp-app",                 "sha256:abc") -> "mycompany/jp-app@sha256:abc"

Both Docker and Kubernetes accept "repo:tag@digest" references; when both are present the digest is authoritative. Returns image unchanged if either argument is empty.

func GenerateDockerConfigJSON

func GenerateDockerConfigJSON(r *types.RegistryConfig) ([]byte, error)

func GetDockerConfig

func GetDockerConfig(ctx context.Context, imageRef string, registryConfig *types.RegistryConfig) (name.Reference, []remote.Option, error)

func GetImageReferenceConfig added in v0.18.3

func GetImageReferenceConfig(ctx context.Context, imageRef string, registryConfig *types.RegistryConfig) (name.Reference, []remote.Option, error)

func HasPersistentVolume added in v0.18.3

func HasPersistentVolume(volumes []*VolumeInfo) bool

HasPersistentVolume reports whether any mount is PVC-backed (a named volume or UNNAMED_VOLUME). Secrets (IsSecret) and config-maps (VolumeName == "") are per-pod and impose no single-writer constraint, so they are excluded. Under the default ReadWriteOnce access mode such a volume cannot be multi-attached, so its presence forces a downtime (Recreate) deploy rather than a surge-based rolling update.

TODO: exempt volumes once per-app ReadOnlyMany/ReadWriteMany access modes are supported.

func ImageExists

func ImageExists(ctx context.Context, logger *types.Logger, imageRef string, r *types.RegistryConfig) (bool, error)

func KanikoJob

func KanikoJob(ctx context.Context, logger *types.Logger, cs kubernetes.Interface, cfg *rest.Config, r *types.RegistryConfig, dockerCfgJSON []byte, kb KanikoBuild) error

func LocalhostBindingHostname added in v0.18.0

func LocalhostBindingHostname(containerCommand string) string

LocalhostBindingHostname returns the hostname app containers should use to reach services bound to localhost on the OpenRun host.

func LocalhostHostGatewayArgs added in v0.18.0

func LocalhostHostGatewayArgs(containerCommand string) []string

LocalhostHostGatewayArgs returns runtime args needed for host.docker.internal to resolve inside Docker app containers.

func LookupContainerCommand

func LookupContainerCommand(checkKubernetes bool) string

func RedactEnvArgs added in v0.17.5

func RedactEnvArgs(args []string) []string

func TrimLabelValue added in v0.16.0

func TrimLabelValue(input string) string

TrimLabelValue trims the input string to 63 characters so that it can be used as a Kubernetes label value

Types

type CommandCM added in v0.16.0

type CommandCM struct {
	*types.Logger
	// contains filtered or unexported fields
}

func NewCommandCM added in v0.16.0

func NewCommandCM(logger *types.Logger, config *types.ServerConfig, appId types.AppId, appRunDir string) *CommandCM

func (*CommandCM) BuildImage added in v0.16.0

func (c *CommandCM) BuildImage(ctx context.Context, imgName ImageName, sourceUrl, containerFile string, containerArgs map[string]string) error

func (*CommandCM) DeployContainer added in v0.18.3

func (c *CommandCM) DeployContainer(ctx context.Context, req DeployRequest) (DeployResult, error)

func (*CommandCM) ExecTailN added in v0.16.0

func (c *CommandCM) ExecTailN(ctx context.Context, command string, args []string, n int) ([]string, error)

ExecTailN executes a command and returns the last n lines of output

func (*CommandCM) GetContainerLogs added in v0.16.0

func (c *CommandCM) GetContainerLogs(ctx context.Context, name ContainerName, linesToShow int) (string, error)

func (*CommandCM) GetContainerState added in v0.16.0

func (c *CommandCM) GetContainerState(ctx context.Context, name ContainerName, expectHash string) (string, bool, error)

GetContainerState returns the host:port of the running container, "" if not running. running is true if the container is running.

func (*CommandCM) ImageExists added in v0.16.0

func (c *CommandCM) ImageExists(ctx context.Context, name ImageName) (bool, error)

func (*CommandCM) ListOpenRunContainers added in v0.17.3

func (c *CommandCM) ListOpenRunContainers(ctx context.Context) ([]Container, error)

ListOpenRunContainers returns running containers with an OpenRun ownership label.

func (*CommandCM) RefreshImage added in v0.17.3

func (c *CommandCM) RefreshImage(ctx context.Context, name ImageName) (string, error)

RefreshImage pulls the named image and returns its content-addressable digest. It first attempts to extract the manifest digest from RepoDigests (which is stable across container managers and matches the digest the registry advertises); it falls back to the image config digest (.Id) when the local image has no associated RepoDigests entry (e.g. it was built locally rather than pulled).

func (*CommandCM) RemoveContainer added in v0.16.0

func (c *CommandCM) RemoveContainer(ctx context.Context, name ContainerName) error

func (*CommandCM) RemoveImage added in v0.16.0

func (c *CommandCM) RemoveImage(ctx context.Context, name ImageName) error

func (*CommandCM) RunContainer added in v0.16.0

func (c *CommandCM) RunContainer(ctx context.Context, appEntry *types.AppEntry, sourceDir string, containerName ContainerName,
	imageName ImageName, port int32, envMap map[string]string, volumes []*VolumeInfo,
	containerOptions map[string]string, paramMap map[string]string, versionHash string, isImageSpec bool,
	_ *HealthProbe) error

func (*CommandCM) StartContainer added in v0.16.0

func (c *CommandCM) StartContainer(ctx context.Context, name ContainerName) error

func (*CommandCM) StopContainer added in v0.16.0

func (c *CommandCM) StopContainer(ctx context.Context, name ContainerName) error

func (*CommandCM) SupportsInPlaceUpdate added in v0.16.0

func (k *CommandCM) SupportsInPlaceUpdate() bool

func (CommandCM) VolumeCreate added in v0.16.0

func (c CommandCM) VolumeCreate(ctx context.Context, name VolumeName) error

func (CommandCM) VolumeExists added in v0.16.0

func (c CommandCM) VolumeExists(ctx context.Context, name VolumeName) bool

type CommandOptions added in v0.16.0

type CommandOptions struct {
	Cpus   string         `mapstructure:"cpus"`
	Memory string         `mapstructure:"memory"`
	Other  map[string]any `mapstructure:",remain"`
}

func ParseCommandOptions added in v0.17.0

func ParseCommandOptions(containerCommand string, options map[string]string) (CommandOptions, error)

type Container

type Container struct {
	ID         string `json:"ID"`
	Names      string `json:"Names"`
	Image      string `json:"Image"`
	State      string `json:"State"`
	Status     string `json:"Status"`
	PortString string `json:"Ports"`
	Port       int
}

type ContainerManager

type ContainerManager interface {
	BuildImage(ctx context.Context, name ImageName, sourceUrl, containerFile string, containerArgs map[string]string) error
	ImageExists(ctx context.Context, name ImageName) (bool, error)
	// RefreshImage pulls (or HEADs) the named image from its registry and returns a
	// stable content-addressable digest (e.g. "sha256:..."). Only used for
	// image-spec apps so the container handler can detect when the upstream
	// reference has moved and recreate the container with the new content.
	RefreshImage(ctx context.Context, name ImageName) (digest string, err error)
	GetContainerState(ctx context.Context, name ContainerName, expectHash string) (hostPort string, running bool, err error)
	StartContainer(ctx context.Context, name ContainerName) error
	StopContainer(ctx context.Context, name ContainerName) error
	RunContainer(ctx context.Context, appEntry *types.AppEntry, sourceDir string, containerName ContainerName,
		imageName ImageName, port int32, envMap map[string]string, volumes []*VolumeInfo,
		containerOptions map[string]string, paramMap map[string]string, versionHash string, isImageSpec bool,
		healthProbe *HealthProbe) error
	DeployContainer(ctx context.Context, req DeployRequest) (DeployResult, error)
	GetContainerLogs(ctx context.Context, name ContainerName, linesToShow int) (string, error)
	VolumeExists(ctx context.Context, name VolumeName) bool
	VolumeCreate(ctx context.Context, name VolumeName) error
	SupportsInPlaceUpdate() bool
}

ContainerManager is the interface for managing containers

func WrapContainerManager added in v0.17.1

func WrapContainerManager(cm ContainerManager, kind string) ContainerManager

type ContainerName

type ContainerName string

func GenContainerName

func GenContainerName(appId types.AppId, contentHash string, supportsInPlaceUpdate bool) ContainerName

type DelegateRequest

type DelegateRequest struct {
	ImageTag       string
	ContainerFile  string
	ContainerArgs  map[string]string
	RegistryConfig *types.RegistryConfig
}

type DeployRequest added in v0.18.3

type DeployRequest struct {
	AppEntry           *types.AppEntry
	SourceDir          string
	ContainerName      ContainerName
	ImageName          ImageName
	Port               int32
	EnvMap             map[string]string
	Volumes            []*VolumeInfo
	ContainerOptions   map[string]string
	ParamMap           map[string]string
	VersionHash        string
	IsImageSpec        bool
	HealthProbe        *HealthProbe
	Verify             bool
	DeployAttempts     int
	LogLinesToShow     int
	ShowLogsForFailure bool
}

type DeployResult added in v0.18.3

type DeployResult struct {
	ContainerName ContainerName
	VersionHash   string
	HostNamePort  string
}

type DeployRollbackError added in v0.18.3

type DeployRollbackError struct {
	Err         error
	Available   bool
	RollbackErr error
}

DeployRollbackError wraps a verification failure with the status of the cluster-side rollback, so callers can report accurately instead of always claiming "all changes have been reverted".

func (*DeployRollbackError) Error added in v0.18.3

func (e *DeployRollbackError) Error() string

func (*DeployRollbackError) Unwrap added in v0.18.3

func (e *DeployRollbackError) Unwrap() error

type DeployTxn added in v0.18.3

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

DeployTxn is an operation-level deploy stack for container deployments. A single reload/apply command may deploy several apps before a later app fails. Because the control-plane DB transaction commits or rolls back as a whole, the cluster must follow: each app that successfully deploys registers an onRollback and an onCommit closure here, and the server invokes RollbackAll on failure or CommitAll on success.

func DeployTxnFromContext added in v0.18.3

func DeployTxnFromContext(ctx context.Context) *DeployTxn

func NewDeployTxn added in v0.18.3

func NewDeployTxn() *DeployTxn

func (*DeployTxn) CommitAll added in v0.18.3

func (d *DeployTxn) CommitAll(ctx context.Context) error

func (*DeployTxn) Register added in v0.18.3

func (d *DeployTxn) Register(appId types.AppId, onRollback, onCommit func(ctx context.Context) error)

func (*DeployTxn) RollbackAll added in v0.18.3

func (d *DeployTxn) RollbackAll(ctx context.Context) error

type DevContainerManager

type DevContainerManager interface {
	ContainerManager
	RemoveImage(ctx context.Context, name ImageName) error
	RemoveContainer(ctx context.Context, name ContainerName) error
}

DevContainerManager is the interface for managing containers in dev mode

type ExistsResult

type ExistsResult struct {
	Exists bool
	Digest string
}

func CheckImageReferenceExists added in v0.18.3

func CheckImageReferenceExists(ctx context.Context, logger *types.Logger, imageRef string, registryConfig *types.RegistryConfig) (ExistsResult, error)

func CheckImagesExists

func CheckImagesExists(ctx context.Context, logger *types.Logger, imageRef string, registryConfig *types.RegistryConfig) (ExistsResult, error)

type HealthProbe added in v0.18.3

type HealthProbe struct {
	Path             string
	Port             int32
	Scheme           string // "HTTP" or "HTTPS"
	PeriodSecs       int32
	TimeoutSecs      int32
	FailureThreshold int32 // steady-state readiness tolerance
	StartupFailures  int32 // startup probe tolerance for slow boots
}

HealthProbe describes an HTTP health check that a container manager can translate into a native readiness/startup probe. A nil *HealthProbe means no probe should be configured (e.g. command-lifetime apps or apps without a health URL).

type ImageName

type ImageName string

func GenImageName

func GenImageName(appId types.AppId, contentHash string) ImageName

type KanikoBuild

type KanikoBuild struct {
	Namespace     string
	JobName       string
	Image         string // e.g. "cgr.dev/chainguard/kaniko:latest"
	SourceDir     string // Local directory to tar up and send to Kaniko
	Dockerfile    string
	Destination   string
	ContainerArgs map[string]string
	ExtraArgs     []string
}

type KubernetesCM added in v0.16.0

type KubernetesCM struct {
	*types.Logger
	// contains filtered or unexported fields
}

func NewKubernetesCM added in v0.16.0

func NewKubernetesCM(logger *types.Logger, config *types.ServerConfig, appConfig *types.AppConfig, appRunDir string, appId types.AppId) (*KubernetesCM, error)

func (*KubernetesCM) BuildImage added in v0.16.0

func (k *KubernetesCM) BuildImage(ctx context.Context, imgName ImageName, sourceUrl, containerFile string, containerArgs map[string]string) error

func (*KubernetesCM) CurrentVersionHash added in v0.18.3

func (k *KubernetesCM) CurrentVersionHash(ctx context.Context, name ContainerName) (string, error)

CurrentVersionHash returns the version hash the stable Service currently routes to. It is used by stale app handlers to avoid acting on a newer deployment. For stateless apps it is the Service selector's version hash; for PVC apps (version-agnostic selector) it is the active Deployment's pod hash.

func (*KubernetesCM) DeployContainer added in v0.18.3

func (k *KubernetesCM) DeployContainer(ctx context.Context, req DeployRequest) (DeployResult, error)

func (*KubernetesCM) GetContainerLogs added in v0.16.0

func (k *KubernetesCM) GetContainerLogs(ctx context.Context, name ContainerName, linesToShow int) (string, error)

func (*KubernetesCM) GetContainerState added in v0.16.0

func (k *KubernetesCM) GetContainerState(ctx context.Context, name ContainerName, expectHash string) (string, bool, error)

func (*KubernetesCM) ImageExists added in v0.16.0

func (k *KubernetesCM) ImageExists(ctx context.Context, name ImageName) (bool, error)

func (*KubernetesCM) PromoteVersion added in v0.18.3

func (k *KubernetesCM) PromoteVersion(ctx context.Context, serviceName ContainerName, versionHash string) (string, map[string]string, error)

PromoteVersion points the stable Service at versionHash and returns the version hash and selector that were previously active.

func (*KubernetesCM) RefreshImage added in v0.17.3

func (k *KubernetesCM) RefreshImage(ctx context.Context, name ImageName) (string, error)

func (*KubernetesCM) RemoveVersion added in v0.18.3

func (k *KubernetesCM) RemoveVersion(ctx context.Context, serviceName ContainerName, versionHash string) error

RemoveVersion deletes the workload (Deployment plus owned HPA, Secrets and ConfigMaps) for one stateless version. A NotFound is treated as success.

func (*KubernetesCM) Restore added in v0.18.3

func (k *KubernetesCM) Restore(ctx context.Context, snapshot any) error

Restore reverts the Deployment, HPA, Secrets and ConfigMaps to the captured snapshot and deletes any of those objects that were created after it. It is best-effort: all steps run and the joined error (if any) is returned. PVC contents are not reverted.

func (*KubernetesCM) RunContainer added in v0.16.0

func (k *KubernetesCM) RunContainer(ctx context.Context, appEntry *types.AppEntry, sourceDir string, containerName ContainerName,
	imageName ImageName, port int32, envMap map[string]string, volumes []*VolumeInfo,
	containerOptions map[string]string, paramMap map[string]string, versionHash string, isImageSpec bool,
	healthProbe *HealthProbe) error

func (*KubernetesCM) Snapshot added in v0.18.3

func (k *KubernetesCM) Snapshot(ctx context.Context, name ContainerName) (any, error)

Snapshot captures the current Deployment plus the HPA, Secrets and ConfigMaps owned by the named container. Secrets/ConfigMaps are selected by the OpenRun ownership labels (see ownershipSelector) so only OpenRun-managed objects are captured, never an unrelated object sharing the "app" label.

func (*KubernetesCM) StartContainer added in v0.16.0

func (k *KubernetesCM) StartContainer(ctx context.Context, name ContainerName) error

func (*KubernetesCM) StopContainer added in v0.16.0

func (k *KubernetesCM) StopContainer(ctx context.Context, name ContainerName) error

func (*KubernetesCM) SupportsInPlaceUpdate added in v0.16.0

func (k *KubernetesCM) SupportsInPlaceUpdate() bool

func (*KubernetesCM) VolumeCreate added in v0.16.0

func (k *KubernetesCM) VolumeCreate(ctx context.Context, name VolumeName) error

func (*KubernetesCM) VolumeExists added in v0.16.0

func (k *KubernetesCM) VolumeExists(ctx context.Context, name VolumeName) bool

type KubernetesOptions added in v0.16.0

type KubernetesOptions struct {
	Cpus        string         `mapstructure:"cpus"`
	Memory      string         `mapstructure:"memory"`
	MinReplicas int32          `mapstructure:"min_replicas"` // min number of replicas to run the app on
	MaxReplicas int32          `mapstructure:"max_replicas"` // max number of replicas to run the app on
	Other       map[string]any `mapstructure:",remain"`
}

type VersionReporter added in v0.18.3

type VersionReporter interface {
	CurrentVersionHash(ctx context.Context, name ContainerName) (string, error)
}

VersionReporter is implemented by managers that can report the version hash currently configured on a live workload.

func AsVersionReporter added in v0.18.3

func AsVersionReporter(cm ContainerManager) (VersionReporter, bool)

AsVersionReporter unwraps any decorating container managers and returns the underlying VersionReporter if one is present.

type VolumeInfo

type VolumeInfo struct {
	IsSecret   bool
	VolumeName string
	SourcePath string
	TargetPath string
	ReadOnly   bool
}

type VolumeName

type VolumeName string

func GenVolumeName

func GenVolumeName(appId types.AppId, dirName string) VolumeName

Jump to

Keyboard shortcuts

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