util

package
v1.2.0-rc1 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: Apache-2.0 Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Device                    = "device"
	Fleet                     = "fleet"
	EnrollmentRequest         = "enrollmentrequest"
	Repository                = "repository"
	ResourceSync              = "resourcesync"
	CertificateSigningRequest = "certificatesigningrequest"
	ImageBuild                = "imagebuild"
	ImageExport               = "imageexport"

	//resource related
	ApplyAction    = "apply"
	DenyAction     = "deny"
	DeviceResource = "Device"
	RepoResource   = "Repository"
	ErResource     = "EnrollmentRequest"
	FleetResource  = "Fleet"
	SystemResource = "System"

	//example yaml names
	DeviceYAMLName = "device.yaml"
	FleetYAMLName  = "fleet.yaml"
	FleetBYAMLName = "fleet-b.yaml"
	RepoYAMLName   = "repository-flightctl.yaml"
	ErYAMLName     = "enrollmentrequest.yaml"

	// events
	ForceFlag    = "-f"
	EventCreated = "created"
	EventDeleted = "deleted"
	EventUpdated = "updated"

	//Event reasons
	ResourceCreated          = "ResourceCreated"
	DeviceApplicationError   = "DeviceApplicationError"
	DeviceApplicationHealthy = "DeviceApplicationHealthy"
	DeviceSpecInvalid        = "DeviceSpecInvalid"
	DeviceSpecValid          = "DeviceSpecValid"
	DeviceContentOutOfDate   = "DeviceContentOutOfDate"
	DeviceContentUpToDate    = "DeviceContentUpToDate"
	DeviceUpdateFailed       = "DeviceUpdateFailed"

	// Eventually polling timeout/interval constants
	TIMEOUT      = time.Minute
	LONG_TIMEOUT = 10 * time.Minute
	POLLING      = time.Second
	LONG_POLLING = 10 * time.Second

	DURATION_TIMEOUT       = 5 * time.Minute
	EVENTUALLY_POLLING_250 = 250 * time.Millisecond // Used by Ginkgo SetDefaultEventuallyPollingInterval (e.g. quadlets, rootless)
	REBOOT_WAIT_INTERVAL   = 15 * time.Second       // Interval between reboot attempts in RebootVMAndWaitForSSH (e.g. quadlets, rootless)
	REBOOT_MAX_ATTEMPTS    = 5                      // Max attempts in RebootVMAndWaitForSSH (e.g. quadlets, rootless)
	SHORT_POLLING          = "250ms"
	SPECK_UPDATE_DELAY     = 10 * time.Second // Delay between back-to-back spec updates to avoid TCP port TIME_WAIT / bind race (EDM-3451)
	TIMEOUT_5M             = "5m"
	LONGTIMEOUT            = "10m"

	HTTP_403_ERROR = 403
	HTTP_404_ERROR = 404

	DefaultOrgLabel = "flightctl"
	OrgLabelEnvVar  = "FLIGHTCTL_ORG_LABEL"
	OrgLabelKey     = "io.flightctl/instance"
)

Resource types

View Source
const DeviceImageRegistryPath = "flightctl/flightctl-device"

DeviceImageRegistryPath is the path segment used when pushing/pulling the device image to/from a local registry (e.g. auxiliary). Same as "flightctl/flightctl-device"; full ref is registryHost:port/DeviceImageRegistryPath:tag.

View Source
const E2E_NAMESPACE = "flightctl-e2e"
View Source
const E2E_REGISTRY_NAME = "registry"
View Source
const FLIGHTCTL_AGENT_SERVICE = "flightctl-agent"
View Source
const (
	ImageRepo = "quay.io/flightctl"
)
View Source
const KIND = "KIND"
View Source
const OCP = "OCP"
View Source
const QUADLET = "QUADLET"
View Source
const SleepAppRegistryPath = "flightctl/sleep-app"

SleepAppRegistryPath is the path segment for the sleep-app image in a local registry (e.g. auxiliary). Full ref is registryHost:port/SleepAppRegistryPath:tag.

Variables

View Source
var (
	DeviceIDKey    = DeviceIDKeyType{}
	DeviceKey      = DeviceKeyType{}
	TestContextKey = TestContextKeyType{}
)
View Source
var DefaultSystemInfo = []string{
	"hostname",
	"kernel",
	"distroName",
	"distroVersion",
	"productName",
	"productUuid",
	"productSerial",
	"netInterfaceDefault",
	"netIpDefault",
	"netMacDefault",
}

