shared

package
v0.0.0-...-288c4de Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2023 License: Apache-2.0 Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const ConfigVolatilePrefix = "volatile."

ConfigVolatilePrefix indicates the prefix used for volatile config keys.

View Source
const HTTPDefaultPort = 8080
View Source
const HTTPSDefaultPort = 8443
View Source
const HTTPSMetricsDefaultPort = 9100
View Source
const HTTPSStorageBucketsDefaultPort = 9000

HTTPSStorageBucketsDefaultPort the default port for the storage buckets listener.

View Source
const SnapshotDelimiter = "/"

Variables

View Source
var ErrNoRootDisk = fmt.Errorf("No root device could be found")

ErrNoRootDisk means there is no root disk device found.

View Source
var HugePageSizeKeys = [...]string{"limits.hugepages.64KB", "limits.hugepages.1MB", "limits.hugepages.2MB", "limits.hugepages.1GB"}

HugePageSizeKeys is a list of known hugepage size configuration keys.

View Source
var HugePageSizeSuffix = [...]string{"64KB", "1MB", "2MB", "1GB"}

HugePageSizeSuffix contains the list of known hugepage size suffixes.

View Source
var InstanceConfigKeysAny = map[string]func(value string) error{
	"boot.autostart":             validate.Optional(validate.IsBool),
	"boot.autostart.delay":       validate.Optional(validate.IsInt64),
	"boot.autostart.priority":    validate.Optional(validate.IsInt64),
	"boot.stop.priority":         validate.Optional(validate.IsInt64),
	"boot.host_shutdown_timeout": validate.Optional(validate.IsInt64),

	"cloud-init.network-config": validate.Optional(validate.IsYAML),
	"cloud-init.user-data":      validate.Optional(validate.IsCloudInitUserData),
	"cloud-init.vendor-data":    validate.Optional(validate.IsCloudInitUserData),

	"cluster.evacuate": validate.Optional(validate.IsOneOf("auto", "migrate", "live-migrate", "stop")),

	"limits.cpu":           validate.Optional(validate.IsValidCPUSet),
	"limits.cpu.nodes":     validate.Optional(validate.IsValidCPUSet),
	"limits.disk.priority": validate.Optional(validate.IsPriority),
	"limits.memory": func(value string) error {
		if value == "" {
			return nil
		}

		if strings.HasSuffix(value, "%") {
			num, err := strconv.ParseInt(strings.TrimSuffix(value, "%"), 10, 64)
			if err != nil {
				return err
			}

			if num == 0 {
				return errors.New("Memory limit can't be 0%")
			}

			return nil
		}

		num, err := units.ParseByteSizeString(value)
		if err != nil {
			return err
		}

		if num == 0 {
			return fmt.Errorf("Memory limit can't be 0")
		}

		return nil
	},
	"limits.network.priority": validate.Optional(validate.IsPriority),

	"raw.apparmor": validate.IsAny,
	"raw.idmap":    validate.IsAny,

	"security.devlxd":            validate.Optional(validate.IsBool),
	"security.protection.delete": validate.Optional(validate.IsBool),

	"snapshots.schedule":         validate.Optional(validate.IsCron([]string{"@hourly", "@daily", "@midnight", "@weekly", "@monthly", "@annually", "@yearly", "@startup", "@never"})),
	"snapshots.schedule.stopped": validate.Optional(validate.IsBool),
	"snapshots.pattern":          validate.IsAny,
	"snapshots.expiry": func(value string) error {

		_, err := GetExpiry(time.Time{}, value)
		return err
	},

	"volatile.apply_template":         validate.IsAny,
	"volatile.base_image":             validate.IsAny,
	"volatile.cloud-init.instance-id": validate.Optional(validate.IsUUID),
	"volatile.evacuate.origin":        validate.IsAny,
	"volatile.last_state.power":       validate.IsAny,
	"volatile.last_state.ready":       validate.IsBool,
	"volatile.apply_quota":            validate.IsAny,
	"volatile.uuid":                   validate.Optional(validate.IsUUID),
	"volatile.uuid.generation":        validate.Optional(validate.IsUUID),
}

