shared

package
v0.0.0-...-a810e79 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2021 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Index

Constants

View Source
const ABSTRACT_UNIX_SOCK_LEN int = C.ABSTRACT_UNIX_SOCK_LEN
View Source
const ConfigVolatilePrefix = "volatile."

ConfigVolatilePrefix indicates the prefix used for volatile config keys.

View Source
const DefaultPort = 8443
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 KnownInstanceConfigKeys = 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),

	"limits.cpu": func(value string) error {
		if value == "" {
			return nil
		}

		match, _ := regexp.MatchString("^[-,0-9]*$", value)
		if !match {
			return fmt.Errorf("Invalid CPU limit syntax")
		}

		if strings.HasPrefix(value, "-") || strings.HasPrefix(value, ",") {
			return fmt.Errorf("CPU limit can't start with a separator")
		}

		if strings.HasSuffix(value, "-") || strings.HasSuffix(value, ",") {
			return fmt.Errorf("CPU limit can't end with a separator")
		}

		return nil
	},
	"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.disk.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": func(value string) error {
		if value == "" {
			return nil
		}

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

			return nil
		}

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

		return nil
	},
	"limits.memory.enforce": func(value string) error {
		return validate.IsOneOf(value, []string{"soft", "hard"})
	},
	"limits.memory.swap":          validate.Optional(validate.IsBool),
	"limits.memory.swap.priority": validate.Optional(validate.IsPriority),
	"limits.memory.hugepages":     validate.Optional(validate.IsBool),

	"limits.network.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),
	"migration.stateful":                      validate.Optional(validate.IsBool),

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

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

	"security.protection.delete": validate.Optional(validate.IsBool),
	"security.protection.shift":  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.secureboot": 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.setxattr":      validate.Optional(validate.IsBool),
	"security.syscalls.whitelist":               validate.IsAny,

	"snapshots.schedule": func(value string) error {
		if value == "" {
			return nil
		}

		if len(strings.Split(value, " ")) != 5 {
			return fmt.Errorf("Schedule must be of the form: <minute> <hour> <day-of-month> <month> <day-of-week>")
		}

		_, err := cron.Parse(fmt.Sprintf("* %s", value))
		if err != nil {
			return errors.Wrap(err, "Error parsing schedule")
		}

		return nil
	},
	"snapshots.schedule.stopped": validate.Optional(validate.IsBool),
	"snapshots.pattern":          validate.IsAny,
	"snapshots.expiry": func(value string) error {

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

	"raw.apparmor": validate.IsAny,
	"raw.idmap":    validate.IsAny,
	"raw.lxc":      validate.IsAny,
	"raw.qemu":     validate.IsAny,
	"raw.seccomp":  validate.IsAny,

	"volatile.apply_template":   validate.IsAny,
	"volatile.base_image":       validate.IsAny,
	"volatile.last_state.idmap": validate.IsAny,
	"volatile.last_state.power": validate.IsAny,
	"volatile.idmap.base":       validate.IsAny,
	"volatile.idmap.current":    validate.IsAny,
	"volatile.idmap.next":       validate.IsAny,
	"volatile.apply_quota":      validate.IsAny,
	"volatile.uuid":             validate.Optional(validate.IsUUID),
}

KnownInstanceConfigKeys maps all fully defined, well-known config keys to an appropriate checker function, which validates whether or not a given value is syntactically legal.

View Source
var ObjectFound = fmt.Errorf("Found requested object")
View Source
var WebsocketUpgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

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 CompressedTarReader

func CompressedTarReader(ctx context.Context, r io.ReadSeeker, unpacker []string) (*tar.Reader, context.CancelFunc, error)

CompressedTarReader returns a tar reader from the supplied (optionally compressed) tarball stream. The unpacker arguments are those returned by DetectCompressionFile(). The returned cancelFunc should be called when finished with reader to clean up any resources used. This can be done before reading to the end of the tarball if desired.

func ConfigKeyChecker