RequiredSystemInfoKeys defines the required system info keys that should be present

View Source
var DeviceTags = versionTags{
	V1:   "v1",
	V2:   "v2",
	V3:   "v3",
	V4:   "v4",
	V5:   "v5",
	V6:   "v6",
	V7:   "v7",
	V8:   "v8",
	V9:   "v9",
	V10:  "v10",
	V11:  "v11",
	V12:  "v12",
	Base: "base",
}
View Source
var ImageNames = imageNames{
	Device:   "flightctl-device",
	SleepApp: "sleep-app",
}
View Source
var SleepAppTags = sleepAppTags{
	V1: "v1",
	V2: "v2",
	V3: "v3",
}
View Source
var TestIDKey = TestIDKeyType{}

Functions

func BinaryExistsOnPath added in v0.8.1

func BinaryExistsOnPath(binaryName string) bool

func BuildInlineConfigSpec added in v1.1.0

func BuildInlineConfigSpec(name, filePath, content, user string) (api.ConfigProviderSpec, error)

func CleanupTempYAMLFile added in v0.10.0

func CleanupTempYAMLFile(tempFilePath string)

CleanupTempYAMLFile removes the temporary YAML file

func CleanupTempYAMLFiles added in v0.10.0

func CleanupTempYAMLFiles(tempFilePaths []string)

CleanupTempYAMLFiles removes multiple temporary YAML files

func CopyFile added in v1.1.0

func CopyFile(src, dst string) error

CopyFile copies a file from src to dst, creating the destination directory if it does not exist.

func CreateRepositories

func CreateRepositories(ctx context.Context, numRepositories int, storeInst store.Store, orgId uuid.UUID) error

func CreateTestAuthProvider added in v1.0.0

func CreateTestAuthProvider(ctx context.Context, authStore store.AuthProvider, orgId uuid.UUID, name string, issuer string, labels *map[string]string)

CreateTestAuthProvider creates a test auth provider in the store

func CreateTestAuthProviderWithDynamicOrg added in v1.0.0

func CreateTestAuthProviderWithDynamicOrg(ctx context.Context, authStore store.AuthProvider, orgId uuid.UUID, name string)

CreateTestAuthProviderWithDynamicOrg creates a test OIDC provider with dynamic organization assignment

func CreateTestAuthProviderWithPerUserOrg added in v1.0.0

func CreateTestAuthProviderWithPerUserOrg(ctx context.Context, authStore store.AuthProvider, orgId uuid.UUID, name string, prefix *string, suffix *string)

CreateTestAuthProviderWithPerUserOrg creates a test OIDC provider with per-user organization assignment

func CreateTestAuthProviderWithStaticOrg added in v1.0.0

func CreateTestAuthProviderWithStaticOrg(ctx context.Context, authStore store.AuthProvider, orgId uuid.UUID, name string, orgName string)

CreateTestAuthProviderWithStaticOrg creates a test OIDC provider with static organization assignment

func CreateTestAuthProviders added in v1.0.0

func CreateTestAuthProviders(ctx context.Context, numProviders int, authStore store.AuthProvider, orgId uuid.UUID, sameVals bool)

CreateTestAuthProviders creates multiple test auth providers

func CreateTestAuthProvidersWithOffset added in v1.0.0

func CreateTestAuthProvidersWithOffset(ctx context.Context, numProviders int, authStore store.AuthProvider, orgId uuid.UUID, sameVals bool, offset int)

CreateTestAuthProvidersWithOffset creates multiple test OIDC providers with an offset

func CreateTestDevice

func CreateTestDevice(ctx context.Context, deviceStore store.Device, orgId uuid.UUID, name string, owner *string, tv *string, labels *map[string]string)

func CreateTestDevices

func CreateTestDevices(ctx context.Context, numDevices int, deviceStore store.Device, orgId uuid.UUID, owner *string, sameVals bool)

func CreateTestDevicesWithOffset

func CreateTestDevicesWithOffset(ctx context.Context, numDevices int, deviceStore store.Device, orgId uuid.UUID, owner *string, sameVals bool, offset int)

func CreateTestEnrolmentRequests added in v0.8.1