InstanceConfigKeysAny is a map of config key to validator. (keys applying to containers AND virtual machines).

View Source
var InstanceConfigKeysContainer = map[string]func(value string) error{
	"limits.cpu.allowance": func(value string) error {
		if value == "" {
			return nil
		}

		if strings.HasSuffix(value, "%") {

			_, err := strconv.Atoi(strings.TrimSuffix(value, "%"))
			if err != nil {
				return err
			}

			return nil
		}

		fields := strings.SplitN(value, "/", 2)
		if len(fields) != 2 {
			return fmt.Errorf("Invalid allowance: %s", value)
		}

		_, err := strconv.Atoi(strings.TrimSuffix(fields[0], "ms"))
		if err != nil {
			return err
		}

		_, err = strconv.Atoi(strings.TrimSuffix(fields[1], "ms"))
		if err != nil {
			return err
		}

		return nil
	},
	"limits.cpu.priority":   validate.Optional(validate.IsPriority),
	"limits.hugepages.64KB": validate.Optional(validate.IsSize),
	"limits.hugepages.1MB":  validate.Optional(validate.IsSize),
	"limits.hugepages.2MB":  validate.Optional(validate.IsSize),
	"limits.hugepages.1GB":  validate.Optional(validate.IsSize),
	"limits.memory.enforce": validate.Optional(validate.IsOneOf("soft", "hard")),

	"limits.memory.swap":          validate.Optional(validate.IsBool),
	"limits.memory.swap.priority": validate.Optional(validate.IsPriority),
	"limits.processes":            validate.Optional(validate.IsInt64),

	"linux.kernel_modules": validate.IsAny,

	"migration.incremental.memory":            validate.Optional(validate.IsBool),
	"migration.incremental.memory.iterations": validate.Optional(validate.IsUint32),
	"migration.incremental.memory.goal":       validate.Optional(validate.IsUint32),

	"nvidia.runtime":             validate.Optional(validate.IsBool),
	"nvidia.driver.capabilities": validate.IsAny,
	"nvidia.require.cuda":        validate.IsAny,
	"nvidia.require.driver":      validate.IsAny,

	"raw.lxc":     validate.IsAny,
	"raw.seccomp": validate.IsAny,

	"security.devlxd.images": validate.Optional(validate.IsBool),

	"security.idmap.base":     validate.Optional(validate.IsUint32),
	"security.idmap.isolated": validate.Optional(validate.IsBool),
	"security.idmap.size":     validate.Optional(validate.IsUint32),

	"security.nesting":          validate.Optional(validate.IsBool),
	"security.privileged":       validate.Optional(validate.IsBool),
	"security.protection.shift": validate.Optional(validate.IsBool),

	"security.syscalls.allow":                        validate.IsAny,
	"security.syscalls.blacklist_default":            validate.Optional(validate.IsBool),
	"security.syscalls.blacklist_compat":             validate.Optional(validate.IsBool),
	"security.syscalls.blacklist":                    validate.IsAny,
	"security.syscalls.deny_default":                 validate.Optional(validate.IsBool),
	"security.syscalls.deny_compat":                  validate.Optional(validate.IsBool),
	"security.syscalls.deny":                         validate.IsAny,
	"security.syscalls.intercept.bpf":                validate.Optional(validate.IsBool),
	"security.syscalls.intercept.bpf.devices":        validate.Optional(validate.IsBool),
	"security.syscalls.intercept.mknod":              validate.Optional(validate.IsBool),
	"security.syscalls.intercept.mount":              validate.Optional(validate.IsBool),
	"security.syscalls.intercept.mount.allowed":      validate.IsAny,
	"security.syscalls.intercept.mount.fuse":         validate.IsAny,
	"security.syscalls.intercept.mount.shift":        validate.Optional(validate.IsBool),
	"security.syscalls.intercept.sched_setscheduler": validate.Optional(validate.IsBool),
	"security.syscalls.intercept.setxattr":           validate.Optional(validate.IsBool),
	"security.syscalls.intercept.sysinfo":            validate.Optional(validate.IsBool),
	"security.syscalls.whitelist":                    validate.IsAny,

	"volatile.last_state.idmap": validate.IsAny,
	"volatile.idmap.base":       validate.IsAny,
	"volatile.idmap.current":    validate.IsAny,
	"volatile.idmap.next":       validate.IsAny,
}

