shared

package
v0.0.0-...-ff4e629 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, Apache-2.0 Imports: 47 Imported by: 36

Documentation

Overview

Example (IpRangesOverlap)
rangePairs := [][2]string{
	{"10.1.1.1-10.1.1.2", "10.1.1.3-10.1.1.4"},
	{"10.1.1.1-10.1.2.1", "10.1.1.254-10.1.1.255"},
	{"10.1.1.1-10.1.1.6", "10.1.1.5-10.1.1.9"},
	{"10.1.1.5-10.1.1.9", "10.1.1.1-10.1.1.6"},
	{"::1-::2", "::3-::4"},
	{"::1-::6", "::5-::9"},
	{"::5-::9", "::1-::6"},
}

for _, pair := range rangePairs {
	r0, _ := ParseIPRange(pair[0])
	r1, _ := ParseIPRange(pair[1])
	result := r0.Overlaps(r1)
	fmt.Printf("Range1: %v, Range2: %v, overlapped: %t\n", r0, r1, result)
}

// also do a couple of tests with ranges that have no end
singleIPRange := &IPRange{
	Start: net.ParseIP("10.1.1.4"),
}

otherRange, _ := ParseIPRange("10.1.1.1-10.1.1.6")

fmt.Printf("Range1: %v, Range2: %v, overlapped: %t\n", singleIPRange, otherRange, singleIPRange.Overlaps(otherRange))
fmt.Printf("Range1: %v, Range2: %v, overlapped: %t\n", otherRange, singleIPRange, otherRange.Overlaps(singleIPRange))
fmt.Printf("Range1: %v, Range2: %v, overlapped: %t\n", singleIPRange, singleIPRange, singleIPRange.Overlaps(singleIPRange))

otherRange, _ = ParseIPRange("10.1.1.8-10.1.1.9")

fmt.Printf("Range1: %v, Range2: %v, overlapped: %t\n", singleIPRange, otherRange, singleIPRange.Overlaps(otherRange))
fmt.Printf("Range1: %v, Range2: %v, overlapped: %t\n", otherRange, singleIPRange, otherRange.Overlaps(singleIPRange))
Output:

Range1: 10.1.1.1-10.1.1.2, Range2: 10.1.1.3-10.1.1.4, overlapped: false
Range1: 10.1.1.1-10.1.2.1, Range2: 10.1.1.254-10.1.1.255, overlapped: true
Range1: 10.1.1.1-10.1.1.6, Range2: 10.1.1.5-10.1.1.9, overlapped: true
Range1: 10.1.1.5-10.1.1.9, Range2: 10.1.1.1-10.1.1.6, overlapped: true
Range1: ::1-::2, Range2: ::3-::4, overlapped: false
Range1: ::1-::6, Range2: ::5-::9, overlapped: true
Range1: ::5-::9, Range2: ::1-::6, overlapped: true
Range1: 10.1.1.4, Range2: 10.1.1.1-10.1.1.6, overlapped: true
Range1: 10.1.1.1-10.1.1.6, Range2: 10.1.1.4, overlapped: true
Range1: 10.1.1.4, Range2: 10.1.1.4, overlapped: true
Range1: 10.1.1.4, Range2: 10.1.1.8-10.1.1.9, overlapped: false
Range1: 10.1.1.8-10.1.1.9, Range2: 10.1.1.4, overlapped: false
Example (ParseIPRange)
_, allowedv4NetworkA, _ := net.ParseCIDR("192.168.1.0/24")
_, allowedv4NetworkB, _ := net.ParseCIDR("192.168.0.0/16")
_, allowedv6NetworkA, _ := net.ParseCIDR("fd22:c952:653e:3df6::/64")
_, allowedv6NetworkB, _ := net.ParseCIDR("fd22:c952:653e::/48")

ipRanges := []string{
	// Ranges within allowedv4NetworkA.
	"192.168.1.1-192.168.1.255",
	"0.0.0.1-192.168.1.255",
	"0.0.0.1-0.0.0.255",
	// Ranges outsde of allowedv4NetworkA but within allowedv4NetworkB.
	"192.168.0.1-192.168.0.255",
	"192.168.0.0-192.168.0.0",
	"0.0.2.0-0.0.2.255",
	// Invalid IP ranges.
	"0.0.0.0.1-192.168.1.255",
	"192.0.0.1-192.0.0.255",
	"0.0.0.1-1.0.0.255",
	"0.0.2.1-0.0.0.255",
	// Ranges within allowedv6NetworkA.
	"fd22:c952:653e:3df6::1-fd22:c952:653e:3df6::FFFF",
	"::1-::FFFF",
	// Ranges outsde of allowedv6NetworkA but within allowedv6NetworkB.
	"fd22:c952:653e:FFFF::1-fd22:c952:653e:FFFF::FFFF",
	"::AAAA:FFFF:FFFF:FFFF:1-::AAAA:FFFF:FFFF:FFFF:FFFF",
}

