util

package
v0.0.0-...-4df9163 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: AGPL-3.0 Imports: 28 Imported by: 13

Documentation

Index

Examples

Constants

View Source
const SystemdListenFDsStart = 3

SystemdListenFDsStart is the number of the first file descriptor that might have been opened by systemd when socket activation is enabled. It's always 3 in real-world usage (i.e. the first file descriptor opened after stdin, stdout and stderr), so this constant should always be the value passed to GetListeners, except for unit tests.

Variables

This section is empty.

Functions

func AppArmorProfile

func AppArmorProfile() string

AppArmorProfile returns the current apparmor profile.

func AvailableStorageDrivers

func AvailableStorageDrivers(supportedDrivers []api.ServerStorageDriverInfo, poolType PoolType) []string

AvailableStorageDrivers returns a list of storage drivers that are available.

func CanonicalNetworkAddress

func CanonicalNetworkAddress(address string, defaultPort int64) string

CanonicalNetworkAddress parses the given network address and returns a string of the form "host:port", possibly filling it with the default port if it's missing. It will also wrap a bare IPv6 address with square brackets if needed.

func CanonicalNetworkAddressFromAddressAndPort

func CanonicalNetworkAddressFromAddressAndPort(address string, port int64, defaultPort int64) string

CanonicalNetworkAddressFromAddressAndPort returns a network address from separate address and port values. The address accepts values such as "[::]", "::" and "localhost".

func CheckCASignature

func CheckCASignature(cert x509.Certificate, networkCert *shared.CertInfo) (trusted bool, revoked bool, fingerprint string)

CheckCASignature returns whether the certificate is signed by the CA, whether the certificate has been revoked, and the certificate fingerprint.

func CheckMutualTLS

func CheckMutualTLS(cert x509.Certificate, trustedCerts map[string]x509.Certificate) (bool, string)

CheckMutualTLS checks whether the given certificate is valid and is present in the given trustedCerts map. Returns true if the certificate is trusted, and the fingerprint of the certificate.

func CompareConfigs

func CompareConfigs(config1, config2 map[string]string, exclude []string) error

CompareConfigs compares two config maps and returns an error if they differ.

func CompareVersions

func CompareVersions(version1, version2 [2]int) (int, error)

CompareVersions the versions of two LXD nodes.

A version consists of the version the node's schema and the number of API extensions it supports.

Return 0 if they equal, 1 if the first version is greater than the second and 2 if the second is greater than the first.

Return an error if inconsistent versions are detected, for example the first node's schema is greater than the second's, but the number of extensions is smaller.

func CopyConfig

func CopyConfig(config map[string]string) map[string]string

CopyConfig creates a new map with a copy of the given config.

func DebugJSON

func DebugJSON(title string, r *bytes.Buffer, l logger.Logger)

DebugJSON helper to log JSON. Accepts a title to prefix the JSON log with, a *bytes.Buffer containing the JSON and a logger to use for logging the JSON (allowing for custom context to be added to the log).

func EtagCheck

func EtagCheck(r *http.Request, data any) error

EtagCheck validates the hash of the current state with the hash provided by the client.

func EtagHash

func EtagHash(data any) (string, error)

EtagHash hashes the provided data and returns the sha256.

func GenerateSequenceInt64

func GenerateSequenceInt64(begin, end, step int) ([]int64, error)

GenerateSequenceInt64 returns a sequence within a given range with given steps.

func GetArchitectures

func GetArchitectures() ([]int, error)

GetArchitectures returns the list of supported architectures.

func GetExecPath

func GetExecPath() string

GetExecPath returns the path to the current binary.

func GetListeners

func GetListeners(start int) []net.Listener

GetListeners returns the socket-activated network listeners, if any.

The 'start' parameter must be SystemdListenFDsStart, except in unit tests, see the docstring of SystemdListenFDsStart below.

func GetStableRandomGenerator

func GetStableRandomGenerator(seed string) (*rand.Rand, error)

GetStableRandomGenerator returns a stable random generator. Uses the FNV-1a hash algorithm to convert the seed string into an int64 for use as seed to the non-cryptographic random number generator.

func GetStableRandomInt64FromList

func GetStableRandomInt64FromList(seed int64, list []int64) (int64, error)

GetStableRandomInt64FromList returns a stable random value from a given list.

func HTTPClient

func HTTPClient(certificate string, proxy proxyFunc) (*http.Client, error)

HTTPClient returns an http.Client using the given certificate and proxy.

func HugepagesPath

func HugepagesPath() (string, error)

HugepagesPath attempts to locate the mount point of the hugepages filesystem.

func InMemoryNetwork

func InMemoryNetwork() (net.Listener, func() net.Conn)

InMemoryNetwork creates a fully in-memory listener and dial function.

Each time the dial function is invoked a new pair of net.Conn objects will be created using net.Pipe: the listener's Accept method will unblock and return one end of the pipe and the other end will be returned by the dial function.

func IsAddressCovered

func IsAddressCovered(address1, address2 string) bool

IsAddressCovered detects if network address1 is actually covered by address2, in the sense that they are either the same address or address2 is specified using a wildcard with the same port of address1.

func IsJSONRequest

func IsJSONRequest(r *http.Request) bool

IsJSONRequest returns true if the content type of the HTTP request is JSON.

func IsRecursionRequest

func IsRecursionRequest(r *http.Request) bool