InstanceConfigKeysContainer is a map of config key to validator. (keys applying to containers only).

View Source
var InstanceConfigKeysVM = map[string]func(value string) error{
	"limits.memory.hugepages": validate.Optional(validate.IsBool),

	"migration.stateful": validate.Optional(validate.IsBool),

	"raw.qemu":      validate.IsAny,
	"raw.qemu.conf": validate.IsAny,

	"security.agent.metrics":    validate.Optional(validate.IsBool),
	"security.csm":              validate.Optional(validate.IsBool),
	"security.secureboot":       validate.Optional(validate.IsBool),
	"security.sev":              validate.Optional(validate.IsBool),
	"security.sev.policy.es":    validate.Optional(validate.IsBool),
	"security.sev.session.dh":   validate.Optional(validate.IsAny),
	"security.sev.session.data": validate.Optional(validate.IsAny),

	"agent.nic_config": validate.Optional(validate.IsBool),

	"volatile.apply_nvram": validate.Optional(validate.IsBool),
	"volatile.vsock_id":    validate.Optional(validate.IsInt64),
}

InstanceConfigKeysVM is a map of config key to validator. (keys applying to VM only).

View Source
var ObjectFound = fmt.Errorf("Found requested object")

Functions

func AddSlash

func AddSlash(path string) string

AddSlash adds a slash to the end of paths if they don't already have one. This can be useful for rsyncing things, since rsync has behavior present on the presence or absence of a trailing slash.

func AllocatePort

func AllocatePort() (int, error)

AllocatePort asks the kernel for a free open port that is ready to use.

func AtoiEmptyDefault

func AtoiEmptyDefault(s string, def int) (int, error)

func CachePath

func CachePath(path ...string) string

CachePath returns the directory that LXD should its cache under. If LXD_DIR is set, this path is $LXD_DIR/cache, otherwise it is /var/cache/lxd.

func CertFingerprint

func CertFingerprint(cert *x509.Certificate) string

func CertFingerprintStr

func CertFingerprintStr(c string) (string, error)

func CertificateTokenDecode

func CertificateTokenDecode(input string) (*api.CertificateAddToken, error)

CertificateTokenDecode decodes a base64 and JSON encoded certificate add token.

func ConfigKeyChecker

func ConfigKeyChecker(key string, instanceType instancetype.Type) (func(value string) error, error)

ConfigKeyChecker returns a function that will check whether or not a provide value is valid for the associate config key. Returns an error if the key is not known. The checker function only performs syntactic checking of the value, semantic and usage checking must be done by the caller. User defined keys are always considered to be valid, e.g. user.* and environment.* keys.

func DeepCopy

func DeepCopy(src, dest any) error

DeepCopy copies src to dest by using encoding/gob so its not that fast.

func DetectCompression

func DetectCompression(fname string) ([]string, string, []string, error)

DetectCompression detects compression from a file name.

func DetectCompressionFile

func DetectCompressionFile(f io.Reader) ([]string, string, []string, error)

DetectCompressionFile detects the compression type of a file and returns the tar arguments needed to unpack the file, compression type (in the form of a file extension), and the command needed to decompress the file to an uncompressed tarball.

func DeviceTotalMemory

func DeviceTotalMemory() (int64, error)

func DirCopy

func DirCopy(source string, dest string) error

DirCopy copies a directory recursively, overwriting the target if it exists.

func DownloadFileHash

