shared

package
v0.0.0-...-53daa5b Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2015 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Overview

This is a FLEXible file which can be used by both client and daemon.
* Teehee.

That this code needs to exist is kind of dumb, but I'm not sure how else to do it.

Index

Constants

View Source
const (
	SYS_CLASS_NET = "/sys/class/net"
)

Variables

View Source
var APICompat = 1

* Please increment the api compat number every time you change the API. * * Version 1.0: ping

View Source
var APIVersion = "1.0"
View Source
var StateMap = map[string]State{
	"STOPPED":  STOPPED,
	"STARTING": STARTING,
	"RUNNING":  RUNNING,
	"STOPPING": STOPPING,
	"ABORTING": ABORTING,
	"FREEZING": FREEZING,
	"FROZEN":   FROZEN,
	"THAWED":   THAWED,
}
View Source
var UserAgent = "LXD " + Version
View Source
var Version = "0.10"
View Source
var WebsocketUpgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin:     func(r *http.Request) bool { return true },
}

Functions

func AtoiEmptyDefault

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

func CopyFile

func CopyFile(dest string, source string) error

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

func DbBegin

func DbBegin(db *sql.DB) (*sql.Tx, error)

func DbExec

func DbExec(db *sql.DB, q string, args ...interface{}) (sql.Result, error)

func DbQuery

func DbQuery(db *sql.DB, q string, args ...interface{}) (*sql.Rows, error)

func DbQueryRowScan

func DbQueryRowScan(db *sql.DB, q string, args []interface{}, outargs []interface{}) error

func DbQueryScan

func DbQueryScan(db *sql.DB, q string, inargs []interface{}, outfmt []interface{}) ([][]interface{}, error)

* . q is the database query * . inargs is an array of interfaces containing the query arguments * . outfmt is an array of interfaces containing the right types of output * arguments, i.e. * var arg1 string * var arg2 int * outfmt := {}interface{}{arg1, arg2} * * The result will be an array (one per output row) of arrays (one per output argument) * of interfaces, containing pointers to the actual output arguments.

func DebugJson

func DebugJson(r *bytes.Buffer)

func Debugf

func Debugf(format string, args ...interface{})

Debugf sends to the logger registered via SetLogger the string resulting from running format and args through Sprintf, but only if debugging was enabled via SetDebug.

func FindOrGenCert

func FindOrGenCert(certf string, keyf string) error

func GenCert

func GenCert(certf string, keyf string) error

func GenerateFingerprint

func GenerateFingerprint(cert *x509.Certificate) string

func GetFilesystem

func GetFilesystem(path string) (string, error)

func GetTLSConfig

func GetTLSConfig(certf string, keyf string) (*tls.Config, error)

func GroupId

func GroupId(name string) (int, error)

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

func GroupName

func GroupName(gid int) (string, error)

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

func IsBridge

func IsBridge(iface *net.Interface) bool

func IsDbLockedError

func IsDbLockedError(err error) bool

func IsDir

func IsDir(name string) bool

func IsLoopback

func IsLoopback(iface *net.Interface) bool

func IsSnapshot

func IsSnapshot(name string) bool

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 Logf

func Logf(format string, args ...interface{})

Logf sends to the logger registered via SetLogger the string resulting from running format and args through Sprintf.

func OpenPty

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

func OperationWrap

func OperationWrap(f func() error) func() OperationResult

func OperationsURL

func OperationsURL(id string) string

func ParseLXDFileHeaders

func ParseLXDFileHeaders(headers http.Header) (uid int, gid int, mode os.FileMode, err error)

func PathExists

func PathExists(name string) bool

func Pipe

func Pipe() (master *os.File, slave *os.File, err error)

func PrintStack

func PrintStack()

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 ReadLastNLines

func ReadLastNLines(f *os.File, lines int) (string, error)

func ReadStdin

func ReadStdin() ([]byte, error)

func ReadToJSON

func ReadToJSON(r io.Reader, req interface{}) error

func ReaderToChannel

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

func SetDebug

func SetDebug(enabled bool)

SetDebug defines whether debugging is enabled or not.

func SetLogger

func SetLogger(l Logger)

SetLogger defines the *log.Logger where log messages are sent to.