func CreateTestEnrolmentRequests(numEnrollmentRequests int, ctx context.Context, store store.Store, orgId uuid.UUID)

func CreateTestFleet

func CreateTestFleet(ctx context.Context, fleetStore store.Fleet, orgId uuid.UUID, name string, selector *map[string]string, owner *string)

func CreateTestFleets

func CreateTestFleets(ctx context.Context, numFleets int, fleetStore store.Fleet, orgId uuid.UUID, namePrefix string, sameVals bool, owner *string)

func CreateTestOrganization added in v0.9.0

func CreateTestOrganization(ctx context.Context, storeInst store.Store, orgId uuid.UUID) error

func CreateTestOrganizationAssignment added in v1.0.0

func CreateTestOrganizationAssignment() api.AuthOrganizationAssignment

CreateTestOrganizationAssignment creates a test organization assignment

func CreateTestResourceSyncs added in v0.8.1

func CreateTestResourceSyncs(ctx context.Context, numResourceSyncs int, storeInst store.Store, orgId uuid.UUID)

func CreateTestTemplateVersion

func CreateTestTemplateVersion(ctx context.Context, tvStore store.TemplateVersion, orgId uuid.UUID, fleet, name string, status *api.TemplateVersionStatus) error

func CreateTestTemplateVersions

func CreateTestTemplateVersions(ctx context.Context, numTemplateVersions int, tvStore store.TemplateVersion, orgId uuid.UUID, fleet string) error

func CreateUniqueYAMLFile added in v0.10.0

func CreateUniqueYAMLFile(originalYAMLPath, testID string) (string, error)

CreateUniqueYAMLFile creates a temporary YAML file with unique resource names based on test ID

func EventuallySlow added in v0.10.0

func EventuallySlow(actual any) types.AsyncAssertion

func GetCurrentYearBounds added in v0.7.0

func GetCurrentYearBounds() (string, string)

GetCurrentYearBounds returns start of current and next year in RFC3339 format.

func GetEnrollmentIdFromText added in v0.2.0

func GetEnrollmentIdFromText(text string) string

GetEnrollmentIdFromText returns the enrollment ID from the given text. The enrollment ID is expected to be part of url path like https://example.com/enroll/1234

func GetExtIP

func GetExtIP() string

func GetJournalLogs added in v1.0.0

func GetJournalLogs(serviceName string, since string) (string, error)

GetJournalLogs retrieves systemd journal logs for a service

func GetScriptPath

func GetScriptPath(script string) string

func GetSystemdStatus added in v1.0.0

func GetSystemdStatus(pattern string) (string, error)

GetSystemdStatus gets the status of systemd units matching a pattern

func GetTestExamplesYamlPath added in v0.6.0

func GetTestExamplesYamlPath(yamlName string) string

func GetTopLevelDir

func GetTopLevelDir() string

func InitLogsWithDebug added in v1.0.0

func InitLogsWithDebug() *logrus.Logger

InitLogsWithDebug creates a logger with debug level if LOG_LEVEL=debug is set

func InitSuiteTracerForGinkgo added in v0.8.1

func InitSuiteTracerForGinkgo(description string) context.Context

func InitTracerForTests added in v0.8.1

func InitTracerForTests() func(context.Context) error

func IntegrationRedisPassword added in v1.2.0

func IntegrationRedisPassword() domain.SecureString

IntegrationRedisPassword returns the Redis password for integration tests. Note: IntegrationRedisHost/Port/Addr functions have been removed because there is no longer a shared Redis container. Each test suite should create its own ephemeral Redis using testdb.CreateTestRedis() and use the returned host/port directly.

func IsAcmInstalled added in v0.10.0

func IsAcmInstalled() (bool, bool, error)

IsAcmInstalled checks if ACM is installed and if it is running. returns: isAcmInstalled, isAcmRunning, error

func IsRPMInstalled added in v1.0.0

func IsRPMInstalled(packageName string) (bool, string, error)

IsRPMInstalled checks if an RPM package is installed and returns its version

func ListSystemdUnits added in v1.0.0

func ListSystemdUnits(pattern string) ([]string, error)

ListSystemdUnits lists all systemd units matching a pattern

func NewAgentClient

func NewAgentClient(serverUrl string, caBundle []*x509.Certificate, clientCert *crypto.TLSCertificateConfig) (*agentclient.ClientWithResponses, error)