func DownloadFileHash(ctx context.Context, httpClient *http.Client, useragent string, progress func(progress ioprogress.ProgressData), canceler *cancel.HTTPRequestCanceller, filename string, url string, hash string, hashFunc hash.Hash, target io.WriteSeeker) (int64, error)

func EscapePathFstab

func EscapePathFstab(path string) string

EscapePathFstab escapes a path fstab-style. This ensures that getmntent_r() and friends can correctly parse stuff like /some/wacky path with spaces /some/wacky target with spaces.

func ExitStatus

func ExitStatus(err error) (int, error)

ExitStatus extracts the exit status from the error returned by exec.Cmd. If a nil err is provided then an exit status of 0 is returned along with the nil error. If a valid exit status can be extracted from err then it is returned along with a nil error. If no valid exit status can be extracted then a -1 exit status is returned along with the err provided.

func FileCopy

func FileCopy(source string, dest string) error

FileCopy copies a file, overwriting the target if it exists.

func FileMove

func FileMove(oldPath string, newPath string) error

FileMove tries to move a file by using os.Rename, if that fails it tries to copy the file and remove the source.

func FindOrGenCert

func FindOrGenCert(certf string, keyf string, certtype bool, addHosts bool) error

FindOrGenCert generates a keypair if needed. The type argument is false for server, true for client.

func GenCert

func GenCert(certf string, keyf string, certtype bool, addHosts bool) error

GenCert will create and populate a certificate file and a key file.

func GenerateMemCert

func GenerateMemCert(client bool, addHosts bool) ([]byte, []byte, error)

GenerateMemCert creates client or server certificate and key pair, returning them as byte arrays in memory.

func GenerateTrustCertificate

func GenerateTrustCertificate(cert *CertInfo, name string) (*api.Certificate, error)

GenerateTrustCertificate converts the specified serverCert and serverName into an api.Certificate suitable for use as a trusted cluster server certificate.

func GetAllXattr

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

GetAllXattr retrieves all extended attributes associated with a file, directory or symbolic link.

func GetErrno

func GetErrno(err error) (errno error, iserrno bool)

Detect whether err is an errno.

func GetExpiry

func GetExpiry(refDate time.Time, s string) (time.Time, error)

GetExpiry returns the expiry date based on the reference date and a length of time. The length of time format is "<integer>(S|M|H|d|w|m|y)", and can contain multiple such fields, e.g. "1d 3H" (1 day and 3 hours).

func GetFileStat

func GetFileStat(p string) (uid int, gid int, major uint32, minor uint32, inode uint64, nlink int, err error)

func GetMeminfo

func GetMeminfo(field string) (int64, error)

func GetOwnerMode

func GetOwnerMode(fInfo os.FileInfo) (os.FileMode, int, int)

func GetPathMode

func GetPathMode(path string) (os.FileMode, error)

GetPathMode returns a os.FileMode for the provided path.

func GetRemoteCertificate

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

func GetRootDiskDevice

func GetRootDiskDevice(devices map[string]map[string]string) (string, map[string]string, error)

GetRootDiskDevice returns the instance device that is configured as root disk. Returns the device name and device config map.

func GetTLSConfig

func GetTLSConfig(tlsClientCertFile string, tlsClientKeyFile string, tlsClientCAFile string, tlsRemoteCert *x509.Certificate) (*tls.Config, error)

func GetTLSConfigMem

func GetTLSConfigMem(tlsClientCert string, tlsClientKey string, tlsClientCA string, tlsRemoteCertPEM string, insecureSkipVerify bool) (*tls.Config, error)

func HasKey

func HasKey[K comparable, V any](key K, m map[K]V) bool

HasKey returns true if map has key.

func HostPath

func HostPath(path string) string

HostPath returns the host path for the provided path On a normal system, this does nothing When inside of a snap environment, returns the real path.

func HostPathFollow

func HostPathFollow(path string) string

HostPathFollow takes a valid path (from HostPath) and resolves it all the way to its target or to the last which can be resolved.

func InSnap

func InSnap() bool

InSnap returns true if we're running inside the LXD snap.