func SetSize

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

func SplitExt

func SplitExt(fpath string) (string, string)

func TxCommit

func TxCommit(tx *sql.Tx) error

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 WebsocketMirror

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

WebsocketMirror allows mirroring a reader to a websocket and taking the result and writing it to a writer.

func WebsocketRecvStream

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

func WebsocketSendStream

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

func WriteAll

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

func WriteAllBuf

func WriteAllBuf(w io.Writer, buf *bytes.Buffer) error

Types

type BriefContainerState

type BriefContainerState struct {
	Name      string            `json:"name"`
	Profiles  []string          `json:"profiles"`
	Config    map[string]string `json:"config"`
	Devices   Devices           `json:"devices"`
	Ephemeral bool              `json:"ephemeral"`
}

* BriefContainerState contains a subset of the fields in * ContainerState, namely those which a user may update

type BriefServerState

type BriefServerState struct {
	Config map[string]interface{} `json:"config"`
}

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 ContainerAction

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

type ContainerExecControl

type ContainerExecControl struct {
	Command string            `json:"command"`
	Args    map[string]string `json:"args"`
}

type ContainerInfo

type ContainerInfo struct {
	State ContainerState `json:"state"`
	Snaps []string       `json:"snaps"`
}

type ContainerState

type ContainerState struct {
	Name            string            `json:"name"`
	Profiles        []string          `json:"profiles"`
	Config          map[string]string `json:"config"`
	ExpandedConfig  map[string]string `json:"expanded_config"`
	Userdata        []byte            `json:"userdata"`
	Status          ContainerStatus   `json:"status"`
	Devices         Devices           `json:"devices"`
	ExpandedDevices Devices           `json:"expanded_devices"`
	Ephemeral       bool              `json:"ephemeral"`
	Log             string            `json:"log"`
}

func (*ContainerState) BriefState

func (c *ContainerState) BriefState() BriefContainerState

func (*ContainerState) State

func (c *ContainerState) State() State

type ContainerStatus

type ContainerStatus struct {
	State     string `json:"status"`
	StateCode State  `json:"status_code"`
	Init      int    `json:"init"`
	Ips       []Ip   `json:"ips"`
}

type Device

type Device map[string]string

type Devices

type Devices map[string]Device

type IdmapSet

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

func DefaultIdmapSet

func DefaultIdmapSet() (*IdmapSet, error)

* Create a new default idmap

func (IdmapSet) Append

func (m IdmapSet) Append(s string) (IdmapSet, error)

func (IdmapSet) Intersects

func (m IdmapSet) Intersects(i idmapEntry) bool

func (IdmapSet) Len

func (m IdmapSet) Len() int

func (IdmapSet) ShiftIntoNs

func (m IdmapSet) ShiftIntoNs(uid int, gid int) (int, int)

func (*IdmapSet) ShiftRootfs

func (set *IdmapSet) ShiftRootfs(p string) error

func (IdmapSet) ToLxcString

func (m IdmapSet) ToLxcString() []string

func (*IdmapSet) UidshiftIntoContainer

func (set *IdmapSet) UidshiftIntoContainer(dir string, testmode bool) error

type ImageAlias

type ImageAlias struct {
	Name        string `json:"target"`
	Description string `json:"description"`
}

type ImageAliases

type ImageAliases []ImageAlias

type ImageBaseInfo

type ImageBaseInfo struct {
	Id           int
	Fingerprint  string
	Filename     string
	Size         int64
	Public       int
	Architecture int
	CreationDate int64
	ExpiryDate   int64
	UploadDate   int64
}

type ImageInfo

type ImageInfo struct {
	Aliases      ImageAliases      `json:"aliases"`
	Architecture int               `json:"architecture"`
	Fingerprint  string            `json:"fingerprint"`
	Filename     string            `json:"filename"`
	Properties   map[string]string `json:"properties"`
	Public       int               `json:"public"`
	Size         int64             `json:"size"`
	CreationDate int64             `json:"created_at"`
	ExpiryDate   int64             `json:"expires_at"`
	UploadDate   int64             `json:"uploaded_at"`
}

type ImageProperties

type ImageProperties map[string]string

type Ip