IsRecursionRequest checks whether the given HTTP request is marked with the "recursion" flag in its form values.

func IsWildCardAddress

func IsWildCardAddress(address string) bool

IsWildCardAddress returns whether the given address is a wildcard.

func ListenAddresses

func ListenAddresses(configListenAddress string) ([]string, error)

ListenAddresses returns a list of <host>:<port> combinations at which this machine can be reached. It accepts the configured listen address in the following formats: <host>, <host>:<port> or :<port>. If a listen port is not specified then then shared.HTTPSDefaultPort is used instead. If a non-empty and non-wildcard host is passed in then this functions returns a single element list with the listen address specified. Otherwise if an empty host or wildcard address is specified then all global unicast addresses actively configured on the host are returned. If an IPv4 wildcard address (0.0.0.0) is specified as the host then only IPv4 addresses configured on the host are returned.

Example
listenAddressConfigs := []string{
	"",
	"127.0.0.1:8000",   // Valid IPv4 address with port.
	"127.0.0.1",        // Valid IPv4 address without port.
	"[127.0.0.1]",      // Valid wrapped IPv4 address without port.
	"[::1]:8000",       // Valid IPv6 address with port.
	"::1:8000",         // Valid IPv6 address without port (that might look like a port).
	"::1",              // Valid IPv6 address without port.
	"[::1]",            // Valid wrapped IPv6 address without port.
	"example.com",      // Valid hostname without port.
	"example.com:8000", // Valid hostname with port.
	"foo:8000:9000",    // Invalid host and port combination.
	":::8000",          // Invalid host and port combination.
}

for _, listlistenAddressConfig := range listenAddressConfigs {
	listenAddress, err := ListenAddresses(listlistenAddressConfig)
	fmt.Printf("%q: %v %v\n", listlistenAddressConfig, listenAddress, err)
}
Output:

"": [] <nil>
"127.0.0.1:8000": [127.0.0.1:8000] <nil>
"127.0.0.1": [127.0.0.1:8443] <nil>
"[127.0.0.1]": [127.0.0.1:8443] <nil>
"[::1]:8000": [[::1]:8000] <nil>
"::1:8000": [[::1:8000]:8443] <nil>
"::1": [[::1]:8443] <nil>
"[::1]": [[::1]:8443] <nil>
"example.com": [example.com:8443] <nil>
"example.com:8000": [example.com:8000] <nil>
"foo:8000:9000": [] address foo:8000:9000: too many colons in address
":::8000": [] address :::8000: too many colons in address

func LoadCert

func LoadCert(dir string) (*shared.CertInfo, error)

LoadCert reads the LXD server certificate from the given var dir.

If a cluster certificate is found it will be loaded instead. If neither a server or cluster certfificate exists, a new server certificate will be generated.

func LoadClusterCert

func LoadClusterCert(dir string) (*shared.CertInfo, error)

LoadClusterCert reads the LXD cluster certificate from the given var dir.

If a cluster certificate doesn't exist, a new one is generated.

func LoadModule

func LoadModule(module string) error

LoadModule loads the kernel module with the given name, by invoking modprobe. This respects any modprobe configuration on the system.

func LoadServerCert

func LoadServerCert(dir string) (*shared.CertInfo, error)

LoadServerCert reads the LXD server certificate from the given var dir.

func NetworkInterfaceAddress

func NetworkInterfaceAddress() string

NetworkInterfaceAddress returns the first global unicast address of any of the system network interfaces. Return the empty string if none is found.

func ReplaceDaemon

func ReplaceDaemon() error

ReplaceDaemon replaces the LXD process.

func ServerTLSConfig

func ServerTLSConfig(cert *shared.CertInfo) *tls.Config

ServerTLSConfig returns a new server-side tls.Config generated from the give certificate info.

func SupportsFilesystem

func SupportsFilesystem(filesystem string) bool

SupportsFilesystem checks whether a given filesystem is already supported by the kernel. Note that if the filesystem is a module, you may need to load it first.

func SysctlGet

func SysctlGet(path string) (string, error)

SysctlGet retrieves the value of a sysctl file in /proc/sys.

func SysctlSet

func SysctlSet(parts ...string) error

SysctlSet writes a value to a sysctl file in /proc/sys. Requires an even number of arguments as key/value pairs. E.g. SysctlSet("path1", "value1", "path2", "value2").

func WriteCert

func WriteCert(dir, prefix string, cert, key, ca []byte) error

WriteCert writes the given material to the appropriate certificate files in the given LXD var directory.

func WriteJSON

func WriteJSON(w http.ResponseWriter, body any, debugLogger logger.Logger) error

WriteJSON encodes the body as JSON and sends it back to the client Accepts optional debugLogger that activates debug logging if non-nil.

Types

type ContextAwareRequest

type ContextAwareRequest interface {
	WithContext(ctx context.Context) *http.Request
}

ContextAwareRequest is an interface implemented by http.Request starting from Go 1.8. It supports graceful cancellation using a context.

type PoolType

type PoolType string

PoolType represents a type of storage pool (local, remote or any).

const PoolTypeAny PoolType = ""

PoolTypeAny represents any storage pool (local or remote).

const PoolTypeLocal PoolType = "local"

PoolTypeLocal represents local storage pools.

const PoolTypeRemote PoolType = "remote"

PoolTypeRemote represents remote storage pools.

Jump to

Keyboard shortcuts

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