func InitTLSConfig

func InitTLSConfig() *tls.Config

InitTLSConfig returns a tls.Config populated with default encryption parameters. This is used as baseline config for both client and server certificates used by LXD.

func InstanceIncludeWhenCopying

func InstanceIncludeWhenCopying(configKey string, remoteCopy bool) bool

InstanceIncludeWhenCopying is used to decide whether to include a config item or not when copying an instance. The remoteCopy argument indicates if the copy is remote (i.e between LXD nodes) as this affects the keys kept.

func Int64InSlice

func Int64InSlice(key int64, list []int64) bool

func IntInSlice

func IntInSlice(key int, list []int) bool

func IsBlockdev

func IsBlockdev(fm os.FileMode) bool

func IsBlockdevPath

func IsBlockdevPath(pathName string) bool

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError returns true if the given error is due to the dialer not being able to connect to the target LXD server.

func IsDir

func IsDir(name string) bool

IsDir returns true if the given path is a directory.

func IsFalse

func IsFalse(value string) bool

IsFalse returns true if value is "false", "0", "no" or "off" (case insensitive).

func IsFalseOrEmpty

func IsFalseOrEmpty(value string) bool

IsFalseOrEmpty returns true if value is empty or if IsFalse() returns true.

func IsLoopback

func IsLoopback(iface *net.Interface) bool

func IsRootDiskDevice

func IsRootDiskDevice(device map[string]string) bool

IsRootDiskDevice returns true if the given device representation is configured as root disk for an instance. It typically get passed a specific entry of api.Instance.Devices.

func IsSnapshot

func IsSnapshot(name string) bool

func IsTrue

func IsTrue(value string) bool

IsTrue returns true if value is "true", "1", "yes" or "on" (case insensitive).

func IsTrueOrEmpty

func IsTrueOrEmpty(value string) bool

IsTrueOrEmpty returns true if value is empty or if IsTrue() returns true.

func IsUnixSocket

func IsUnixSocket(path string) bool

IsUnixSocket returns true if the given path is either a Unix socket or a symbolic link pointing at a Unix socket.

func IsUserConfig

func IsUserConfig(key string) bool

func JoinTokenDecode

func JoinTokenDecode(input string) (*api.ClusterMemberJoinToken, error)

JoinTokenDecode decodes a base64 and JSON encode join token.

func JoinUrls

func JoinUrls(baseUrl, p string) (string, error)

JoinUrlPath return the join of the input urls/paths sanitized.

func LogPath

func LogPath(path ...string) string

LogPath returns the directory that LXD should put logs under. If LXD_DIR is set, this path is $LXD_DIR/logs, otherwise it is /var/log/lxd.

func LookupUUIDByBlockDevPath

func LookupUUIDByBlockDevPath(diskDevice string) (string, error)

func MkdirAllOwner

func MkdirAllOwner(path string, perm os.FileMode, uid int, gid int) error

func NewRunError

func NewRunError(cmd string, args []string, err error, stdout *bytes.Buffer, stderr *bytes.Buffer) error

NewRunError returns new RunError.

func OpenPty

func OpenPty(uid, gid int64) (*os.File, *os.File, error)

OpenPty creates a new PTS pair, configures them and returns them.

func OpenPtyInDevpts

func OpenPtyInDevpts(devpts_fd int, uid, gid int64) (*os.File, *os.File, error)

OpenPtyInDevpts creates a new PTS pair, configures them and returns them.

func ParseLXDFileHeaders

func ParseLXDFileHeaders(headers http.Header) (uid int64, gid int64, mode int, type_ string, write string)

func ParseMetadata

func ParseMetadata(metadata any) (map[string]any, error)

func ParseNumberFromFile

func ParseNumberFromFile(file string) (int64, error)

func PathExists

func PathExists(name string) bool

func PathIsEmpty

func PathIsEmpty(path string) (bool, error)

PathIsEmpty checks if the given path is empty.

func ProxyFromConfig

