Documentation
¶
Overview ¶
Package infra provides testcontainers-based infrastructure for E2E tests.
Package infra provides testcontainers-based infrastructure for E2E tests.
Package infra provides E2E test infrastructure in two separate layers:
Aux services (test/e2e/infra/aux): Shared testcontainers that run the same for all deployments — registry, git server, prometheus. Use auxiliary.Get(ctx).
Deployment providers (this package + k8s/, quadlet/): Where Flight Control runs. Interfaces (InfraProvider, ServiceLifecycleProvider, RBACProvider, SecretsProvider) and implementations for K8s and Quadlet. Create once at harness creation via the harness's NewProvidersForEnvironment; then use the interface methods without further environment checks.
Package infra provides testcontainers-based infrastructure for E2E tests.
Convention: never use exec kubectl or the raw Kubernetes client outside of infra/k8s. If harness, util, or other e2e code needs cluster or config access, that functionality must live in infra: implement it in infra/k8s (and in infra/quadlet with equivalent behaviour when relevant for both deployment types), expose it via InfraProvider or another infra interface, and have callers use the provider (e.g. from setup.GetDefaultProviders() or the harness).
Package infra provides testcontainers-based infrastructure for E2E tests.
Package infra provides testcontainers-based infrastructure for E2E tests.
Package infra provides testcontainers-based infrastructure for E2E tests.
Package infra provides testcontainers-based infrastructure for E2E tests.
Index ¶
- Constants
- Variables
- func CollectorDeploymentRequired(fallback bool) (bool, error)
- func DeltaWorkerRegistryCACert() ([]byte, error)
- func DeltaWorkerRegistryCertDir(registryURL string) (string, error)
- func DeltaWorkerRegistryRemapFiles(registryURL string) (remap, insecure string)
- func DetectEnvironment() string
- func GetAPIEndpoint() string
- func GetDefaultQuadletAPIEndpoint() string
- func IsK8sEnvironment() bool
- func IsQuadletEnvironment() bool
- func IsRemoteDeployment() bool
- func MarshalEncryptionConfigIntoYAML(configYAML string, enc *internalconfig.EncryptionConfig) (string, error)
- func NormalizeEnvironmentType(envType string) string
- func ParseBoolEnv(name string, fallback bool) (bool, error)
- func ParseEncryptionConfig(configYAML string) (*internalconfig.EncryptionConfig, error)
- func QueryDB(p *Providers, sql string) (string, error)
- func RequireEnvironment(envType string)
- func RunCleanup(ctx context.Context, steps []CleanupStep) error
- func ServiceFailureObserver(ctx context.Context, lifecycle ServiceLifecycleProvider, ...) (string, error)
- func SkipIfEnvironment(envType string, reason ...string)
- func SkipIfNotK8s(reason ...string)
- func SkipIfNotQuadlet(reason ...string)
- func SkipIfObservabilityNotConfigured(ctx context.Context, providers *Providers)
- func SkipIfRBACNotSupported(rbacProvider RBACProvider)
- type CleanupStep
- type CollectorAvailability
- type CollectorConfigContext
- type CollectorDeployer
- type CollectorDeploymentConfig
- type CollectorImageSelection
- type CollectorInstance
- type DBConnectionParams
- type EnvironmentConfig
- type InfraProvider
- type Permission
- type ProviderFactory
- type Providers
- type RBACProvider
- type RoleBindingSpec
- type RoleSpec
- type SecretsProvider
- type ServiceLifecycleProvider
- type ServiceLogProvider
- type ServiceName
- type TPMProvider
- type TracingProvider
Constants ¶
const ( // EnvCollectorImage names the exact collector image to deploy. CI sets it // to the image produced by the build the run is testing. EnvCollectorImage = "E2E_CATALOG_COLLECTOR_IMAGE" // EnvCollectorImagePreloaded declares that EnvCollectorImage is already in // the deployment's image store, so it must neither be looked for in a // local container runtime nor loaded again. EnvCollectorImagePreloaded = "E2E_CATALOG_COLLECTOR_IMAGE_PRELOADED" // EnvCollectorRequired turns an unavailable collector deployment into a // failure instead of a skip. CI sets it so that a build which stops // shipping the collector image fails loudly rather than quietly reducing // the suite to zero executed specs. EnvCollectorRequired = "E2E_CATALOG_COLLECTOR_REQUIRED" )
Environment variables that select the catalog collector image under test and how strictly the run requires it.
They are read here rather than in a suite because the answer they produce - "can this deployment run a catalog collector at all, and must it" - is a property of the deployment, not of any particular set of specs.
const ( EnvE2EEnvironment = "E2E_ENVIRONMENT" // Environment type: k8s, ocp, quadlet EnvE2ENamespace = "E2E_NAMESPACE" // K8s namespace EnvE2EAPIEndpoint = "E2E_API_ENDPOINT" // FlightCtl API endpoint URL EnvKubeConfig = "KUBECONFIG" // Kubeconfig path EnvE2EKubeContext = "E2E_KUBE_CONTEXT" // Kubeconfig context EnvE2ESSHHost = "E2E_SSH_HOST" // Remote SSH host for Quadlet EnvE2ESSHUser = "E2E_SSH_USER" // SSH username EnvE2ESSHKeyPath = "E2E_SSH_KEY_PATH" // SSH key path // #nosec G101 -- env var name, not a credential value EnvE2ESSHPassword = "E2E_SSH_PASSWORD" // SSH password (alternative to key; requires sshpass) EnvE2EUseSudo = "E2E_USE_SUDO" // Use sudo (default: true for quadlet) EnvE2EConfigDir = "E2E_CONFIG_DIR" // Config directory for Quadlet )
Environment variable names for configuration
const ( // DefaultQuadletConfigDir is the default config directory for Quadlet deployments DefaultQuadletConfigDir = "/etc/flightctl" // DefaultAPIPort is the default port for the FlightCtl API DefaultAPIPort = "443" )
Default values for different environments
const ( EnvironmentKind = "kind" EnvironmentOCP = "ocp" EnvironmentQuadlet = "quadlet" )
EnvironmentType constants for environment detection.
const CoreAPIGroup = "core"
CoreAPIGroup is the sentinel for Kubernetes core API group (e.g. secrets). Use in Permission.ApiGroup.
const EncryptionKeyDir = "/root/.flightctl/encryption"
EncryptionKeyDir is the in-container directory where encryption key files are mounted. Both K8s (via Secret volume) and Quadlet (via bind mount at /etc/flightctl/encryption) present keys at this path inside the container.
const OrgLabelKey = "io.flightctl/instance"
OrgLabelKey is the namespace/project label key for the Flight Control release (K8s: io.flightctl/instance=<releaseName>).
Variables ¶
var DeploymentServiceNames = map[string]ServiceName{ "flightctl-kv": ServiceRedis, "flightctl-api": ServiceAPI, "flightctl-worker": ServiceWorker, "flightctl-delta-worker": ServiceDeltaWorker, "flightctl-periodic": ServicePeriodic, "flightctl-telemetry-gateway": ServiceTelemetryGateway, "flightctl-db": ServiceDB, "flightctl-ui": ServiceUI, "flightctl-alertmanager": ServiceAlertmanager, "flightctl-alertmanager-proxy": ServiceAlertmanagerProxy, "flightctl-imagebuilder-api": ServiceImageBuilderAPI, "flightctl-imagebuilder-worker": ServiceImageBuilderWorker, "flightctl-alert-exporter": ServiceAlertExporter, }
DeploymentServiceNames maps deployment/service names (same in K8s and Quadlet) to ServiceName. Use when callers have a string (e.g. "flightctl-ui") and need a ServiceName for provider calls.
var ErrCollectorDeploymentUnsupported = errors.New("catalog collector deployment is not supported for this deployment type")
ErrCollectorDeploymentUnsupported is returned by CollectorDeployer implementations for deployment types that cannot host a catalog collector. Callers branch on this instead of on the implementation type.
var ErrSecretsNotSupported = fmt.Errorf("secrets not supported in this environment")
ErrSecretsNotSupported is returned when the environment does not support secret storage (e.g. quadlet).
var ErrTPMNotSupported = fmt.Errorf("TPM operations not supported in this environment")
ErrTPMNotSupported is returned when the environment does not support TPM operations.
Functions ¶
func CollectorDeploymentRequired ¶ added in v1.4.0
CollectorDeploymentRequired reports whether the run requires a catalog collector deployment, so that an unavailable one fails instead of skipping.
func DeltaWorkerRegistryCACert ¶ added in v1.4.0
DeltaWorkerRegistryCACert returns the E2E CA certificate used by the auxiliary registry.
func DeltaWorkerRegistryCertDir ¶ added in v1.4.0
DeltaWorkerRegistryCertDir returns the containers/image certs.d directory for the authenticated registry endpoint.
func DeltaWorkerRegistryRemapFiles ¶ added in v1.4.0
DeltaWorkerRegistryRemapFiles returns registries.conf.d snippets that rewrite quay.io/flightctl image refs to registryURL (host:port).
func DetectEnvironment ¶
func DetectEnvironment() string
DetectEnvironment returns the detected environment type using the default factory.
func GetAPIEndpoint ¶
func GetAPIEndpoint() string
GetAPIEndpoint returns the API endpoint using the default factory's config. Uses defaults if not explicitly configured.
func GetDefaultQuadletAPIEndpoint ¶
func GetDefaultQuadletAPIEndpoint() string
GetDefaultQuadletAPIEndpoint returns the default API endpoint for Quadlet deployments. Uses the host's FQDN (hostname -f). VMs will have /etc/hosts entry injected during prepare.
func IsK8sEnvironment ¶
func IsK8sEnvironment() bool
IsK8sEnvironment returns true if running in a K8s environment.
func IsQuadletEnvironment ¶
func IsQuadletEnvironment() bool
IsQuadletEnvironment returns true if running in a Quadlet environment.
func IsRemoteDeployment ¶
func IsRemoteDeployment() bool
IsRemoteDeployment returns true if testing against a remote deployment.
func MarshalEncryptionConfigIntoYAML ¶ added in v1.3.0
func MarshalEncryptionConfigIntoYAML(configYAML string, enc *internalconfig.EncryptionConfig) (string, error)
MarshalEncryptionConfigIntoYAML merges the given EncryptionConfig into the provided service config YAML string, replacing the existing encryption block (if any). Unrelated top-level keys are preserved.
func NormalizeEnvironmentType ¶
NormalizeEnvironmentType normalizes environment type strings.
func ParseBoolEnv ¶ added in v1.4.0
ParseBoolEnv reads an optional boolean environment variable. An unset or empty variable yields fallback; a value that is set but not a boolean is an error rather than a silent fallback.
func ParseEncryptionConfig ¶ added in v1.3.0
func ParseEncryptionConfig(configYAML string) (*internalconfig.EncryptionConfig, error)
ParseEncryptionConfig extracts the encryption block from a service config YAML string and returns a typed EncryptionConfig. If no encryption block is present (e.g. Quadlet with defaults baked in), it synthesizes the default — activeKeyID=default, path=EncryptionKeyDir/key.
func QueryDB ¶ added in v1.3.0
QueryDB executes a psql query against the flightctl PostgreSQL database and returns the trimmed output.
When the built-in flightctl-db pod/container is available (Helm db.type=builtin or Quadlet db.type=builtin), the query is executed via psql inside that pod using ExecInService. When the built-in workload is absent (external DB), the query is delegated to InfraProvider.QueryDBExternal, which uses a deployment-specific mechanism (a short-lived K8s Job or a direct pgx connection from the test binary).
func RequireEnvironment ¶
func RequireEnvironment(envType string)
RequireEnvironment fails the test if not running in the specified environment.
func RunCleanup ¶ added in v1.4.0
func RunCleanup(ctx context.Context, steps []CleanupStep) error
RunCleanup runs every step in order and returns the accumulated failures.
Unlike asserting after each action, a failing step does not abort the sequence: every remaining step still runs, so one broken teardown action cannot strand the rest of the suite's resources. All failures are joined and returned together, so the caller can fail the suite once with the full list rather than only the first problem.
ctx is passed to every step unchanged. An expired context does not stop the loop; each step decides how to handle it and reports its own error, which keeps the accumulated report complete instead of truncating at the first timeout.
func ServiceFailureObserver ¶ added in v1.4.0
func ServiceFailureObserver(ctx context.Context, lifecycle ServiceLifecycleProvider, logs ServiceLogProvider, service ServiceName, timeout time.Duration, tailLines int, expectedLog string) (string, error)
ServiceFailureObserver waits for both the expected startup error and a failed readiness check. A container without a readiness probe can briefly be ready before configuration validation exits, so initial readiness is not conclusive.
func SkipIfEnvironment ¶
SkipIfEnvironment skips the current test if running in the specified environment.
func SkipIfNotK8s ¶
func SkipIfNotK8s(reason ...string)
SkipIfNotK8s skips the current test if not running in a Kubernetes environment. Use this for tests that require Kubernetes-specific features (RBAC, etc.).
func SkipIfNotQuadlet ¶
func SkipIfNotQuadlet(reason ...string)
SkipIfNotQuadlet skips the current test if not running in a Quadlet environment. Use this for tests that require Quadlet-specific features.
func SkipIfObservabilityNotConfigured ¶ added in v1.3.0
SkipIfObservabilityNotConfigured skips the suite when infra cannot provide ServicePrometheus. Kind uses the auxiliary testcontainer instead and is not checked here.
func SkipIfRBACNotSupported ¶
func SkipIfRBACNotSupported(rbacProvider RBACProvider)
SkipIfRBACNotSupported skips the current test if RBAC provider is not available. Both K8s and PAM environments support RBAC, so this only checks for nil provider.
Types ¶
type CleanupStep ¶ added in v1.4.0
type CleanupStep struct {
// Name identifies the step in progress output and in the error returned
// by RunCleanup. It reads as the action, e.g. "uninstall the chart".
Name string
// Skip reports that this step has nothing to do, typically because the
// resource it removes was never created. A nil Skip means "always run".
Skip func() bool
// Run performs the cleanup. A non-nil error means suite-owned state may
// have been left behind and must surface as a suite failure.
Run func(ctx context.Context) error
}
CleanupStep is one teardown action a suite owes its environment.
Steps are ordered but independent: each one removes a different piece of suite-owned state, so a step that fails must not prevent the ones after it from running. Anything that genuinely depends on an earlier step belongs in that step's Run, not in a later entry.
type CollectorAvailability ¶ added in v1.4.0
type CollectorAvailability struct {
// Available reports that Start can be attempted.
Available bool
// Required reports that the run explicitly asked for a collector
// deployment, so an unavailable one must fail rather than skip.
Required bool
// Reason explains an unavailable deployment in terms a caller can print,
// both as a skip message and as a failure message. Empty when Available.
Reason string
}
CollectorAvailability reports whether a catalog collector can be deployed here, and what an unavailable deployment means for the run.
It is deliberately separate from the error a deployer returns. An error means the question could not be answered - a broken container runtime, an unparseable setting - and always fails the caller. This value answers the question successfully; Available simply says no.
type CollectorConfigContext ¶ added in v1.4.0
type CollectorConfigContext struct {
// FlightControlServer is the base URL of the Flight Control API as the
// collector reaches it from inside the deployment.
FlightControlServer string
// OAuthClientIDFile is where the deployment places
// CollectorDeploymentConfig.OAuthClientID.
OAuthClientIDFile string
// OAuthClientSecretFile is where the deployment places
// CollectorDeploymentConfig.OAuthClientSecret.
OAuthClientSecretFile string
// CertificateAuthorityFile is where the deployment places the Flight
// Control CA bundle it discovered, for the collector to verify the
// endpoint against.
CertificateAuthorityFile string
}
CollectorConfigContext is everything deployment-specific a caller needs in order to render a collector configuration: how the collector reaches Flight Control from inside the deployment, and where the deployment places the credentials and trust material it is handed.
These are paths and URLs inside the collector's own runtime, so they stay generic: a different deployment type answers with different values, and the caller never learns how either was produced.
type CollectorDeployer ¶ added in v1.4.0
type CollectorDeployer interface {
// Available reports whether a collector can be deployed here.
//
// A nil error with Available false is a settled answer: the caller skips,
// or fails when Required. A non-nil error means the question could not be
// answered and always fails the caller, so a broken environment is never
// silently reported as an unsupported one.
Available(ctx context.Context) (CollectorAvailability, error)
// ConfigContext returns the deployment-specific values a caller needs to
// render a collector configuration. It is called before Start, because its
// result is an input to the configuration Start is given.
ConfigContext(ctx context.Context) (CollectorConfigContext, error)
// Start deploys a collector and waits for it to come up.
//
// The returned instance is non-nil whenever anything was created, including
// when the error is non-nil: a start that failed partway still leaves state
// the caller has to tear down, and the instance is the only handle to it.
Start(ctx context.Context, config CollectorDeploymentConfig) (CollectorInstance, error)
}
CollectorDeployer deploys the catalog collector into the environment under test.
It is deliberately specific to the collector rather than a general deployment mechanism: every method exists because a caller needs exactly that answer, and none of them exposes how the deployment is actually performed. Callers never touch a container runtime, a cluster client, or a packaging tool.
func NewUnsupportedCollectorDeployer ¶ added in v1.4.0
func NewUnsupportedCollectorDeployer(deploymentType string) CollectorDeployer
NewUnsupportedCollectorDeployer returns a deployer that reports the catalog collector cannot be deployed on deploymentType.
type CollectorDeploymentConfig ¶ added in v1.4.0
type CollectorDeploymentConfig struct {
// InstanceID is a short logical identifier, unique per run, that the
// implementation derives its own object names from so concurrent runs and
// reruns against a reused deployment never collide.
InstanceID string
// Config is the collector configuration document to run.
Config []byte
// OAuthClientID and OAuthClientSecret are the client credentials the
// collector authenticates to Flight Control with. They are placed at the
// paths CollectorConfigContext reports.
OAuthClientID string
OAuthClientSecret string
// StartTimeout bounds starting the collector, including waiting for it to
// come up. Must be positive.
StartTimeout time.Duration
// StopTimeout bounds each step of stopping it. Must be positive.
StopTimeout time.Duration
}
CollectorDeploymentConfig is the generic input to one collector deployment.
It carries only what the caller owns: an identity for the instance, the configuration document to run, the credentials to mount, and the bounds on how long starting and stopping may take. Namespaces, releases, charts, images, selectors, and trust material are the implementation's business.
type CollectorImageSelection ¶ added in v1.4.0
type CollectorImageSelection struct {
// Reference is the image the run named, or empty when it named none.
Reference string
// Preloaded reports that Reference is already in the deployment's image
// store and must not be loaded from a local container runtime.
Preloaded bool
// Required reports that a missing image must fail rather than skip. An
// explicitly named image is required by default: whoever named it meant
// the collector to be deployed from it.
Required bool
}
CollectorImageSelection is the collector image policy the run was given. It is the generic half of image resolution: which image was named, whether the deployment already holds it, and whether its absence is fatal. Finding an image that was not named is deployment-specific and belongs to the implementation.
func CollectorImageFromEnv ¶ added in v1.4.0
func CollectorImageFromEnv() (CollectorImageSelection, error)
CollectorImageFromEnv reads the image policy the run was given.
A setting that is present but unparseable is an error rather than a silent default, because a typo there would quietly change how the run behaves.
type CollectorInstance ¶ added in v1.4.0
type CollectorInstance interface {
// WaitReady blocks until the collector reports itself ready, or the
// timeout elapses.
WaitReady(ctx context.Context, timeout time.Duration) error
// Logs returns the collector's most recent output, bounded to the last
// tailLines lines.
//
// Failures are returned rather than folded into the result: a caller that
// waits for the collector to report something has to be able to tell "not
// logged yet" from "the logs could not be read", and an empty,
// successful-looking result would conflate the two.
Logs(ctx context.Context, tailLines int64) (string, error)
// Diagnostics returns a best-effort, human-readable dump of the
// collector's state. It never fails: it is called on a failing path, where
// an error would replace the information the caller needs.
Diagnostics(ctx context.Context) string
// Stop takes the collector down so it can no longer act on anything.
//
// It answers two different questions through two channels, because they
// can disagree. stopped reports whether the collector is confirmed to be
// down, which is what a caller keys dependent teardown off. The error
// reports whether stopping left instance-owned state behind, which is a
// problem in its own right. An implementation that had to fall back to a
// blunter mechanism returns stopped true together with the original
// failure; only when nothing confirmed the collector is down is stopped
// false.
Stop(ctx context.Context) (stopped bool, err error)
// Cleanup removes whatever the instance still owns. It is idempotent and
// safe to call after Stop, after a failed Start, and more than once.
Cleanup(ctx context.Context) error
}
CollectorInstance is one deployed collector.
type DBConnectionParams ¶ added in v1.4.0
type DBConnectionParams struct {
Hostname string
Port string
DBName string
User string
Password string
SSLMode string
SSLRootCert string // path to the CA cert file on the deployment host (may be remote)
SSLCert string // path to the client cert file on the deployment host
SSLKey string // path to the client key file on the deployment host
}
DBConnectionParams holds the parameters needed to connect to the flightctl PostgreSQL database. Used by QueryDBExternal to reach an external DB when the built-in flightctl-db pod is unavailable.
func ParseDBParamsFromAPIConfig ¶ added in v1.4.0
func ParseDBParamsFromAPIConfig(raw string) (DBConnectionParams, error)
ParseDBParamsFromAPIConfig parses database connection parameters from the raw YAML content of the API service config (the "database" block). It applies defaults for port (5432) and dbname (flightctl), and validates that hostname is present. Provider-specific credential fields (user, password) are left empty if absent — each provider fills them from its own secret source.
type EnvironmentConfig ¶
type EnvironmentConfig struct {
// Type is the environment type: "kind", "ocp", or "quadlet"
Type string
// Namespace is the K8s namespace for flightctl services (K8s only)
Namespace string
// APIEndpoint is the FlightCtl API endpoint URL (e.g., "https://api.flightctl.example.com")
APIEndpoint string
// KubeConfig is the path to kubeconfig file (K8s only, defaults to ~/.kube/config)
KubeConfig string
// KubeContext is the kubeconfig context to use (K8s only)
KubeContext string
// SSHHost is the remote host for Quadlet deployments (Quadlet only, for remote testing)
SSHHost string
// SSHUser is the SSH username for remote Quadlet deployments
SSHUser string
// SSHKeyPath is the path to SSH private key for remote Quadlet deployments
SSHKeyPath string
// UseSudo indicates whether to use sudo for systemctl/podman commands (Quadlet only)
UseSudo bool
// ConfigDir is the config directory for Quadlet deployments (defaults to /etc/flightctl)
ConfigDir string
}
EnvironmentConfig holds configuration for the test environment. Values can be set via environment variables or programmatically.
func GetConfig ¶
func GetConfig() *EnvironmentConfig
GetConfig returns the environment configuration from the default factory.
func GetEnvironmentConfig ¶
func GetEnvironmentConfig() *EnvironmentConfig
GetEnvironmentConfig reads configuration from environment variables.
func (*EnvironmentConfig) GetAPIEndpoint ¶
func (c *EnvironmentConfig) GetAPIEndpoint() string
GetAPIEndpoint returns the API endpoint, using defaults if not explicitly set. For K8s: checks API_ENDPOINT env var (set by run_e2e_tests.sh from K8s route) For Quadlet: defaults to https://<host-ip> (uses host IP so VMs can reach it)
func (*EnvironmentConfig) GetConfigDir ¶
func (c *EnvironmentConfig) GetConfigDir() string
GetConfigDir returns the config directory, using defaults if not set.
func (*EnvironmentConfig) GetNamespace ¶
func (c *EnvironmentConfig) GetNamespace() string
GetNamespace returns the namespace from config (E2E_NAMESPACE or FLIGHTCTL_NS). Returns empty string when not set; K8s providers then detect from cluster (flightctl-api / flightctl-worker pods).
func (*EnvironmentConfig) IsRemote ¶
func (c *EnvironmentConfig) IsRemote() bool
IsRemote returns true if this is a remote deployment (has SSHHost or external API endpoint).
type InfraProvider ¶
type InfraProvider interface {
// GetConfigValue retrieves a configuration value by name and key.
// For K8s: reads from ConfigMap
// For Quadlet: reads from config files or environment variables
GetConfigValue(name, key string) (string, error)
// GetServiceConfig retrieves the full configuration content for a service.
// For K8s: reads from ConfigMap data (e.g., config.yaml key)
// For Quadlet: reads the config file from container or host
GetServiceConfig(service ServiceName) (string, error)
// GetSecretValue retrieves a secret value by name and key.
// For K8s: reads from Secret (base64 decoded)
// For Quadlet: reads from secret files or environment variables
GetSecretValue(name, key string) (string, error)
// GetServiceEndpoint returns the host and port for a named service.
// For K8s: returns in-cluster DNS name and port (not directly accessible from test host)
// For Quadlet: returns the configured host with the service's port
GetServiceEndpoint(service ServiceName) (host string, port int, err error)
// ExposeService makes an internal service accessible from the test host.
// Use this for services not normally exposed externally (e.g., metrics endpoints).
// For K8s: starts port-forwarding and returns localhost URL + cleanup function
// For Quadlet: returns direct URL + no-op cleanup (internal services accessible on host)
// The cleanup function must be called when done (e.g., defer cleanup()).
ExposeService(service ServiceName, protocol string) (url string, cleanup func(), err error)
// InvalidateExposeCache closes any cached port-forward for the service and removes it from the cache.
// Call before retrying ExposeService so the next call creates a new port-forward (e.g. after Redis restart).
InvalidateExposeCache(service ServiceName)
// ExecInService executes a command in the context of a service.
// For K8s: kubectl exec into the service's pod
// For Quadlet: direct command execution or SSH
ExecInService(service ServiceName, command []string) (string, error)
// ExecInServiceWithStdin executes a command in the context of a service with stdin attached.
// Used e.g. to pipe a backup file into psql during DB restore.
// For K8s: kubectl exec -i into the service's pod
// For Quadlet: podman exec -i (and stdin piped through SSH when remote)
ExecInServiceWithStdin(service ServiceName, command []string, stdin io.Reader) (string, error)
// GetEnvironmentType returns the type of environment ("kind", "ocp", "quadlet").
GetEnvironmentType() string
// GetAPILoginToken returns a token suitable for flightctl login --token.
// For K8s/KIND: kubectl create token in main namespace; OCP: oc whoami -t.
// For Quadlet: read from file or return error. Namespace is internal to the provider.
GetAPILoginToken() (string, error)
// SetServiceConfig writes back config for a service (e.g. config.yaml in ConfigMap).
// For K8s: updates ConfigMap data[configKey]. For Quadlet: single config file per
// service; configKey is ignored (callers may pass "" or "config.yaml").
SetServiceConfig(service ServiceName, configKey, content string) error
// GetInternalNamespace returns the namespace where internal services (worker, db, kv, etc.) run.
// For K8s: e.g. flightctl-internal when using split namespaces; empty when all in one namespace.
// For Quadlet: empty.
GetInternalNamespace() string
// GetExternalNamespace returns the namespace where external services (API, UI, etc.) run (release namespace).
// For K8s: the namespace where flightctl-api is deployed; used e.g. for io.flightctl/instance label.
// For Quadlet: empty.
GetExternalNamespace() string
// BuiltinDatabaseWorkloadAvailable reports whether backup/restore tests can pg_dump/psql via the
// built-in DB workload: K8s checks for a flightctl-db pod (Helm db.type=builtin); external Helm DB
// has no such pod. Quadlet reads db.type from service-config.yaml (deploy/podman/service-config.yaml);
// db.type=external uses an external Postgres instance instead of the flightctl-db container.
BuiltinDatabaseWorkloadAvailable() bool
// ServiceExists reports whether the deployment-specific resource for a logical service is present.
// For K8s: checks the Service object exists. For Quadlet: checks the systemd unit is active.
ServiceExists(ctx context.Context, service ServiceName) (bool, error)
// SetEncryptionKey writes a named encryption key so it is available to the given service.
// For K8s: patches the flightctl-encryption-key Secret to add/update the key entry, then
// triggers a rollout restart of the service's deployment so the new Secret is mounted.
// For Quadlet: writes the key file directly to the host filesystem at the encryption key directory.
// keyFileName is the base name of the key file (e.g. "key-rotated-key").
// keyBytes is the raw key material to store.
SetEncryptionKey(service ServiceName, keyFileName string, keyBytes []byte) error
// ResetEncryptionKeys removes all non-default encryption key files, leaving only the
// original "key" file (the deployment default). Used by test recovery to undo key rotation.
// For K8s: replaces the flightctl-encryption-key Secret's data with only the "key" entry.
// For Quadlet: removes all key-* files from the encryption key directory.
ResetEncryptionKeys() error
// GetEncryptionConfig reads the current encryption block from the service's config.
// Returns the parsed EncryptionConfig. If the service config has no encryption block
// (e.g. Quadlet with defaults baked in), returns a synthesized default config with
// activeKeyID=default and path=EncryptionKeyDir/key.
// For K8s: reads ConfigMap config.yaml. For Quadlet: reads the service config file.
GetEncryptionConfig(service ServiceName) (*internalconfig.EncryptionConfig, error)
// SetEncryptionConfig writes the given encryption block into the service's config,
// merging it with any existing top-level keys so unrelated settings are preserved.
// For K8s: updates ConfigMap data["config.yaml"]. For Quadlet: writes per-service config.
SetEncryptionConfig(service ServiceName, enc *internalconfig.EncryptionConfig) error
// GetDBConnectionParams returns the parameters needed to connect to the flightctl database.
// For K8s: reads hostname/port/name from the API ConfigMap and user/password from the
// flightctl-db-app-secret Secret. For Quadlet: reads from the API service config file
// and from secret files or environment variables.
// Used by QueryDBExternal to reach an external DB when the built-in pod is unavailable.
GetDBConnectionParams() (DBConnectionParams, error)
// QueryDBExternal executes a SQL query against the flightctl database without relying on
// the built-in flightctl-db pod. Used when BuiltinDatabaseWorkloadAvailable() is false.
// For K8s: spawns a short-lived batch/v1 Job running psql in the cluster.
// For Quadlet: connects directly via pgx using TCP to the database host.
QueryDBExternal(sql string) (string, error)
// ApplyDeltaWorkerRegistryRemap writes containers/image remaps so the delta
// worker and render worker rewrite quay.io/flightctl refs to the e2e registry.
// Callers restart those services via Lifecycle.
// For K8s: ConfigMap mounted at /etc/containers/registries.conf.d and certs.d (not baked into Helm).
// For Quadlet: files under /etc/flightctl/flightctl-delta-worker and /etc/flightctl/flightctl-worker.
// ctx cancels the remap operations if the E2E setup is canceled.
ApplyDeltaWorkerRegistryRemap(ctx context.Context, registryURL string) error
}
InfraProvider abstracts infrastructure access for different deployment environments. K8s implementations use kubectl/client-go, Quadlet implementations use systemctl and files.
type Permission ¶
type Permission struct {
Resources []string
Verbs []string
ApiGroup string // K8s: CoreAPIGroup for core (e.g. secrets), "" defaults to flightctl.io; PAM ignores
}
Permission defines access to resources. K8s uses Resources, Verbs, and ApiGroup to build PolicyRules (ApiGroup "" is core API). PAM ignores this (permissions are implicit based on role name).
type ProviderFactory ¶
type ProviderFactory struct {
// contains filtered or unexported fields
}
ProviderFactory creates providers based on environment detection.
func NewProviderFactory ¶
func NewProviderFactory() *ProviderFactory
NewProviderFactory creates a new provider factory.
func NewProviderFactoryWithConfig ¶
func NewProviderFactoryWithConfig(config *EnvironmentConfig) *ProviderFactory
NewProviderFactoryWithConfig creates a provider factory with explicit configuration.
func (*ProviderFactory) DetectEnvironment ¶
func (f *ProviderFactory) DetectEnvironment() string
DetectEnvironment determines the current environment type. Priority: E2E_ENVIRONMENT env var > auto-detection
func (*ProviderFactory) GetConfig ¶
func (f *ProviderFactory) GetConfig() *EnvironmentConfig
GetConfig returns the environment configuration.
func (*ProviderFactory) IsK8sEnvironment ¶
func (f *ProviderFactory) IsK8sEnvironment() bool
IsK8sEnvironment returns true if the current environment is Kubernetes-based.
func (*ProviderFactory) IsQuadletEnvironment ¶
func (f *ProviderFactory) IsQuadletEnvironment() bool
IsQuadletEnvironment returns true if the current environment is Quadlet-based.
type Providers ¶
type Providers struct {
Infra InfraProvider
Lifecycle ServiceLifecycleProvider
RBAC RBACProvider
Secrets SecretsProvider
TPM TPMProvider
// CollectorDeployment deploys the catalog collector into the environment
// under test. It is always populated: a deployment type that cannot host a
// collector gets an implementation whose Available says so, so callers ask
// the same question everywhere instead of branching on the deployment type
// or on a nil provider.
CollectorDeployment CollectorDeployer
}
Providers holds all the infrastructure providers for a test environment. Create once at harness/suite creation via infra/setup.NewProvidersForEnvironment or setup.EnsureDefaultProviders; after that use the interface methods (e.g. GetSecretsProvider().GetSecretData) without further environment checks. Methods that are not supported in an implementation (e.g. GetSecretData on Quadlet) return an error (e.g. ErrSecretsNotSupported); callers handle that instead of branching on implementation type.
type RBACProvider ¶
type RBACProvider interface {
// CreateRole creates a role.
// K8s: creates rbacv1.Role in namespace
// PAM: creates group "<namespace>.<name>" if namespace provided, else "<name>"
CreateRole(ctx context.Context, spec *RoleSpec) error
// UpdateRole updates a role.
// K8s: updates rbacv1.Role
// PAM: no-op (groups don't have permissions)
UpdateRole(ctx context.Context, spec *RoleSpec) error
// DeleteRole deletes a role.
// K8s: deletes rbacv1.Role
// PAM: deletes group "<namespace>.<name>" or "<name>"
DeleteRole(ctx context.Context, namespace, name string) error
// CreateRoleBinding binds a user to a role.
// K8s: creates rbacv1.RoleBinding
// PAM: adds user to group via usermod -aG
CreateRoleBinding(ctx context.Context, spec *RoleBindingSpec) error
// DeleteRoleBinding removes a user from a role.
// K8s: deletes rbacv1.RoleBinding
// PAM: removes user from group via gpasswd -d
DeleteRoleBinding(ctx context.Context, namespace, name string) error
// CreateClusterRole creates a cluster-scoped role.
// K8s: creates rbacv1.ClusterRole
// PAM: creates group "<name>" (no namespace prefix)
CreateClusterRole(ctx context.Context, spec *RoleSpec) error
// UpdateClusterRole updates a cluster-scoped role.
// K8s: updates rbacv1.ClusterRole
// PAM: no-op (groups don't have permissions)
UpdateClusterRole(ctx context.Context, spec *RoleSpec) error
// DeleteClusterRole deletes a cluster-scoped role.
// K8s: deletes rbacv1.ClusterRole
// PAM: deletes group "<name>"
DeleteClusterRole(ctx context.Context, name string) error
// CreateClusterRoleBinding binds a user to a cluster role.
// K8s: creates rbacv1.ClusterRoleBinding
// PAM: adds user to group via usermod -aG
CreateClusterRoleBinding(ctx context.Context, spec *RoleBindingSpec) error
// DeleteClusterRoleBinding removes a user from a cluster role.
// K8s: deletes rbacv1.ClusterRoleBinding
// PAM: removes user from group via gpasswd -d
DeleteClusterRoleBinding(ctx context.Context, name string) error
// CreateOrganization creates an organization (K8s: namespace with release label; PAM: org-<name> group).
CreateOrganization(ctx context.Context, name string) error
// AddUserToOrg grants the user access to the organization (K8s: view RoleBinding in namespace; PAM: add user to org-<name> group).
AddUserToOrg(ctx context.Context, orgName, userName string) error
// DeleteOrganization deletes an organization (K8s: namespace; PAM: org-<name> group).
DeleteOrganization(ctx context.Context, name string) error
}
RBACProvider abstracts RBAC operations for different environments. K8s implementations use the RBAC API, PAM implementations use Linux groups.
type RoleBindingSpec ¶
type RoleBindingSpec struct {
Name string
Namespace string // empty for cluster-scoped
RoleName string
Subject string // user name or service account name
// SubjectKind: "User" (default) or "ServiceAccount"
SubjectKind string
// SubjectNamespace: required when SubjectKind is ServiceAccount (namespace of the SA)
SubjectNamespace string
}
RoleBindingSpec binds a subject (user or service account) to a role.
type RoleSpec ¶
type RoleSpec struct {
Name string
Namespace string // empty for cluster-scoped
Permissions []Permission
}
RoleSpec defines a role with permissions.
type SecretsProvider ¶
type SecretsProvider interface {
// GetSecretData returns the value of a key in a secret.
// Namespace and secretName identify the secret; key is the data key.
// Returns decoded bytes (K8s API returns Secret.Data already decoded).
GetSecretData(ctx context.Context, namespace, secretName, key string) ([]byte, error)
// GetSecretDataForService returns the value of a key in a secret for the given service.
// K8s: resolves service to namespace internally. Quadlet: returns ErrSecretsNotSupported.
GetSecretDataForService(ctx context.Context, service ServiceName, secretName, key string) ([]byte, error)
// CreateSecret creates a secret with the given namespace, name, and string data (key -> value).
// K8s: creates a Secret with StringData; idempotent (no-op if already exists with same data or update as needed).
// Quadlet: returns ErrSecretsNotSupported.
CreateSecret(ctx context.Context, namespace, name string, stringData map[string]string) error
}
SecretsProvider abstracts secret access for different environments. K8s: reads from Kubernetes Secret API. Quadlet: not supported; GetSecretData returns an error so callers fall back to file/infra paths.
type ServiceLifecycleProvider ¶
type ServiceLifecycleProvider interface {
// IsRunning checks if a service is currently running.
// For K8s: checks pod phase is Running
// For Quadlet: checks systemctl is-active
IsRunning(service ServiceName) (bool, error)
// Start starts a stopped service.
// For K8s: scales deployment to 1 replica
// For Quadlet: systemctl start
Start(service ServiceName) error
// Stop stops a running service.
// For K8s: scales deployment to 0 replicas
// For Quadlet: systemctl stop
Stop(service ServiceName) error
// Restart restarts a service.
// For K8s: deletes the pod to force restart
// For Quadlet: systemctl restart
Restart(service ServiceName) error
// WaitForReady waits for a service to be ready and healthy.
// For K8s: waits for pod Ready condition
// For Quadlet: waits for systemctl is-active and optionally health checks
WaitForReady(service ServiceName, timeout time.Duration) error
// AreServicesHealthy checks if all flightctl services are healthy.
// For K8s: checks all deployments have ready replicas
// For Quadlet: checks all systemd services are active
AreServicesHealthy() (bool, error)
// SetDeploymentEnv sets an environment variable on a service's deployment
// and waits for the rollout to complete.
// For K8s: patches the deployment container spec and waits for rollout
// For Quadlet: creates a Quadlet container drop-in override and restarts the service
SetDeploymentEnv(service ServiceName, envName, envValue string) error
// RemoveDeploymentEnv removes an environment variable from a service's
// deployment and waits for the rollout to complete.
// For K8s: removes the env var from the deployment container spec and waits for rollout
// For Quadlet: removes the env var from the container drop-in override and restarts the service
RemoveDeploymentEnv(service ServiceName, envName string) error
}
ServiceLifecycleProvider abstracts service lifecycle management for different environments. K8s implementations use kubectl scale/delete, Quadlet implementations use systemctl.
type ServiceLogProvider ¶ added in v1.4.0
type ServiceLogProvider interface {
GetServiceLogs(ctx context.Context, service ServiceName, tailLines int) (string, error)
}
ServiceLogProvider retrieves recent logs for a Flight Control service in the active deployment environment.
type ServiceName ¶
type ServiceName string
ServiceName is a type-safe identifier for flightctl services.
const ( ServiceRedis ServiceName = "redis" ServiceAPI ServiceName = "api" ServiceWorker ServiceName = "worker" ServiceDeltaWorker ServiceName = "delta-worker" ServicePeriodic ServiceName = "periodic" ServiceTelemetryGateway ServiceName = "telemetry-gateway" ServiceUI ServiceName = "ui" ServiceDB ServiceName = "db" ServiceAlertmanager ServiceName = "alertmanager" ServiceAlertmanagerProxy ServiceName = "alertmanager-proxy" ServiceImageBuilderAPI ServiceName = "imagebuilder-api" ServiceImageBuilderWorker ServiceName = "imagebuilder-worker" ServiceAlertExporter ServiceName = "alert-exporter" ServicePrometheus ServiceName = "prometheus" )
ServiceName constants for logical service names. Use these constants when calling InfraProvider methods that accept ServiceName.
func ServiceNameFromDeploymentName ¶
func ServiceNameFromDeploymentName(name string) (ServiceName, bool)
ServiceNameFromDeploymentName returns the ServiceName for a deployment/service name string, or false if unknown.
type TPMProvider ¶
type TPMProvider interface {
// InjectCerts configures TPM CA certificates for the API server.
// certs is a map of filename -> PEM certificate data.
// The implementation handles all environment-specific details:
// - K8s: creates ConfigMap, updates API config with tpmCAPaths, adds volume mount, restarts deployment
// - Quadlet: writes certs to config directory, updates config file, restarts service
InjectCerts(ctx context.Context, certs map[string][]byte) error
// CleanupCerts removes TPM CA certificates from the API server configuration.
// - K8s: deletes ConfigMap, removes volume mount from deployment, restarts deployment
// - Quadlet: removes cert files, updates config to remove tpmCAPaths, restarts service
CleanupCerts(ctx context.Context) error
}
TPMProvider abstracts TPM certificate management for different environments. K8s: creates ConfigMap, updates API config, adds volume mount, restarts deployment. Quadlet: writes certs to config directory, updates config file, restarts service.
type TracingProvider ¶
type TracingProvider struct {
// contains filtered or unexported fields
}
TracingProvider starts/stops the tracing aux container and configures flightctl services accordingly.
func NewTracingProvider ¶
func NewTracingProvider(infra InfraProvider, lifecycle ServiceLifecycleProvider) *TracingProvider
NewTracingProvider returns a TracingProvider that uses the given infra and lifecycle.
func (*TracingProvider) StartTracing ¶
StartTracing starts the tracing aux container and configures flightctl services to report to it.
func (*TracingProvider) StopTracing ¶
func (p *TracingProvider) StopTracing() error
StopTracing reconfigures flightctl services to disable tracing, then stops the tracing aux container.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auxiliary provides shared testcontainer-based services for E2E tests.
|
Package auxiliary provides shared testcontainer-based services for E2E tests. |
|
cmd
|
|
|
push-e2e-images
command
|
|
|
Package k8s provides Kubernetes-specific implementations of the infra providers.
|
Package k8s provides Kubernetes-specific implementations of the infra providers. |
|
Package quadlet provides Quadlet/systemd-specific implementations of the infra providers.
|
Package quadlet provides Quadlet/systemd-specific implementations of the infra providers. |
|
Package redis provides Redis and queue helpers for e2e tests using infra providers.
|
Package redis provides Redis and queue helpers for e2e tests using infra providers. |
|
Package setup provides provider factory and default-providers for e2e tests.
|
Package setup provides provider factory and default-providers for e2e tests. |