fmt.Println("With allowed networks")
for _, ipRange := range ipRanges {
	parsedRange, err := ParseIPRange(ipRange, allowedv4NetworkA, allowedv4NetworkB, allowedv6NetworkA, allowedv6NetworkB)
	if err != nil {
		fmt.Printf("Err: %v\n", err)
		continue
	}

	fmt.Printf("Start: %s, End: %s\n", parsedRange.Start.String(), parsedRange.End.String())
}

fmt.Println("Without allowed networks")
for _, ipRange := range ipRanges {
	parsedRange, err := ParseIPRange(ipRange)
	if err != nil {
		fmt.Printf("Err: %v\n", err)
		continue
	}

	fmt.Printf("Start: %s, End: %s\n", parsedRange.Start.String(), parsedRange.End.String())
}
Output:

With allowed networks
Start: 192.168.1.1, End: 192.168.1.255
Start: 192.168.1.1, End: 192.168.1.255
Start: 192.168.1.1, End: 192.168.1.255
Start: 192.168.0.1, End: 192.168.0.255
Start: 192.168.0.0, End: 192.168.0.0
Start: 192.168.2.0, End: 192.168.2.255
Err: Start IP "0.0.0.0.1" is invalid
Err: IP range "192.0.0.1-192.0.0.255" does not fall within any of the allowed networks [192.168.1.0/24 192.168.0.0/16 fd22:c952:653e:3df6::/64 fd22:c952:653e::/48]
Err: IP range "0.0.0.1-1.0.0.255" does not fall within any of the allowed networks [192.168.1.0/24 192.168.0.0/16 fd22:c952:653e:3df6::/64 fd22:c952:653e::/48]
Err: Start IP "0.0.2.1" must be less than End IP "0.0.0.255"
Start: fd22:c952:653e:3df6::1, End: fd22:c952:653e:3df6::ffff
Start: fd22:c952:653e:3df6::1, End: fd22:c952:653e:3df6::ffff
Start: fd22:c952:653e:ffff::1, End: fd22:c952:653e:ffff::ffff
Start: fd22:c952:653e:aaaa:ffff:ffff:ffff:1, End: fd22:c952:653e:aaaa:ffff:ffff:ffff:ffff
Without allowed networks
Start: 192.168.1.1, End: 192.168.1.255
Start: 0.0.0.1, End: 192.168.1.255
Start: 0.0.0.1, End: 0.0.0.255
Start: 192.168.0.1, End: 192.168.0.255
Start: 192.168.0.0, End: 192.168.0.0
Start: 0.0.2.0, End: 0.0.2.255
Err: Start IP "0.0.0.0.1" is invalid
Start: 192.0.0.1, End: 192.0.0.255
Start: 0.0.0.1, End: 1.0.0.255
Err: Start IP "0.0.2.1" must be less than End IP "0.0.0.255"
Start: fd22:c952:653e:3df6::1, End: fd22:c952:653e:3df6::ffff
Start: ::1, End: ::ffff
Start: fd22:c952:653e:ffff::1, End: fd22:c952:653e:ffff::ffff
Start: ::aaaa:ffff:ffff:ffff:1, End: ::aaaa:ffff:ffff:ffff:ffff

Index

Examples

Constants

View Source
const HTTPDefaultPort = 8080

HTTPDefaultPort is the default port for the LXD HTTP listener.

View Source
const HTTPSDefaultPort = 8443

HTTPSDefaultPort is the default port for the LXD HTTPS listener.

View Source
const HTTPSMetricsDefaultPort = 9100

HTTPSMetricsDefaultPort is the default port for LXD metrics.

View Source
const HTTPSStorageBucketsDefaultPort = 9000

HTTPSStorageBucketsDefaultPort is the default port for the storage buckets listener.

View Source
const SnapshotDelimiter = "/"

SnapshotDelimiter is the character used to delimit instance and snapshot names.

Variables

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

ErrObjectFound indicates that the requested object was found.

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 ApplyDeviceOverrides

func ApplyDeviceOverrides(localDevices map[string]map[string]string, profileDevices map[string]map[string]string, deviceOverrides map[string]map[string]string) (map[string]map[string]string, error)

ApplyDeviceOverrides handles the logic for applying device overrides. Receives the profile and local devices and the device overrides. Returns the resulting list of devices.

func AtoiEmptyDefault

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

AtoiEmptyDefault returns the default value if the string is empty, otherwise converts it to an integer.

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

CertFingerprint returns the SHA256 fingerprint of a X.509 certificate.

func CertFingerprintStr

func CertFingerprintStr(c string) (string, error)

