core

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package core provides file utilities: permission constants, temp file creation, and template processing.

Package core provides retry and polling utilities: configurable retry logic, status polling, and timeout handling.

Package ssh provides SSH utilities: direct/two-hop connections, known hosts management, and remote file operations.

Package core provides validation utilities: resource names, SSH keys, paths, IPs, node names, and integer bounds to prevent security vulnerabilities.

Index

Constants

View Source
const (
	SecureFileMode   os.FileMode = 0600 // Sensitive files (secrets, keys)
	ReadOnlyFileMode os.FileMode = 0400 // Read-only configs
	SecureDirMode    os.FileMode = 0700 // Sensitive directories
	StandardFileMode os.FileMode = 0644 // Non-sensitive files
	StandardDirMode  os.FileMode = 0755 // Standard directories
)

File permission constants for secure file handling.

Variables

This section is empty.

Functions

func BackupResource

func BackupResource(oc *exutil.CLI, resourceType, name, namespace, backupDir string) error

BackupResource saves a Kubernetes resource to a YAML file with secure permissions.

err := BackupResource(oc, "secret", secretName, "openshift-etcd", backupDir)

func CleanupLocalKnownHostsFile

func CleanupLocalKnownHostsFile(sshConfig *SSHConfig, knownHostsPath string) error

CleanupLocalKnownHostsFile removes the temporary local known hosts file.

err := CleanupLocalKnownHostsFile(sshConfig, knownHostsPath)

func CleanupRemoteKnownHostsFile

func CleanupRemoteKnownHostsFile(sshConfig *SSHConfig, localKnownHostsPath string, remoteKnownHostsPath string) error

CleanupRemoteKnownHostsFile removes the temporary known_hosts file from the proxy node.

err := CleanupRemoteKnownHostsFile(sshConfig, localKH, remoteKH)

func CreateFromTemplate

func CreateFromTemplate(templatePath string, replacements map[string]string) (string, func(), error)

CreateFromTemplate processes a template with placeholder substitution, returns temp file path and cleanup function.

tmpFile, cleanup, err := CreateFromTemplate(templatePath, map[string]string{"{NAME}": "master-0"})

func CreateRemoteFile

func CreateRemoteFile(filepath, content string, mode os.FileMode, sshConfig *SSHConfig, knownHostsPath string) error

CreateRemoteFile creates a file on a remote host via SSH using base64 encoding for security.

err := CreateRemoteFile("/tmp/config.xml", xmlContent, SecureFileMode, sshConfig, knownHostsPath)

func CreateRemoteTempFile

func CreateRemoteTempFile(filename, content string, mode os.FileMode, sshConfig *SSHConfig, knownHostsPath string) (string, error)

CreateRemoteTempFile creates a temporary file in /tmp on a remote host via SSH.

tmpPath, err := CreateRemoteTempFile("master-0.xml", xmlContent, SecureFileMode, sshConfig, knownHostsPath)

func CreateResourceFromTemplate

func CreateResourceFromTemplate(oc *exutil.CLI, templatePath string, replacements map[string]string) error

CreateResourceFromTemplate processes a template and creates a Kubernetes resource with "oc create -f".

err := CreateResourceFromTemplate(oc, templatePath, map[string]string{"{NAME}": "master-0", "{UUID}": uuid})

func DeleteRemoteTempFile

func DeleteRemoteTempFile(remotePath string, sshConfig *SSHConfig, knownHostsPath string) error

DeleteRemoteTempFile removes a temporary file from a remote host via SSH.

defer DeleteRemoteTempFile(tmpPath, sshConfig, knownHostsPath)

func ExecuteRemoteSSHCommand

func ExecuteRemoteSSHCommand(remoteNodeIP, command string, sshConfig *SSHConfig, localKnownHostsPath, remoteKnownHostsPath string) (string, string, error)

ExecuteRemoteSSHCommand executes a command via two-hop SSH (local → hypervisor → node).

stdout, stderr, err := ExecuteRemoteSSHCommand(nodeIP, "systemctl status etcd", sshConfig, localKH, remoteKH)

func ExecuteSSHCommand

func ExecuteSSHCommand(command string, sshConfig *SSHConfig, knownHostsPath string) (string, string, error)

ExecuteSSHCommand executes a command on a remote host via SSH.

stdout, stderr, err := ExecuteSSHCommand("ls /var/lib", sshConfig, knownHostsPath)

func ExpectNotEmpty

func ExpectNotEmpty(value interface{}, description string, args ...interface{})

ExpectNotEmpty validates that a value is not empty with a descriptive error message.

ExpectNotEmpty(nodeName, "Expected node name to be set")

func NewError

func NewError(operation, details string) error

NewError creates a new error with standardized context following the pattern: "failed to <operation> <details>".

return NewError("connect to hypervisor", "no SSH key provided")

func PollUntil

func PollUntil(checker StatusChecker, timeout, pollInterval time.Duration, description string) error

PollUntil is a convenience wrapper for simple timeout-based polling.

err := PollUntil(func() (bool, error) { return checkCondition() }, 5*time.Minute, 10*time.Second, "condition")

func PollUntilWithOptions

func PollUntilWithOptions(checker StatusChecker, opts PollOptions, description string) error

PollUntilWithOptions repeatedly checks a condition until it's met or limits are reached.

