utils

package
v0.0.0-...-92c1b5f Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: GPL-3.0 Imports: 39 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	LoadStateLoaded   = "loaded"
	LoadStateNotFound = "not-found"
)

Variables

View Source
var ErrUnitNotRunning = errors.New("unit is not running")
View Source
var ErrUnknownMount = errors.New("mount is unknown")

Functions

func CIDRsOverlap

func CIDRsOverlap(cidr1, cidr2 string) (bool, error)

CIDRsOverlap checks if two given CIDR blocks overlap. It takes two strings representing the CIDR blocks as input and returns a boolean indicating whether they overlap and an error if any of the CIDR blocks are invalid.

func CertFingerprint

func CertFingerprint(cert *x509.Certificate) string

CertFingerprint returns the SHA256 fingerprint of a certificate.

func CleanHostEnviron

func CleanHostEnviron(environ []string) []string

CleanHostEnviron filters an environment slice so host binaries do not inherit snap-specific library or binary search paths that conflict with host glibc.

func CleanHostname

func CleanHostname(hostname string) (string, error)

CleanHostname sanitises hostnames.

func CopyFile

func CopyFile(srcFile, dstFile string) error

func DeepCopyMap

func DeepCopyMap(original map[string]string) map[string]string

DeepCopyMap copies a string map by creating a distinct new map and copying over the values.

func EqualIP

func EqualIP(ip1, ip2 string) bool

EqualIP compares two IP addresses canonically, falling back to string equality if parsing fails.

func FileExists

func FileExists(path ...string) (bool, error)

func GetFileMatches

func GetFileMatches(path string, re *regexp.Regexp) ([]string, error)

GetFileMatches returns the path of the first file in a dir matching the regex or "" if no file match was found.

func GetFirstIP

func GetFirstIP(subnet string) (net.IP, error)

GetFirstIP returns the first IP address of a subnet. Use big.Int so that it can handle both IPv4 and IPv6 addreses.

func GetIPv46Addresses

func GetIPv46Addresses(ip net.IP) ([]net.IP, error)

GetIPv46Addresses returns an IPv4 and IPv6 pair if possible, from the local network interface which has the given IP address. This looks through all the interface's IPs to find a global unicast IP of the opposite type (IPv4 / IPv6) from the input IP. GetIPv46Addresses will return an array containing only the given IP address if the pair could not be found. If the given IP address cannot be found locally, an error will be returned.

func GetKubernetesServiceIPsFromServiceCIDRs

func GetKubernetesServiceIPsFromServiceCIDRs(serviceCIDR string) ([]net.IP, error)

GetKubernetesServiceIPsFromServiceCIDRs returns a list of the first IP addrs from a given service cidr string.

func GetLocalhostAddress

func GetLocalhostAddress() (net.IP, error)

GetLocalhostAddress returns the loopback address (IPv4 or IPv6) of the local machine. It checks the loopback interface "lo" and returns "127.0.0.1" if available, or "::1" if only IPv6 is available. If neither is found, it returns an error.

func GetMountPath

func GetMountPath(fsType string) (string, error)

GetMountPath returns the first mountpath for a given filesystem type. GetMountPath returns ErrUnkownMount if the mount path does not exist.

func GetRemoteCertificate

func GetRemoteCertificate(address string) (*x509.Certificate, error)

GetRemoteCertificate retrieves the remote certificate from a given address The address should be in the format of "hostname:port" Returns the remote certificate or an error.

func HostCommandContext

func HostCommandContext(ctx context.Context, name string, arg ...string) *exec.Cmd

HostCommandContext creates an *exec.Cmd configured to run a host binary with an environment and executable lookup sanitized of snap-specific search paths.

func HostEnviron

func HostEnviron() []string

HostEnviron returns a copy of os.Environ() sanitized for running host binaries.

func IsIPv4

func IsIPv4(address string) bool

IsIPv4 returns true if the address is a valid IPv4 address, false otherwise. The address may contain a port number.

func IsLocalPortOpen

func IsLocalPortOpen(port string) (bool, error)

IsLocalPortOpen checks if the given local port is already open or not.

func JSONResponse

func JSONResponse(status int, v any) mctypes.Response

JSONResponse marshals the response to JSON and sets the status code.

func JoinHostPort

func JoinHostPort(host string, port int) string

JoinHostPort is like net.JoinHostPort but accepts an int for the port number.

func MaybeNotify

func MaybeNotify(ch chan<- struct{})

MaybeNotify pushes an empty struct to a channel, but does not block if that fails.

func MaybeReceive

func MaybeReceive(ch <-chan struct{})

MaybeReceive tries to receive from a channel, but does not block if that fails.