func ProxyFromConfig(httpsProxy string, httpProxy string, noProxy string) func(req *http.Request) (*url.URL, error)

func ProxyFromEnvironment

func ProxyFromEnvironment(req *http.Request) (*url.URL, error)

This is basically the same as golang's ProxyFromEnvironment, except it doesn't fall back to http_proxy when https_proxy isn't around, which is incorrect behavior. It still respects HTTP_PROXY, HTTPS_PROXY, and NO_PROXY.

func RFC3493Dialer

func RFC3493Dialer(context context.Context, network string, address string) (net.Conn, error)

RFC3493Dialer connects to the specified server and returns the connection. If the connection cannot be established then an error with the connectErrorPrefix is returned.

func RandomCryptoString

func RandomCryptoString() (string, error)

Returns a random base64 encoded string from crypto/rand.

func ReadCert

func ReadCert(fpath string) (*x509.Certificate, error)

func ReadStdin

func ReadStdin() ([]byte, error)

func ReaderToChannel

func ReaderToChannel(r io.Reader, bufferSize int) <-chan []byte

func RemoveDuplicatesFromString

func RemoveDuplicatesFromString(s string, sep string) string

RemoveDuplicatesFromString removes all duplicates of the string 'sep' from the specified string 's'. Leading and trailing occurrences of sep are NOT removed (duplicate leading/trailing are). Performs poorly if there are multiple consecutive redundant separators.

func RemoveElementsFromStringSlice

func RemoveElementsFromStringSlice(list []string, elements ...string) []string

RemoveElementsFromStringSlice returns a slice equivalent to removing the given elements from the given list. Elements not present in the list are ignored.

func RenderTemplate

func RenderTemplate(template string, ctx pongo2.Context) (string, error)

RenderTemplate renders a pongo2 template.

func RunCommand

func RunCommand(name string, arg ...string) (string, error)

RunCommand runs a command with optional arguments and returns stdout. If the command fails to start or returns a non-zero exit code then an error is returned containing the output of stderr. Deprecated: Use RunCommandContext.

func RunCommandCLocale

func RunCommandCLocale(name string, arg ...string) (string, error)

RunCommandCLocale runs a command with a LANG=C.UTF-8 and LANGUAGE=en environment set with optional arguments and returns stdout. If the command fails to start or returns a non-zero exit code then an error is returned containing the output of stderr.

func RunCommandContext

func RunCommandContext(ctx context.Context, name string, arg ...string) (string, error)

RunCommandContext runs a command with optional arguments and returns stdout. If the command fails to start or returns a non-zero exit code then an error is returned containing the output of stderr.

func RunCommandInheritFds

func RunCommandInheritFds(ctx context.Context, filesInherit []*os.File, name string, arg ...string) (string, error)

RunCommandInheritFds runs a command with optional arguments and passes a set of file descriptors to the newly created process, returning stdout. If the command fails to start or returns a non-zero exit code then an error is returned containing the output of stderr.

func RunCommandSplit

func RunCommandSplit(ctx context.Context, env []string, filesInherit []*os.File, name string, arg ...string) (string, string, error)

RunCommandSplit runs a command with a supplied environment and optional arguments and returns the resulting stdout and stderr output as separate variables. If the supplied environment is nil then the default environment is used. If the command fails to start or returns a non-zero exit code then an error is returned containing the output of stderr too.

func RunCommandWithFds

func RunCommandWithFds(ctx context.Context, stdin io.Reader, stdout io.Writer, name string, arg ...string) error

RunCommandWithFds runs a command with supplied file descriptors.

func RunningInUserNS

func RunningInUserNS() bool

func SetProgressMetadata

func SetProgressMetadata(metadata map[string]any, stage, displayPrefix string, percent, processed, speed int64)

func SetSize

func SetSize(fd int, width int, height int) (err error)

func SplitNTrimSpace

func SplitNTrimSpace(s string, sep string, n int, nilIfEmpty bool) []string