NewClient creates a new client with the given server URL and certificates. If the certs are nil a http client will be created.

func NewBackoff added in v0.6.0

func NewBackoff() wait.Backoff

func NewBareHTTPsClient

func NewBareHTTPsClient(caBundle []*x509.Certificate, clientCert *crypto.TLSCertificateConfig) (*http.Client, error)

func NewClient

func NewClient(serverUrl string, caBundle []*x509.Certificate) (*client.ClientWithResponses, error)

NewClient creates a new client with the given server URL and certificates. If the certs are nil a http client will be created.

func NewComposeSpec added in v0.6.0

func NewComposeSpec(images ...string) string

func NewPollConfig added in v0.9.0

func NewPollConfig() poll.Config

func NewTestAgentServer

func NewTestAgentServer(ctx context.Context, log logrus.FieldLogger, cfg *config.Config, store store.Store, ca *crypto.CAClient, serverCerts *crypto.TLSCertificateConfig, queuesProvider queues.Provider) (*agentserver.AgentServer, net.Listener, error)

NewTestAgentServer creates a new test server and returns the server and the listener listening on localhost's next available port.

func NewTestApiServer

func NewTestApiServer(log logrus.FieldLogger, cfg *config.Config, store store.Store, ca *crypto.CAClient, serverCerts *crypto.TLSCertificateConfig, queuesProvider queues.Provider) (*apiserver.Server, net.Listener, error)

NewTestApiServer creates a new test server and returns the server and the listener listening on localhost's next available port.

func NewTestCerts

NewTestCerts creates new test certificates in the service certstore and returns the CA, server certificate, and enrollment certificate.

func NewTestProvider

func NewTestProvider(log logrus.FieldLogger) queues.Provider

func NewTestStore

func NewTestStore(ctx context.Context, cfg config.Config, log *logrus.Logger) (store.Store, string, error)

NewTestStore creates a new test store and returns the store and the database name.

func ParseURIForIPAndPort added in v0.8.1

func ParseURIForIPAndPort(rawURI string) (string, string, error)

ParseURIForIPAndPort parses a string URI and attempts to extract the IP address and port. It handles URIs with or without a scheme. If no port is specified, it attempts to deduce it from common schemes (http: 80, https: 443). If no scheme is supplied, http is assumed

func RandString added in v0.7.0

func RandString(n int) (string, error)

RandString generates a random string of length 'n' using lowercase alphabetic characters.

func ReturnTestAuthProvider added in v1.0.0

func ReturnTestAuthProvider(orgId uuid.UUID, name string, issuer string, labels *map[string]string) api.AuthProvider

ReturnTestAuthProvider creates a test auth provider with the given parameters

func ReturnTestDevice added in v0.3.0

func ReturnTestDevice(orgId uuid.UUID, name string, owner *string, tv *string, labels *map[string]string) api.Device

func RunTable added in v0.8.1

func RunTable[T any](cases []TestCase[T], runFunc func(T))

RunTable executes the provided run function for each test case in the cases slice.

func StartSpecTracerForGinkgo added in v0.8.1

func StartSpecTracerForGinkgo(parent context.Context) context.Context

func SystemdUnitExists added in v1.0.0

func SystemdUnitExists(unitName string) (bool, error)

SystemdUnitExists checks if a systemd unit exists

func TestEnrollmentApproval

func TestEnrollmentApproval() *v1beta1.EnrollmentRequestApproval

func TestTempEnv

func TestTempEnv(kv ...string) func()

TestTempEnv sets one or more environment variables and returns a cleanup function that restores their original values.

func ValidateStructuredError added in v1.1.0

func ValidateStructuredError(msg, phase, component string, statusMsgs ...string) error

ValidateStructuredError checks that a structured error message contains the expected phase, component, and at least one of the given status messages. The message is expected to start with a timestamp in brackets in the agent's format ("YYYY-MM-DD HH:MM:SS").

func WaitForServiceReady added in v1.0.0

func WaitForServiceReady(serviceName string, timeout time.Duration) error

WaitForServiceReady waits for a service to be active

Types

type DeviceIDKeyType added in v0.10.0

type DeviceIDKeyType struct{}

Context keys for storing test data

type DeviceKeyType added in v0.10.0

type DeviceKeyType struct{}

type ImageReference added in v1.1.0