func MicroclusterBootstrapConfigFromMap

func MicroclusterBootstrapConfigFromMap(m map[string]string) (apiv2.BootstrapConfig, error)

MicroclusterBootstrapConfigFromMap returns an apiv2.BootstrapConfig from the config struct.

func MicroclusterControlPlaneJoinConfigFromMap

func MicroclusterControlPlaneJoinConfigFromMap(m map[string]string) (apiv2.ControlPlaneJoinConfig, error)

MicroclusterControlPlaneJoinConfigFromMap returns an apiv2.ControlPlaneJoinConfig from the config struct.

func MicroclusterMapWithBootstrapConfig

func MicroclusterMapWithBootstrapConfig(m map[string]string, bootstrap apiv2.BootstrapConfig) (map[string]string, error)

MicroclusterConfigWithBootstrap adds apiv2.BootstrapConfig to the config struct.

func MicroclusterMapWithControlPlaneJoinConfig

func MicroclusterMapWithControlPlaneJoinConfig(m map[string]string, controlPlaneJoinConfigJSON string) map[string]string

MicroclusterMapWithControlPlaneJoinConfig adds (a JSON formatted) apiv2.ControlPlaneJoinConfig to the config struct.

func MicroclusterMapWithTimeout

func MicroclusterMapWithTimeout(m map[string]string, timeout time.Duration) map[string]string

MicroclusterMapWithTimeout adds a "timeout" configuration value to the config struct. If timeout is zero, the configuration is not affected.

func MicroclusterMapWithWorkerJoinConfig

func MicroclusterMapWithWorkerJoinConfig(m map[string]string, token string, workerJoinConfigJSON string) map[string]string

MicroclusterMapWithWorkerJoinConfig adds (a JSON formatted) apiv2.WorkerJoinConfig to the config struct.

func MicroclusterTimeoutFromMap

func MicroclusterTimeoutFromMap(m map[string]string) time.Duration

MicroclusterTimeoutFromMap returns the configured timeout option from the config struct. In case of an invalid or empty value, 0 is returned.

func MicroclusterWorkerJoinConfigFromMap

func MicroclusterWorkerJoinConfigFromMap(m map[string]string) (apiv2.WorkerJoinConfig, error)

MicroclusterWorkerJoinConfigFromMap returns an apiv2.WorkerJoinConfig from the config struct.

func MinConfigFileDiff

func MinConfigFileDiff(dirs []string, minConfig map[string]string, excludeFile string) map[string]string

MinConfigFileDiff searches configuration directories to check whether the minimum configurations are set in them. Returns a map with the key, value configurations that need to be set to enforce the minimum configuration requirements.

func NewStrictJSONDecoder

func NewStrictJSONDecoder(r io.Reader) *json.Decoder

NewStrictJSONDecoder creates a new JSON decoder that disallows unknown fields.

func ParseAddressString

func ParseAddressString(address string, port int64) (string, error)

ParseAddressString parses an address string and returns a canonical network address.

func ParseArgumentFile

func ParseArgumentFile(path string) (map[string]string, error)

Reads an argument file and parses the lines to an <arg, value> map.

func ParseArgumentLine

func ParseArgumentLine(line string) (key string, value string)

ParseArgumentLine parses a command-line argument from a single line. The returned key includes any dash prefixes.

func ParseEndpointSlices

func ParseEndpointSlices(endpointSlices *discoveryv1.EndpointSliceList) []string

ParseEndpoints processes the given kube-apiserver endpointslices and returns a list of IPv4:port or [IPv6]:port strings.

func ParseEndpoints

func ParseEndpoints(endpoints *corev1.Endpoints) []string

ParseEndpoints processes the given kube-apiserver endpoints and returns a list of IPv4:port or [IPv6]:port strings.

func Path

func Path(u *url.URL, pathParts ...string) *url.URL

Path sets the path of the URL from one or more path parts. It appends each of the pathParts (escaped using url.PathEscape) prefixed with "/" to the URL path.

func Pointer

func Pointer[T any](v T) *T

func RunCommand

func RunCommand(ctx context.Context, command []string, opts ...func(*exec.Cmd)) error

RunCommand executes a command with a given context. RunCommand returns nil if the command completes successfully and the exit code is 0.

func RunHostCommand

func RunHostCommand(ctx context.Context, command []string, opts ...func(*exec.Cmd)) error

RunHostCommand executes a host command with a sanitized environment.

func RunningServiceArgs

func RunningServiceArgs(ctx context.Context, serviceName string) (map[string]string, error)

RunningServiceArgs queries systemd for the MainPID of the snap service unit and returns its parsed command-line arguments from /proc/<pid>/cmdline. Returns nil, nil when the service is not running.