func ConfigKeyChecker(key string) (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 DebugJson

func DebugJson(r *bytes.Buffer)

func DeepCopy

func DeepCopy(src, dest interface{}) error

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

func DefaultWriter

func DefaultWriter(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool)

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(httpClient *http.Client, useragent string, progress func(progress ioprogress.ProgressData), canceler *cancel.Canceler, 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 ExecReaderToChannel

func ExecReaderToChannel(r io.Reader, bufferSize int, exited <-chan struct{}, fd int) <-chan []byte

Extensively commented directly in the code. Please leave the comments! Looking at this in a couple of months noone will know why and how this works anymore.

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 GetAllXattr

func GetAllXattr(path string) (xattrs map[string]string, err 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 GetFileStat

func GetFileStat(p string) (uid int, gid int, major uint32, minor uint32, inode uint64, nlink int, err 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 GetPollRevents

func GetPollRevents(fd int, timeout int, flags int) (int, int, error)

GetPollRevents poll for events on provided fd.

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 GetSnapshotExpiry

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

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

func InstanceGetParentAndSnapshotName(name string) (string, string, bool)

InstanceGetParentAndSnapshotName returns the parent instance name, snapshot name, and whether it actually was a snapshot name.

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 IsDir

func IsDir(name string) bool

IsDir returns true if the given path is a directory.

func IsLoopback

func IsLoopback(iface *net.Interface) bool

func IsMountPoint

func IsMountPoint(name string) 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

func IsUnixDev

func IsUnixDev(path string) bool

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 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 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 interface{}) (map[string]interface{}, 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 PidFdOpen

func PidFdOpen(Pid int, Flags uint32) (*os.File, error)

func PidfdSendSignal

func PidfdSendSignal(Pidfd int, Signal int, Flags uint32) error

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(network, address string) (net.Conn, error)

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 ReadPid

func ReadPid(r *os.File) int

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

func RunCommandCLocale

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

RunCommandCLocale runs a command with a LANG=C.UTF-8 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 RunCommandInheritFds

func RunCommandInheritFds(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(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(stdin io.Reader, stdout io.Writer, name string, arg ...string) error

func RunningInUserNS

func RunningInUserNS() bool

func SetProgressMetadata

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

func SetSize

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

func SplitExt

func SplitExt(fpath string) (string, string)

func Statvfs

func Statvfs(path string) (*unix.Statfs_t, error)

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

func Unpack(file string, path string, blockBackend bool, runningInUserns bool, tracker *ioprogress.ProgressTracker) error

func ValidHostname

func ValidHostname(name string) error

ValidHostname checks the string is valid DNS hostname.

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 WebsocketConsoleMirror

func WebsocketConsoleMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser) (chan bool, chan bool)

func WebsocketMirror

func WebsocketMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser, Reader WebSocketMirrorReader, Writer WebSocketMirrorWriter) (chan bool, chan bool)

func WebsocketProxy

func WebsocketProxy(source *websocket.Conn, target *websocket.Conn) chan bool

func WebsocketRecvStream

func WebsocketRecvStream(w io.Writer, conn *websocket.Conn) chan bool

func WebsocketSendStream

func WebsocketSendStream(conn *websocket.Conn, r io.Reader, bufferSize int) chan bool

func WriteAll

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

func WriteTempFile

func WriteTempFile(dir string, prefix string, content string) (string, error)

WriteTempFile creates a temp file with the specified content

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

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]interface{}

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 {
	Err    error
	Stdout string
	Stderr string
	// contains filtered or unexported fields
}

func (RunError) Error

func (e RunError) Error() string

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

type WebSocketMirrorReader

type WebSocketMirrorReader func(conn *websocket.Conn, r io.ReadCloser, readDone chan<- bool)

WebsocketMirror allows mirroring a reader to a websocket and taking the result and writing it to a writer. This function allows for multiple mirrorings and correctly negotiates stream endings. However, it means any websocket.Conns passed to it are live when it returns, and must be closed explicitly.

type WebSocketMirrorWriter

type WebSocketMirrorWriter func(conn *websocket.Conn, w io.WriteCloser, writeDone chan<- bool)

type WebsocketIO

type WebsocketIO struct {
	Conn *websocket.Conn
	// contains filtered or unexported fields
}

WebsocketIO is a wrapper implementing ReadWriteCloser on top of websocket

func (*WebsocketIO) Close

func (w *WebsocketIO) Close() error

Close sends a control message indicating the stream is finished, but it does not actually close the socket.

func (*WebsocketIO) Read

func (w *WebsocketIO) Read(p []byte) (n int, err error)

func (*WebsocketIO) Write

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

Directories

Path Synopsis
Package api contains Go structs for all LXD API objects Overview This package has Go structs for every API object, all the various structs are named after the object they represent and some variations of those structs exist for initial object creation, object update and object retrieval.
Package api contains Go structs for all LXD API objects Overview This package has Go structs for every API object, all the various structs are named after the object they represent and some variations of those structs exist for initial object creation, object update and object retrieval.
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
stack
Package stack implements utilities to capture, manipulate, and format call stacks.
Package stack implements utilities to capture, manipulate, and format call stacks.
Package subtest provides a backwards-compatible way to run subtests.
Package subtest provides a backwards-compatible way to run subtests.

Jump to

Keyboard shortcuts

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