type ImageReference struct {
	Repo string
	Name string
	Tag  string
}

func NewDeviceImageReference added in v1.1.0

func NewDeviceImageReference(tag string) ImageReference

func NewImageReference added in v1.1.0

func NewImageReference(repo, name, tag string) ImageReference

func NewImageReferenceFromString added in v1.1.0

func NewImageReferenceFromString(imageRef string) (ImageReference, error)

func NewSleepAppImageReference added in v1.1.0

func NewSleepAppImageReference(tag string) ImageReference

func (ImageReference) String added in v1.1.0

func (r ImageReference) String() string

func (ImageReference) WithTag added in v1.1.0

func (r ImageReference) WithTag(newTag string) ImageReference

type Message added in v0.4.0

type Message string

Define a type for messages.

const (
	UpdateRenderedVersionSuccess  Message = "Updated to desired renderedVersion:"
	UpdateRenderedVersionProgress Message = "the device is upgrading to renderedVersion:"
)

func (Message) String added in v0.4.0

func (m Message) String() string

type SSHPrivateKeyContent added in v1.2.0

type SSHPrivateKeyContent string

SSHPrivateKeyContent is the raw content of an SSH private key (e.g. for API payloads, base64). Use this type for parameters that expect the key material, not a path.

type SSHPrivateKeyPath added in v1.2.0

type SSHPrivateKeyPath string

SSHPrivateKeyPath is the path to a file containing an SSH private key. Use this type for parameters that expect a filesystem path (e.g. ssh -i, GIT_SSH_COMMAND).

func GenerateTempSSHKeyPair added in v1.2.0

func GenerateTempSSHKeyPair() (publicKey string, privateKeyPath SSHPrivateKeyPath, cleanup func(), err error)

GenerateTempSSHKeyPair creates a temporary directory, generates an ed25519 SSH key pair with ssh-keygen, and returns the public key content (one line), the path to the private key, and a cleanup function that removes the temp dir. Call cleanup when done (e.g. defer).

type SafeExecuter added in v1.2.0

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

SafeExecuter wraps a real executer and blocks dangerous system commands that should never be executed during integration tests (like systemctl reboot).

func NewDefaultSafeExecuter added in v1.2.0

func NewDefaultSafeExecuter() *SafeExecuter

NewDefaultSafeExecuter creates a SafeExecuter wrapping CommonExecuter

func NewSafeExecuter added in v1.2.0

func NewSafeExecuter(wrapped executer.Executer) *SafeExecuter

NewSafeExecuter creates a new SafeExecuter that wraps the given executer

func (*SafeExecuter) CommandContext added in v1.2.0

func (s *SafeExecuter) CommandContext(ctx context.Context, command string, args ...string) *exec.Cmd

func (*SafeExecuter) Execute added in v1.2.0

func (s *SafeExecuter) Execute(command string, args ...string) (stdout string, stderr string, exitCode int)

func (*SafeExecuter) ExecuteWithContext added in v1.2.0

func (s *SafeExecuter) ExecuteWithContext(ctx context.Context, command string, args ...string) (stdout string, stderr string, exitCode int)

func (*SafeExecuter) ExecuteWithContextFromDir added in v1.2.0

func (s *SafeExecuter) ExecuteWithContextFromDir(ctx context.Context, workingDir string, command string, args []string, env ...string) (stdout string, stderr string, exitCode int)

type TestCase added in v0.8.1

type TestCase[T any] struct {
	Description string
	Params      T
}

RunTable runs a table of test cases with the given run function. Each test case has a description and parameters of type T.

func Cases added in v0.8.1

func Cases[T any](items ...TestCase[T]) []TestCase[T]

type TestContextKeyType added in v0.10.0

type TestContextKeyType struct{}

type TestIDKeyType added in v0.10.0

type TestIDKeyType struct{}

TestIDKey is the context key used to store the test ID

type TestOrgCache added in v0.10.0

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

func (*TestOrgCache) Get added in v0.10.0

func (c *TestOrgCache) Get(id uuid.UUID) *model.Organization

func (*TestOrgCache) Set added in v0.10.0

func (c *TestOrgCache) Set(id uuid.UUID, org *model.Organization)

Directories

Path Synopsis
Package testdb provides shared test database utilities
Package testdb provides shared test database utilities

Jump to

Keyboard shortcuts

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