err := PollUntilWithOptions(func() (bool, error) { return checkReady() }, PollOptions{Timeout: 10*time.Minute, PollInterval: 30*time.Second}, "node ready")

func PrepareLocalKnownHostsFile

func PrepareLocalKnownHostsFile(sshConfig *SSHConfig) (string, error)

PrepareLocalKnownHostsFile creates a temporary known_hosts file and scans the SSH host key.

knownHostsPath, err := PrepareLocalKnownHostsFile(sshConfig)

func PrepareRemoteKnownHostsFile

func PrepareRemoteKnownHostsFile(remoteNodeIP string, proxyNodeSSHConfig *SSHConfig, localKnownHostsPath string) (string, error)

PrepareRemoteKnownHostsFile creates a known_hosts file on the proxy node for two-hop SSH.

remoteKHPath, err := PrepareRemoteKnownHostsFile(nodeIP, proxySshConfig, localKHPath)

func RestoreResource

func RestoreResource(oc *exutil.CLI, backupFile string) error

RestoreResource creates a Kubernetes resource from a backup YAML file.

err := RestoreResource(oc, filepath.Join(backupDir, secretName+".yaml"))

func RetryWithOptions

func RetryWithOptions(operation func() error, opts RetryOptions, operationName string) error

RetryWithOptions retries an operation with configurable timeout, max attempts, and error filtering.

err := RetryWithOptions(func() error { return etcdOp() }, RetryOptions{Timeout: 5*time.Minute, PollInterval: 30*time.Second}, "etcd operation")

func ValidateIPAddress

func ValidateIPAddress(ip string) error

ValidateIPAddress checks string is valid IPv4/IPv6 (rejects unspecified 0.0.0.0/::).

if err := ValidateIPAddress(nodeIP); err != nil { return err }

func ValidateIntegerBounds

func ValidateIntegerBounds(value, min, max int, paramName string) error

ValidateIntegerBounds checks value is within [min, max] range (prevents overflow/underflow).

if err := ValidateIntegerBounds(lineCount, 1, 10000, "journal line count"); err != nil { return err }

func ValidateNodeName

func ValidateNodeName(name string) error

ValidateNodeName checks name conforms to Kubernetes/RFC 1123 DNS subdomain rules (max 253 chars).

if err := ValidateNodeName(nodeName); err != nil { return err }

func ValidateResourceName

func ValidateResourceName(name, resourceType string) error

ValidateResourceName ensures a name is safe for shell commands (prevents command injection).

if err := ValidateResourceName(vmName, "VM"); err != nil { return err }

func ValidateSSHKeyPermissions

func ValidateSSHKeyPermissions(keyPath string) error

ValidateSSHKeyPermissions checks SSH private key has secure permissions (0600 or 0400). Logs a warning for insecure permissions but continues to support CI environments where file permissions may be set differently (e.g., 0644).

if err := ValidateSSHKeyPermissions(privateKeyPath); err != nil { return err }

func ValidateSafePath

func ValidateSafePath(path, baseDir string) error

ValidateSafePath ensures path is within baseDir (prevents path traversal attacks).

if err := ValidateSafePath(templatePath, "test/extended/testdata/two_node/"); err != nil { return err }

func ValidationError

func ValidationError(field, reason string) error

ValidationError creates a validation error with standardized format: "<field>: <reason>".

return ValidationError("node name", "contains invalid characters")

func ValidationWarning

func ValidationWarning(field, reason string)

ValidationWarning logs a non-fatal validation issue that doesn't prevent test execution. Use for best practices or environment-specific checks that may differ in CI vs prod.

ValidationWarning("config", "suboptimal setting detected but will continue")

func VerifyConnectivity

func VerifyConnectivity(sshConfig *SSHConfig, knownHostsPath string) (string, string, error)

VerifyConnectivity tests SSH connectivity by executing a simple echo command.

stdout, stderr, err := VerifyConnectivity(sshConfig, knownHostsPath)

func WithLocalTempFile

func WithLocalTempFile(pattern, content string, mode os.FileMode, fn func(path string) error) error

WithLocalTempFile creates a temp file, executes fn with the path, then auto-cleans up.

err := WithLocalTempFile("secret-*.yaml", content, SecureFileMode, func(path string) error { return processFile(path) })

func WrapError

func WrapError(operation, details string, err error) error

WrapError wraps an error with standardized context following the pattern: "failed to <operation> <details>: <original error>".

return WrapError("create temp file", "pattern=secret-*.yaml", err)

Types

type PollOptions

type PollOptions struct {
	Timeout      time.Duration
	PollInterval time.Duration
	MaxAttempts  int
}

PollOptions configures polling behavior with timeout, poll interval, and max attempts.

type RetryOptions

type RetryOptions struct {
	Timeout      time.Duration
	PollInterval time.Duration
	MaxRetries   int
	ShouldRetry  func(error) bool
}

RetryOptions configures retry behavior with timeout, poll interval, max attempts, and error filtering.

type SSHConfig

type SSHConfig struct {
	IP             string
	User           string
	PrivateKeyPath string
}

SSHConfig contains configuration for SSH connections.

type StatusChecker

type StatusChecker func() (bool, error)

StatusChecker checks if a condition is met, returning (true, nil) when satisfied.

Jump to

Keyboard shortcuts

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