CertFingerprintStr returns the certificate fingerprint of a X.509 certificate provided as string.

func CertificateTokenDecode

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

CertificateTokenDecode decodes a base64 and JSON encoded certificate add token.

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)

DeviceTotalMemory returns the total memory of the device by reading /proc/meminfo.

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)

DownloadFileHash downloads a file from the specified URL and writes it to the target, optionally verifying the file's hash using the provided hash function. The function either returns the number of bytes written or an error if the download fails or the hash does not match.

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, options CertOptions) 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, options CertOptions) error

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

func GenerateMemCert

func GenerateMemCert(client bool, options CertOptions) ([]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)

GetErrno detects whether the error 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)

GetFileStat retrieves the UID, GID, major and minor device numbers, inode, and number of hard links for the given file path.

func GetMeminfo

func GetMeminfo(field string) (int64, error)

GetMeminfo retrieves the memory information for the specified field from /proc/meminfo.

func GetOwnerMode

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

GetOwnerMode retrieves the file mode, user ID, and group ID for the given file.

func GetPathMode

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

GetPathMode returns a os.FileMode for the provided path.

func GetPollRevents

func GetPollRevents(fd int, timeout int, flags int) (n int, revents int, err error)

GetPollRevents poll for events on provided fd.

func GetRemoteCertificate

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

GetRemoteCertificate returns the unverified peer certificate found at a remote address.

func GetTLSConfig

func GetTLSConfig(tlsRemoteCert *x509.Certificate) (*tls.Config, error)

GetTLSConfig returns a client TLS configuration suitable for requests to LXD.

func GetTLSConfigMem

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

GetTLSConfigMem returns a client TLS configuration suitable for requests to LXD, including client certificates for mTLS.

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 IsBlockdev

func IsBlockdev(fm os.FileMode) bool

IsBlockdev determines if a given file mode represents a block device. It returns true if the mode has the os.ModeDevice bit set and the os.ModeCharDevice bit not set.

func IsBlockdevPath

func IsBlockdevPath(pathName string) bool

IsBlockdevPath checks if the given path corresponds to a block device.

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

IsLoopback returns true if the given interface is a loopback interface.

func IsSnapshot

func IsSnapshot(name string) bool

IsSnapshot returns true if a given name contains the snapshot delimiter.

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

IsUserConfig returns true if the key starts with the prefix "user.".

func JoinTokenDecode

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

JoinTokenDecode decodes a base64 and JSON encoded join token.

func JoinUrls

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

JoinUrls returns 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)

LookupUUIDByBlockDevPath finds and returns the UUID of a block device by its path.

func MkdirAllOwner

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

MkdirAllOwner creates a directory named path, along with any necessary parents, and with specified permissions. It sets the ownership of the created directories to the provided uid and gid.

func NewExecWrapper

func NewExecWrapper(ctx context.Context, f *os.File) io.ReadWriteCloser

NewExecWrapper returns a new ReadWriteCloser wrapper for an os.File. The ctx is used to indicate when the executed process has ended, at which point any further Read calls will return io.EOF rather than potentially blocking on the poll syscall if the process is a shell that still has background processes running that are not producing any output.

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(devptsFD int, uid, gid int64) (*os.File, *os.File, error)

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

func ParseCert

func ParseCert(cert []byte) (*x509.Certificate, error)

ParseCert parse a X.509 certificate from the given byte slice and return its parsed content.

func ParseMetadata

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

ParseMetadata converts the provided metadata into a map[string]any. An error is returned if the input is not a valid map or if the keys are not strings.

func ParseNumberFromFile

func ParseNumberFromFile(file string) (int64, error)

ParseNumberFromFile reads a file content and tries to extract a number as int64 from it.

func PathExists

func PathExists(name string) bool

PathExists checks if the given path exists in the filesystem.

func PathIsEmpty

func PathIsEmpty(path string) (bool, error)

PathIsEmpty checks if the given path is empty.

func PathIsWritable

func PathIsWritable(path string) bool

PathIsWritable returns true if the given path is writable and false otherwise.

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)

RandomCryptoString generates 32 bytes long cryptographically secure random string.

func ReadCert

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

ReadCert reads a X.509 certificate from the filesystem, do PEM decoding and return its parsed content.

func ReadStdin

func ReadStdin() ([]byte, error)

ReadStdin reads a line of input from stdin and returns it as a byte slice.

func ReaderToChannel

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

ReaderToChannel reads data from an io.Reader and sends it to a returned channel in chunks. The function also takes the buffer size, which defaults to 128 KiB if the provided value is smaller.

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 RemoveElementsFromSlice

func RemoveElementsFromSlice[T comparable](list []T, elements ...T) []T