SplitNTrimSpace returns result of strings.SplitN() and then strings.TrimSpace() on each element. Accepts nilIfEmpty argument which if true, will return nil slice if s is empty (after trimming space).

func StringHasPrefix

func StringHasPrefix(value string, prefixes ...string) bool

StringHasPrefix returns true if value has one of the supplied prefixes.

func StringInSlice

func StringInSlice(key string, list []string) bool

func StringMapHasStringKey

func StringMapHasStringKey(m map[string]string, keys ...string) bool

StringMapHasStringKey returns true if any of the supplied keys are present in the map.

func StringPrefixInSlice

func StringPrefixInSlice(key string, list []string) bool

StringPrefixInSlice returns true if any element in the list has the given prefix.

func TargetDetect

func TargetDetect(target string) (targetNode string, targetGroup string)

TargetDetect returns either target node or group based on the provided prefix: An invocation with `target=h1` returns "h1", "" and `target=@g1` returns "", "g1".

func TextEditor

func TextEditor(inPath string, inContent []byte) ([]byte, error)

Spawn the editor with a temporary YAML file for editing configs.

func TimeIsSet

func TimeIsSet(ts time.Time) bool

func TryRunCommand

func TryRunCommand(name string, arg ...string) (string, error)

TryRunCommand runs the specified command up to 20 times with a 500ms delay between each call until it runs without an error. If after 20 times it is still failing then returns the error.

func URLEncode

func URLEncode(path string, query map[string]string) (string, error)

URLEncode encodes a path and query parameters to a URL.

func Uint64InSlice

func Uint64InSlice(key uint64, list []uint64) bool

func VarPath

func VarPath(path ...string) string

VarPath returns the provided path elements joined by a slash and appended to the end of $LXD_DIR, which defaults to /var/lib/lxd.

func WriteAll

func WriteAll(w io.Writer, data []byte) error

Types

type BytesReadCloser

type BytesReadCloser struct {
	Buf *bytes.Buffer
}

func (BytesReadCloser) Close

func (r BytesReadCloser) Close() error

func (BytesReadCloser) Read

func (r BytesReadCloser) Read(b []byte) (n int, err error)

type CertInfo

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

CertInfo captures TLS certificate information about a certain public/private keypair and an optional CA certificate and CRL.

Given LXD's support for PKI setups, these two bits of information are normally used and passed around together, so this structure helps with that (see doc/security.md for more details).

func KeyPairAndCA

func KeyPairAndCA(dir, prefix string, kind CertKind, addHosts bool) (*CertInfo, error)

KeyPairAndCA returns a CertInfo object with a reference to the key pair and (optionally) CA certificate located in the given directory and having the given name prefix

The naming conversion for the various files is:

<prefix>.crt -> public key <prefix>.key -> private key <prefix>.ca -> CA certificate

If no public/private key files are found, a new key pair will be generated and saved on disk.

If a CA certificate is found, it will be returned as well as second return value (otherwise it will be nil).

func KeyPairFromRaw

func KeyPairFromRaw(certificate []byte, key []byte) (*CertInfo, error)

KeyPairFromRaw returns a CertInfo from the raw certificate and key.

func TestingAltKeyPair

func TestingAltKeyPair() *CertInfo

TestingAltKeyPair returns CertInfo object initialized with a test keypair which differs from the one returned by TestCertInfo. It's meant to be used only by tests.

func TestingKeyPair

func TestingKeyPair() *CertInfo

TestingKeyPair returns CertInfo object initialized with a test keypair. It's meant to be used only by tests.

func (*CertInfo) CA

func (c *CertInfo) CA() *x509.Certificate

CA returns the CA certificate.

func (*CertInfo) CRL

func (c *CertInfo) CRL() *pkix.CertificateList

CRL returns the certificate revocation list.

func (*CertInfo) Fingerprint

func (c *CertInfo) Fingerprint() string

Fingerprint returns the fingerprint of the public key.

func (*CertInfo) KeyPair

func (c *CertInfo) KeyPair() tls.Certificate

KeyPair returns the public/private key pair.

