shared

package
v0.0.0-...-f59c3e7 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2018 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const ABSTRACT_UNIX_SOCK_LEN int = C.ABSTRACT_UNIX_SOCK_LEN
View Source
const DefaultPort = "8443"
View Source
const POLLERR int = C.POLLERR
View Source
const POLLHUP int = C.POLLHUP
View Source
const POLLIN int = C.POLLIN
View Source
const POLLNVAL int = C.POLLNVAL
View Source
const POLLPRI int = C.POLLPRI
View Source
const POLLRDHUP int = C.POLLRDHUP
View Source
const SnapshotDelimiter = "/"

Variables

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

	"limits.cpu": IsAny,
	"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": IsPriority,

	"limits.disk.priority": IsPriority,

	"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 := ParseByteSizeString(value)
		if err != nil {
			return err
		}

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

	"limits.network.priority": IsPriority,

	"limits.processes": IsInt64,

	"linux.kernel_modules": IsAny,

	"migration.incremental.memory":            IsBool,
	"migration.incremental.memory.iterations": IsUint32,
	"migration.incremental.memory.goal":       IsUint32,

	"security.nesting":    IsBool,
	"security.privileged": IsBool,
	"security.devlxd":     IsBool,

	"security.idmap.base":     IsUint32,
	"security.idmap.isolated": IsBool,
	"security.idmap.size":     IsUint32,

	"security.syscalls.blacklist_default": IsBool,
	"security.syscalls.blacklist_compat":  IsBool,
	"security.syscalls.blacklist":         IsAny,
	"security.syscalls.whitelist":         IsAny,

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

	"volatile.apply_template":   IsAny,
	"volatile.base_image":       IsAny,
	"volatile.last_state.idmap": IsAny,
	"volatile.last_state.power": IsAny,
	"volatile.idmap.next":       IsAny,
	"volatile.idmap.base":       IsAny,
	"volatile.apply_quota":      IsAny,
}

KnownContainerConfigKeys 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 BlockFsDetect

func BlockFsDetect(dev string) (string, 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 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 DetectCompression

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

func DeviceTotalMemory

func DeviceTotalMemory() (int64, error)

func DownloadFileSha256

func DownloadFileSha256(httpClient *http.Client, useragent string, progress func(progress ioprogress.ProgressData), canceler *cancel.Canceler, filename string, url string, hash string, 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 bool, 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 ExtractSnapshotName

func ExtractSnapshotName(name string) string

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

func GenCert

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

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

func GenerateMemCert

func GenerateMemCert(client 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 GetByteSizeString

func GetByteSizeString(input int64, precision uint) string

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 int, minor int,
	inode uint64, nlink int, err error)

func GetOwnerMode

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

func GetPollRevents

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

func GetRemoteCertificate

func GetRemoteCertificate(address string) (*x509.Certificate, 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 GroupId

func GroupId(name string) (int, error)

GroupId is an adaption from https://codereview.appspot.com/4589049.

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

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

func IntInSlice

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

func IsAny

func IsAny(value string) error

func IsBlockdev

func IsBlockdev(fm os.FileMode) bool

func IsBlockdevPath

func IsBlockdevPath(pathName string) bool

func IsBool

func IsBool(value string) error

func IsDir

func IsDir(name string) bool

IsDir returns true if the given path is a directory.

func IsInt64

func IsInt64(value string) error

func IsLoopback

func IsLoopback(iface *net.Interface) bool

func IsMountPoint

func IsMountPoint(name string) bool

func IsOneOf

func IsOneOf(value string, valid []string) error

func IsPriority

func IsPriority(value string) error

func IsSnapshot

func IsSnapshot(name string) bool

func IsTrue

func IsTrue(value string) bool

func IsUint32

func IsUint32(value string) error

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

func Major(dev uint64) int

func Minor

func Minor(dev uint64) int

func MkdirAllOwner

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

func OpenPty

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

func ParseBitSizeString

func ParseBitSizeString(input string) (int64, error)

Parse a size string in bits (e.g. 200kbit or 5Gbit) into the number of bits it represents. Supports suffixes up to Ebit. "" == 0.

func ParseByteSizeString

func ParseByteSizeString(input string) (int64, error)

Parse a size string in bytes (e.g. 200kB or 5GB) into the number of bytes it represents. Supports suffixes up to EB. "" == 0.

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 PathExists

func PathExists(name string) bool

func PathIsEmpty

func PathIsEmpty(path string) (bool, error)

PathIsEmpty checks if the given path is empty.

func Pipe

func Pipe() (master *os.File, slave *os.File, err 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 ReadStdin

func ReadStdin() ([]byte, error)

func ReadToJSON

func ReadToJSON(r io.Reader, req interface{}) 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 RunCommand

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

func RunningInUserNS

func RunningInUserNS() bool

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) (*syscall.Statfs_t, error)

func StringInSlice

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

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)

func URLEncode

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

URLEncode encodes a path and query parameters to a URL.

func Unpack

func Unpack(file string, path string, blockBackend bool, runningInUserns bool) error

func UserId

func UserId(name string) (int, error)

UserId is an adaption from https://codereview.appspot.com/4589049.

func ValidHostname

func ValidHostname(name string) bool

func VarPath

func VarPath(path ...string) string

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

func WebsocketConsoleMirror

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

func WebsocketExecMirror

func WebsocketExecMirror(conn *websocket.Conn, w io.WriteCloser, r io.ReadCloser, exited chan bool, fd int) (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.

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) (*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) KeyPair

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

KeyPair returns the public/private key pair.

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 ContainerAction

type ContainerAction string
const (
	Stop     ContainerAction = "stop"
	Start    ContainerAction = "start"
	Restart  ContainerAction = "restart"
	Freeze   ContainerAction = "freeze"
	Unfreeze ContainerAction = "unfreeze"
)

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 RunError

type RunError struct {
	Err error
	// 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 syscall.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)

Directories

Path Synopsis
Package api contains Go structs for all LXD API objects
Package api contains Go structs for all LXD API objects
Package gnuflag implements command-line flag parsing in the GNU style.
Package gnuflag implements command-line flag parsing in the GNU style.
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