RemoveElementsFromSlice 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 LC_ALL=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) (stdOutput string, stdError string, err 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

RunningInUserNS checks if the current process is running inside a user namespace.

func SetProgressMetadata

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

SetProgressMetadata updates the provided metadata map with progress information, including the percentage complete, data processed, and speed. It formats and stores these values for both API callers and CLI display purposes.

func SetSize

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

SetSize sets the terminal size to the specified width and height for the given file descriptor.

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 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)

TextEditor opens a text editor with a temporary YAML file for editing configs.

func TimeIsSet

func TimeIsSet(ts time.Time) bool

TimeIsSet checks if the provided time is set to a valid timestamp. It returns false if the timestamp is zero or negative, and true otherwise.

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 ValueInSlice

func ValueInSlice[T comparable](key T, list []T) bool

ValueInSlice returns true if key is in list.

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

WriteAll writes all data from the byte slice to the given writer.

Types

type BytesReadCloser

type BytesReadCloser struct {
	Buf *bytes.Buffer
}

BytesReadCloser wraps a bytes.Buffer to implement io.ReadCloser.

func (BytesReadCloser) Close

func (r BytesReadCloser) Close() error

Close is a no-op as the data is in memory.

func (BytesReadCloser) Read

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

Read reads data from the buffer into b.

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 few 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, options CertOptions) (*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 PEM encoded files is:

<prefix>.crt -> public key <prefix>.key -> private key <prefix>.ca -> CA certificate (optional) ca.crl -> CA certificate revocation list (optional)

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 NewCertInfo

func NewCertInfo(keypair tls.Certificate, ca *x509.Certificate, crl *x509.RevocationList) *CertInfo

NewCertInfo returns a CertInfo struct populated with the given TLS certificate information.

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() *x509.RevocationList

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 CertOptions

type CertOptions struct {
	// AddHosts determines whether to populate the Subject Alternative Name DNS Names and IP Addresses fields.
	AddHosts bool

	// CommonName will be used in place of the system hostname for the SAN DNS Name and Issuer Common Name.
	CommonName string

	// SubjectAlternativeNames contains other names to include in the SAN DNS name field in addition to CommonName.
	SubjectAlternativeNames []string
}

CertOptions holds configuration for creating a new CertInfo.

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 ParseIPRange

func ParseIPRange(ipRange string, allowedNets ...*net.IPNet) (*IPRange, error)

ParseIPRange parses an IP range in the format "start-end" and converts it to a shared.IPRange. If allowedNets are supplied, then each IP in the range is checked that it belongs to at least one of them. IPs in the range can be zero prefixed, e.g. "::1" or "0.0.0.1", however they should not overlap with any supplied allowedNets prefixes. If they are within an allowed network, any zero prefixed addresses are returned combined with the first allowed network they are within. If no allowedNets supplied they are returned as-is.

func ParseIPRanges

func ParseIPRanges(ipRangesList string, allowedNets ...*net.IPNet) ([]*IPRange, error)

ParseIPRanges parses a comma separated list of IP ranges using ParseIPRange.

func (*IPRange) ContainsIP

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

ContainsIP tests whether a supplied IP falls within the IPRange.

func (*IPRange) Overlaps

func (r *IPRange) Overlaps(otherRange *IPRange) bool

Overlaps checks whether two ip ranges have ip addresses in common.

func (*IPRange) String

func (r *IPRange) String() string

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 LXDFileHeaders

type LXDFileHeaders struct {
	UID  int64
	GID  int64
	Mode int

	GIDModifyExisting  bool
	UIDModifyExisting  bool
	ModeModifyExisting bool

	Type  string
	Write string
}

LXDFileHeaders is extracted from the `X-LXD-*` family of file permissions headers.

func ParseLXDFileHeaders

func ParseLXDFileHeaders(headers http.Header) (*LXDFileHeaders, error)

ParseLXDFileHeaders parses and validates the `X-LXD-*` family of file permissions headers.

  • `X-LXD-uid`, `X-LXD-gid` Base 10 integer
  • `X-LXD-mode` Base 10 integer (no leading `0`) or base 8 integer (leading `0`) for the unix permissions bits
  • `X-LXD-type` One of `file`, `symlink`, `directory`
  • `X-LXD-write` One of `overwrite`, `append`
  • `X-LXD-modify-perm` Comma separated list; 0 or more of `mode`, `uid`, `gid`

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
}

ReadSeeker is a composite type that embeds both io.Reader and io.Seeker.

func NewReadSeeker

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

NewReadSeeker creates a new ReadSeeker from the provided io.Reader and io.Seeker.

func (*ReadSeeker) Read

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

Read reads from the embedded io.Reader into the provided slice of bytes.

func (*ReadSeeker) Seek

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

Seek sets the offset for the next Read or Write operation, based on the reference point specified by whence.

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