func (*CertInfo) PrivateKey

func (c *CertInfo) PrivateKey() []byte

PrivateKey is a convenience to encode the underlying private key.

func (*CertInfo) PublicKey

func (c *CertInfo) PublicKey() []byte

PublicKey is a convenience to encode the underlying public key to ASCII.

func (*CertInfo) PublicKeyX509

func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error)

PublicKeyX509 is a convenience to return the underlying public key as an *x509.Certificate.

type CertKind

type CertKind int

CertKind defines the kind of certificate to generate from scratch in KeyPairAndCA when it's not there.

The two possible kinds are client and server, and they differ in the ext-key-usage bitmaps. See GenerateMemCert for more details.

const (
	CertClient CertKind = iota
	CertServer
)

Possible kinds of certificates.

type IPRange

type IPRange struct {
	Start net.IP
	End   net.IP
}

IPRange defines a range of IP addresses. Optionally just set Start to indicate a single IP.

func (*IPRange) ContainsIP

func (r *IPRange) ContainsIP(ip net.IP) bool

ContainsIP tests whether a supplied IP falls within the IPRange.

func (*IPRange) String

func (r *IPRange) String() string

type InstanceAction

type InstanceAction string

InstanceAction indicates the type of action being performed.

const (
	Stop     InstanceAction = "stop"
	Start    InstanceAction = "start"
	Restart  InstanceAction = "restart"
	Freeze   InstanceAction = "freeze"
	Unfreeze InstanceAction = "unfreeze"
)

InstanceAction types.

type Jmap

type Jmap map[string]any

func (Jmap) GetBool

func (m Jmap) GetBool(key string) (bool, error)

func (Jmap) GetInt

func (m Jmap) GetInt(key string) (int, error)

func (Jmap) GetMap

func (m Jmap) GetMap(key string) (Jmap, error)

func (Jmap) GetString

func (m Jmap) GetString(key string) (string, error)

type QuotaWriter

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

QuotaWriter returns an error once a given write quota gets exceeded.

func NewQuotaWriter

func NewQuotaWriter(writer io.Writer, quota int64) *QuotaWriter

NewQuotaWriter returns a new QuotaWriter wrapping the given writer.

If the given quota is negative, then no quota is applied.

func (*QuotaWriter) Write

func (w *QuotaWriter) Write(p []byte) (n int, err error)

Write implements the Writer interface.

type ReadSeeker

type ReadSeeker struct {
	io.Reader
	io.Seeker
}

func NewReadSeeker

func NewReadSeeker(reader io.Reader, seeker io.Seeker) *ReadSeeker

func (*ReadSeeker) Read

func (r *ReadSeeker) Read(p []byte) (n int, err error)

func (*ReadSeeker) Seek

func (r *ReadSeeker) Seek(offset int64, whence int) (int64, error)

type RunError

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

RunError is the error from the RunCommand family of functions.

func (RunError) Error

func (e RunError) Error() string

func (RunError) StdErr

func (e RunError) StdErr() *bytes.Buffer

StdErr returns the stdout buffer.

func (RunError) StdOut

func (e RunError) StdOut() *bytes.Buffer

StdOut returns the stdout buffer.

func (RunError) Unwrap

func (e RunError) Unwrap() error

type Utsname

type Utsname struct {
	Sysname    string
	Nodename   string
	Release    string
	Version    string
	Machine    string
	Domainname string
}

Utsname returns the same info as unix.Utsname, as strings.

func Uname

func Uname() (*Utsname, error)

Uname returns Utsname as strings.

Directories

Path Synopsis
api
Package api contains Go structs for all LXD API objects
Package api contains Go structs for all LXD API objects
Package dnsutil copied from coredns project https://github.com/coredns/coredns/blob/master/plugin/pkg/dnsutil/reverse.go
Package dnsutil copied from coredns project https://github.com/coredns/coredns/blob/master/plugin/pkg/dnsutil/reverse.go

Jump to

Keyboard shortcuts

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