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 ¶
- Constants
- Variables
- func AddSlash(path string) string
- func AllocatePort() (int, error)
- func ApplyDeviceOverrides(localDevices map[string]map[string]string, ...) (map[string]map[string]string, error)
- func AtoiEmptyDefault(s string, def int) (int, error)
- func CachePath(path ...string) string
- func CertFingerprint(cert *x509.Certificate) string
- func CertFingerprintStr(c string) (string, error)
- func CertificateTokenDecode(input string) (*api.CertificateAddToken, error)
- func DeepCopy(src, dest any) error
- func DetectCompression(fname string) ([]string, string, []string, error)
- func DetectCompressionFile(f io.Reader) ([]string, string, []string, error)
- func DeviceTotalMemory() (int64, error)
- func DirCopy(source string, dest string) error
- func DownloadFileHash(ctx context.Context, httpClient *http.Client, useragent string, ...) (int64, error)
- func EscapePathFstab(path string) string
- func ExitStatus(err error) (int, error)
- func FileCopy(source string, dest string) error
- func FileMove(oldPath string, newPath string) error
- func FindOrGenCert(certf string, keyf string, certtype bool, options CertOptions) error
- func GenCert(certf string, keyf string, certtype bool, options CertOptions) error
- func GenerateMemCert(client bool, options CertOptions) ([]byte, []byte, error)
- func GenerateTrustCertificate(cert *CertInfo, name string) (*api.Certificate, error)
- func GetAllXattr(path string) (map[string]string, error)
- func GetErrno(err error) (errno error, iserrno bool)
- func GetExpiry(refDate time.Time, s string) (time.Time, error)
- func GetFileStat(p string) (uid int, gid int, major uint32, minor uint32, inode uint64, nlink int, ...)
- func GetMeminfo(field string) (int64, error)
- func GetOwnerMode(fInfo os.FileInfo) (os.FileMode, int, int)
- func GetPathMode(path string) (os.FileMode, error)
- func GetPollRevents(fd int, timeout int, flags int) (n int, revents int, err error)
- func GetRemoteCertificate(address string, useragent string) (*x509.Certificate, error)
- func GetTLSConfig(tlsRemoteCert *x509.Certificate) (*tls.Config, error)
- func GetTLSConfigMem(tlsClientCert string, tlsClientKey string, tlsClientCA string, ...) (*tls.Config, error)
- func HasKey[K comparable, V any](key K, m map[K]V) bool
- func HostPath(path string) string
- func HostPathFollow(path string) string
- func InSnap() bool
- func InitTLSConfig() *tls.Config
- func IsBlockdev(fm os.FileMode) bool
- func IsBlockdevPath(pathName string) bool
- func IsConnectionError(err error) bool
- func IsDir(name string) bool
- func IsFalse(value string) bool
- func IsFalseOrEmpty(value string) bool
- func IsLoopback(iface *net.Interface) bool
- func IsSnapshot(name string) bool
- func IsTrue(value string) bool
- func IsTrueOrEmpty(value string) bool
- func IsUnixSocket(path string) bool
- func IsUserConfig(key string) bool
- func JoinTokenDecode(input string) (*api.ClusterMemberJoinToken, error)
- func JoinUrls(baseURL string, p string) (string, error)
- func LogPath(path ...string) string
- func LookupUUIDByBlockDevPath(diskDevice string) (string, error)
- func MkdirAllOwner(path string, perm os.FileMode, uid int, gid int) error
- func NewExecWrapper(ctx context.Context, f *os.File) io.ReadWriteCloser
- func NewRunError(cmd string, args []string, err error, stdout *bytes.Buffer, ...) error
- func OpenPty(uid, gid int64) (*os.File, *os.File, error)
- func OpenPtyInDevpts(devptsFD int, uid, gid int64) (*os.File, *os.File, error)
- func ParseCert(cert []byte) (*x509.Certificate, error)
- func ParseMetadata(metadata any) (map[string]any, error)
- func ParseNumberFromFile(file string) (int64, error)
- func PathExists(name string) bool
- func PathIsEmpty(path string) (bool, error)
- func PathIsWritable(path string) bool
- func ProxyFromConfig(httpsProxy string, httpProxy string, noProxy string) func(req *http.Request) (*url.URL, error)
- func ProxyFromEnvironment(req *http.Request) (*url.URL, error)
- func RFC3493Dialer(context context.Context, network string, address string) (net.Conn, error)
- func RandomCryptoString() (string, error)
- func ReadCert(fpath string) (*x509.Certificate, error)
- func ReadStdin() ([]byte, error)
- func ReaderToChannel(r io.Reader, bufferSize int) <-chan []byte
- func RemoveDuplicatesFromString(s string, sep string) string
- func RemoveElementsFromSlice[T comparable](list []T, elements ...T) []T
- func RenderTemplate(template string, ctx pongo2.Context) (string, error)
- func RunCommand(name string, arg ...string) (string, error)
- func RunCommandCLocale(name string, arg ...string) (string, error)
- func RunCommandContext(ctx context.Context, name string, arg ...string) (string, error)
- func RunCommandInheritFds(ctx context.Context, filesInherit []*os.File, name string, arg ...string) (string, error)
- func RunCommandSplit(ctx context.Context, env []string, filesInherit []*os.File, name string, ...) (stdOutput string, stdError string, err error)
- func RunCommandWithFds(ctx context.Context, stdin io.Reader, stdout io.Writer, name string, ...) error
- func RunningInUserNS() bool
- func SetProgressMetadata(metadata map[string]any, stage, displayPrefix string, ...)
- func SetSize(fd int, width int, height int) (err error)
- func SplitNTrimSpace(s string, sep string, n int, nilIfEmpty bool) []string
- func StringHasPrefix(value string, prefixes ...string) bool
- func StringMapHasStringKey(m map[string]string, keys ...string) bool
- func StringPrefixInSlice(key string, list []string) bool
- func TargetDetect(target string) (targetNode string, targetGroup string)
- func TextEditor(inPath string, inContent []byte) ([]byte, error)
- func TimeIsSet(ts time.Time) bool
- func TryRunCommand(name string, arg ...string) (string, error)
- func URLEncode(path string, query map[string]string) (string, error)
- func ValueInSlice[T comparable](key T, list []T) bool
- func VarPath(path ...string) string
- func WriteAll(w io.Writer, data []byte) error
- type BytesReadCloser
- type CertInfo
- func KeyPairAndCA(dir, prefix string, kind CertKind, options CertOptions) (*CertInfo, error)
- func KeyPairFromRaw(certificate []byte, key []byte) (*CertInfo, error)
- func NewCertInfo(keypair tls.Certificate, ca *x509.Certificate, crl *x509.RevocationList) *CertInfo
- func TestingAltKeyPair() *CertInfo
- func TestingKeyPair() *CertInfo
- func (c *CertInfo) CA() *x509.Certificate
- func (c *CertInfo) CRL() *x509.RevocationList
- func (c *CertInfo) Fingerprint() string
- func (c *CertInfo) KeyPair() tls.Certificate
- func (c *CertInfo) PrivateKey() []byte
- func (c *CertInfo) PublicKey() []byte
- func (c *CertInfo) PublicKeyX509() (*x509.Certificate, error)
- type CertKind
- type CertOptions
- type IPRange
- type Jmap
- type LXDFileHeaders
- type QuotaWriter
- type ReadSeeker
- type RunError
- type Utsname
Examples ¶
Constants ¶
const HTTPDefaultPort = 8080
HTTPDefaultPort is the default port for the LXD HTTP listener.
const HTTPSDefaultPort = 8443
HTTPSDefaultPort is the default port for the LXD HTTPS listener.
const HTTPSMetricsDefaultPort = 9100
HTTPSMetricsDefaultPort is the default port for LXD metrics.
const HTTPSStorageBucketsDefaultPort = 9000
HTTPSStorageBucketsDefaultPort is the default port for the storage buckets listener.
const SnapshotDelimiter = "/"
SnapshotDelimiter is the character used to delimit instance and snapshot names.
Variables ¶
var ErrObjectFound = fmt.Errorf("Found requested object")
ErrObjectFound indicates that the requested object was found.
Functions ¶
func AddSlash ¶
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 ¶
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 ¶
AtoiEmptyDefault returns the default value if the string is empty, otherwise converts it to an integer.
func CachePath ¶
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 ¶
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 DetectCompression ¶
DetectCompression detects compression from a file name.
func DetectCompressionFile ¶
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 ¶
DeviceTotalMemory returns the total memory of the device by reading /proc/meminfo.
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 ¶
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 ¶
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 FileMove ¶
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 ¶
GetAllXattr retrieves all extended attributes associated with a file, directory or symbolic link.
func GetExpiry ¶
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 ¶
GetMeminfo retrieves the memory information for the specified field from /proc/meminfo.
func GetOwnerMode ¶
GetOwnerMode retrieves the file mode, user ID, and group ID for the given file.
func GetPathMode ¶
GetPathMode returns a os.FileMode for the provided path.
func GetPollRevents ¶
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 ¶
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 ¶
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 InitTLSConfig ¶
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 ¶
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 ¶
IsBlockdevPath checks if the given path corresponds to a block device.
func IsConnectionError ¶
IsConnectionError returns true if the given error is due to the dialer not being able to connect to the target LXD server.
func IsFalseOrEmpty ¶
IsFalseOrEmpty returns true if value is empty or if IsFalse() returns true.
func IsLoopback ¶
IsLoopback returns true if the given interface is a loopback interface.
func IsSnapshot ¶
IsSnapshot returns true if a given name contains the snapshot delimiter.
func IsTrueOrEmpty ¶
IsTrueOrEmpty returns true if value is empty or if IsTrue() returns true.
func IsUnixSocket ¶
IsUnixSocket returns true if the given path is either a Unix socket or a symbolic link pointing at a Unix socket.
func IsUserConfig ¶
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 LogPath ¶
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 ¶
LookupUUIDByBlockDevPath finds and returns the UUID of a block device by its path.
func MkdirAllOwner ¶
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 ¶
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 OpenPtyInDevpts ¶
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 ¶
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 ¶
ParseNumberFromFile reads a file content and tries to extract a number as int64 from it.
func PathExists ¶
PathExists checks if the given path exists in the filesystem.
func PathIsEmpty ¶
PathIsEmpty checks if the given path is empty.
func PathIsWritable ¶
PathIsWritable returns true if the given path is writable and false otherwise.
func ProxyFromConfig ¶
func ProxyFromEnvironment ¶
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 ¶
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 ¶
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 ReaderToChannel ¶
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 ¶
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 ¶
RenderTemplate renders a pongo2 template.
func RunCommand ¶
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 ¶
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 ¶
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 ¶
SetSize sets the terminal size to the specified width and height for the given file descriptor.
func SplitNTrimSpace ¶
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 ¶
StringHasPrefix returns true if value has one of the supplied prefixes.
func StringMapHasStringKey ¶
StringMapHasStringKey returns true if any of the supplied keys are present in the map.
func StringPrefixInSlice ¶
StringPrefixInSlice returns true if any element in the list has the given prefix.
func TargetDetect ¶
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 ¶
TextEditor opens a text editor with a temporary YAML file for editing configs.
func TimeIsSet ¶
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 ¶
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 ValueInSlice ¶
func ValueInSlice[T comparable](key T, list []T) bool
ValueInSlice returns true if key is in list.
Types ¶
type BytesReadCloser ¶
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.
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 ¶
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) CRL ¶
func (c *CertInfo) CRL() *x509.RevocationList
CRL returns the certificate revocation list.
func (*CertInfo) Fingerprint ¶
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 ¶
PrivateKey is a convenience to encode the underlying private key.
func (*CertInfo) PublicKey ¶
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.
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 ¶
IPRange defines a range of IP addresses. Optionally just set Start to indicate a single IP.
func ParseIPRange ¶
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 ¶
ParseIPRanges parses a comma separated list of IP ranges using ParseIPRange.
func (*IPRange) ContainsIP ¶
ContainsIP tests whether a supplied IP falls within the IPRange.
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.
type ReadSeeker ¶
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
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 |