type Ip struct {
	Interface string `json:"interface"`
	Protocol  string `json:"protocol"`
	Address   string `json:"address"`
}

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 Logger

type Logger interface {
	Output(calldepth int, s string) error
}

Logger is implemented by the standard *log.Logger.

type Operation

type Operation struct {
	CreatedAt  time.Time           `json:"created_at"`
	UpdatedAt  time.Time           `json:"updated_at"`
	Status     string              `json:"status"`
	StatusCode OperationStatus     `json:"status_code"`
	Resources  map[string][]string `json:"resources"`
	Metadata   json.RawMessage     `json:"metadata"`
	MayCancel  bool                `json:"may_cancel"`

	/* The fields below are for use on the server side. */
	Run func() OperationResult `json:"-"`

	/* If this is not nil, the operation can be cancelled by calling this
	 * function */
	Cancel func() error `json:"-"`

	/* This channel receives exactly one value, when the event is done and
	 * the status is updated */
	Chan chan bool `json:"-"`

	/* If this is not nil, users can connect to a websocket for this
	 * operation. The flag indicates whether or not this socket has already
	 * been used: websockets can be connected to exactly once. */
	Websocket OperationWebsocket `json:"-"`
}

func (*Operation) GetError

func (o *Operation) GetError() error

func (*Operation) MetadataAsMap

func (o *Operation) MetadataAsMap() (*Jmap, error)

func (*Operation) SetResult

func (o *Operation) SetResult(result OperationResult)

func (*Operation) SetStatus

func (o *Operation) SetStatus(status OperationStatus)

func (*Operation) SetStatusByErr

func (o *Operation) SetStatusByErr(err error)

type OperationResult

type OperationResult struct {
	Metadata json.RawMessage
	Error    error
}
var OperationSuccess OperationResult = OperationResult{}

func OperationError

func OperationError(err error) OperationResult

type OperationStatus

type OperationStatus int
const (
	OK         OperationStatus = 100
	Started    OperationStatus = 101
	Stopped    OperationStatus = 102
	Running    OperationStatus = 103
	Cancelling OperationStatus = 104
	Pending    OperationStatus = 105

	Success OperationStatus = 200

	Failure   OperationStatus = 400
	Cancelled OperationStatus = 401
)

func (OperationStatus) IsFinal

func (o OperationStatus) IsFinal() bool

func (OperationStatus) String

func (o OperationStatus) String() string

type OperationWebsocket

type OperationWebsocket interface {

	// Metadata() specifies the metadata for the initial response this
	// OperationWebsocket renders.
	Metadata() interface{}

	// Connect should return the error if the connection failed,
	// or nil if the connection was successful.
	Connect(secret string, r *http.Request, w http.ResponseWriter) error

	// Run the actual operation and return its result.
	Do() OperationResult
}

OperationWebsocket represents the /websocket endpoint for operations. Users can connect by specifying a secret (given to them at operation creation time). As soon as the operation is created, the websocket's Do() function is called. It is up to the Do() function to block and wait for any connections it expects before proceeding.

type ProfileConfig

type ProfileConfig struct {
	Name    string            `json:"name"`
	Config  map[string]string `json:"config"`
	Devices Devices           `json:"devices"`
}

type ServerState

type ServerState struct {
	APICompat   int                    `json:"api_compat"`
	Auth        string                 `json:"auth"`
	Environment map[string]string      `json:"environment"`
	Config      map[string]interface{} `json:"config"`
}

func (*ServerState) BriefState

func (c *ServerState) BriefState() BriefServerState

type State

type State int

State type specifies possible container states.

const (
	// STOPPED means container is not running
	STOPPED State = iota + 1
	// STARTING means container is starting
	STARTING
	// RUNNING means container is running
	RUNNING
	// STOPPING means container is stopping
	STOPPING
	// ABORTING means container is aborting
	ABORTING
	// FREEZING means container is freezing
	FREEZING
	// FROZEN means containe is frozen
	FROZEN
	// THAWED means container is thawed
	THAWED
)

type StringSet

type StringSet map[string]bool

func NewStringSet

func NewStringSet(strings []string) StringSet

func (StringSet) IsSubset

func (ss StringSet) IsSubset(oss StringSet) bool

Jump to

Keyboard shortcuts

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