func SecondsToExpirationDate

func SecondsToExpirationDate(now time.Time, seconds int) time.Time

SecondsToExpirationDate returns the expiration date from now plus the given number of seconds.

func SerializeArgumentFile

func SerializeArgumentFile(arguments map[string]string, path string, headerComment string) error

Serializes a map of service arguments in the format "argument=value" to file.

func ServiceArgsFromMap

func ServiceArgsFromMap(args map[string]*string) (map[string]string, []string)

ServiceArgsFromMap processes a map of string pointers and categorizes them into update and delete lists. - If the value pointer is nil, it adds the argument name to the delete list. - If the value pointer is not nil, it adds the argument and its value to the update map.

func SplitCIDRStrings

func SplitCIDRStrings(cidrString string) (string, string, error)

SplitCIDRStrings parses the given CIDR string and returns the respective IPv4 and IPv6 CIDRs.

func SplitIPAndDNSSANs

func SplitIPAndDNSSANs(extraSANs []string) ([]net.IP, []string)

SplitIPAndDNSSANs splits a list of SANs into IP and DNS SANs Returns a list of IP addresses and a list of DNS names.

func StringToFieldsSliceHookFunc

func StringToFieldsSliceHookFunc(r rune) mapstructure.DecodeHookFunc

StringToFieldsSliceHookFunc is like mapstructure.StringToSliceHookFunc() but uses strings.Fields() and filters whitespace.

func StringToStringMapHookFunc

func StringToStringMapHookFunc(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error)

StringToStringMapHookFunc is like StringToFieldsSliceHookFunc(). It splits map entries on ',' and then key-value pairs on '='.

func SyncManualResponseWithSignal

func SyncManualResponseWithSignal(req *http.Request, readyCh chan error, result any) mctypes.Response

SyncManualResponseWithSignal is a convenience wrapper for manualResponseWithSignal that renders a standard SyncResponse.

func TLSClientConfigWithTrustedCertificate

func TLSClientConfigWithTrustedCertificate(remoteCert *x509.Certificate, rootCAs *x509.CertPool) (*tls.Config, error)

TLSClientConfig returns a TLS configuration that trusts a remote server The remoteCert is the public key of the server we are connecting to. The rootCAs is the list of trusted CAs, allowing you to pass the clients existing trusted CAs.

func TTLToSeconds

func TTLToSeconds(ttl string) (int, error)

TTLToSeconds converts a TTL string to seconds. The TTL string is a number followed by a unit: - y: years - mo: months - d: days - any other unit supported by time.ParseDuration.

func ToIPString

func ToIPString(ip net.IP) string

ToIPString returns the string representation of an IP address. If the IP address is an IPv6 address, it is enclosed in square brackets.

func UnmarshalStrict

func UnmarshalStrict(in []byte, out any) error

UnmarshalStrict decodes YAML data into out, failing if any unknown fields are encountered.

func WriteFile

func WriteFile(name string, data []byte, perm fs.FileMode) error

WriteFile writes data to a file with the given name and permissions. The file is written to a temporary file in the same directory as the target file and then renamed to the target file to avoid partial writes in case of a crash.

func YAMLToStringMapHookFunc

func YAMLToStringMapHookFunc(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error)

YAMLToStringMapHookFunc returns a mapstructure.DecodeHookFunc that converts string to map[string]string by parsing YAML.

func YAMLToStringSliceHookFunc

func YAMLToStringSliceHookFunc(f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error)

YAMLToStringSliceHookFunc returns a mapstructure.DecodeHookFunc that converts string to []string by parsing YAML.

func YamlCommentLines

func YamlCommentLines(content []byte) []byte

YamlCommentLines adds "# " at the beginning of each line.

Types

type ActiveState

type ActiveState string
const (
	ActiveStateActive   ActiveState = "active"
	ActiveStateInactive ActiveState = "inactive"
)

type LoadState

type LoadState string

type MountPropagationType

type MountPropagationType string
const (
	MountPropagationShared  MountPropagationType = "shared"
	MountPropagationPrivate MountPropagationType = "private"
	MountPropagationUnknown MountPropagationType = "unknown"
)

func GetMountPropagationType

func GetMountPropagationType(path string) (MountPropagationType, error)

GetMountPropagationType returns the propagation type (shared or private) GetMountPropagationType returns ErrUnkownMount if the mount path does not exist.

type VXLANInterface

type VXLANInterface struct {
	net.Interface
	Port *int
}

func ListVXLANInterfaces

func ListVXLANInterfaces() ([]VXLANInterface, error)

Directories

Path Synopsis
experimental

Jump to

Keyboard shortcuts

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