server

package
v0.0.0-...-03200e1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 60 Imported by: 2

Documentation

Index

Constants

View Source
const (
	AlertTypeGood = "GOOD"
	AlertTypeBad  = "BAD"
)

Alert.Type values

View Source
const (
	AppStorageSeeds   = "mulch-seeds"
	AppStorageDisks   = "mulch-disks"
	AppStorageBackups = "mulch-backups"

	AppNetwork  = "mulch"
	AppNWFilter = "mulch-filter"
)

Mulch storage and network names, see the following usages: - App.initLibvirtStorage() - Libvirt.GetConnection()

View Source
const (
	ProxyChainModeNone   = 0
	ProxyChainModeChild  = 1
	ProxyChainModeParent = 2
)

Reverse Proxy Chaining modes

View Source
const (
	OriginTypeHTTP = "http"
	OriginTypeGIT  = "git"
	OriginTypeFile = "file"
)
View Source
const (
	// git cache expires 30 seconds after last use
	OriginGitCacheExpiration = 30 * time.Second

	// maximum git cache life
	OriginGitCacheMaxLife = 10 * time.Minute
)
View Source
const (
	RouteTypeCustom = 0
	RouteTypeStream = 1
)

Route types

View Source
const (
	RouteInternal = "internal"
	RouteAPI      = "api"
)

Route muxer

View Source
const (
	SeedRefreshForce    = true
	SeedRefreshIfNeeded = false
)

SeedRefresh force flag

View Source
const (
	VMStorageAliasDisk   = "ua-mulch-disk"
	VMStorageAliasBackup = "ua-mulch-backup"
	VMNetworkAliasBridge = "ua-mulch-bridge"
)

Aliases for vm.xml file

View Source
const (
	VMOperationNone    = ""
	VMOperationBackup  = "backup"
	VMOperationRestore = "restore"
)

VMOperation values

View Source
const (
	BackupCompressAllow   = true
	BackupCompressDisable = false
)

Backup compression

View Source
const (
	VMInactive = false
	VMActive   = true
)

New VM : active or inactive

View Source
const (
	VMStopOnScriptFailure = false // default, safe behavior
	VMAllowScriptFailure  = true
)

New VM : allow script failures?

View Source
const (
	VMStopNormal = false
	VMStopForce  = true
)

How to stop a VM ("shutdown" vs "destroy")

View Source
const (
	VMAutoRebuildDaily   = "daily"
	VMAutoRebuildWeekly  = "weekly"
	VMAutoRebuildMonthly = "monthly"
)

auto_rebuild setting values

View Source
const (
	VMTagFromConfig = true
	VMTagFromScript = false
)

VM tag from config or from script?

View Source
const (
	VMPortProtocolTCP = 0

	VMPortDirectionExport  = 0
	VMPortDirectionImport  = 1
	VMPortDirectionInvalid = -1

	VMPortPublic = "@PUBLIC"
)

VMPort constants

View Source
const (
	VMStateUp   = "up"
	VMStateDown = "down"
)

VM states

View Source
const BackupBlankRestore = "-"

BackupBlankRestore disables *install* scripts during a a VM creation (so we can restore backup a bit later)

View Source
const BackupNoExpiration = 0

Backup expiration

View Source
const LogHistorySize = 20000 // ~2.5mB

LogHistorySize is the maximum number of messages in app log history ~128kB / 1000 messages (very rough approx!)

View Source
const ProtocolVersion = 1

ProtocolVersion implemented by this server

View Source
const RevisionNone = -1

RevisionNone means… none (see SetActiveRevision for instance)

View Source
const (
	SSHProxyPair = "mulch_ssh_proxy"
)

Mulchd SSH key pairs (generated during launch if needed)

View Source
const VMPortBaseForward uint16 = 9001

VMPortBaseForward is the value to add to port index (ex : first listening port will be 9001, 2nd will be 9002, …)

View Source
const VMPortMaxRangeSize = 20

VMPortMaxRangeSize is the maximum size of a port range This value is currently very arbitrary, we'll see.

View Source
const VMPortProxyProtocoDefault = 8443

VMPortProxyProtocolDefault is the default port where the PROXY protocol server is available in the VM

View Source
const VMStopDefaultTimeout = 3 * time.Minute
View Source
const Version = "1.45.0"

Version of the server

Variables

This section is empty.

Functions

func AutoRebuildSchedule

func AutoRebuildSchedule(app *App)

AutoRebuildSchedule will schedule auto-rebuilds

func BackupDelete

func BackupDelete(backupName string, app *App) error

func CheckDomainsConflicts

func CheckDomainsConflicts(db *VMDatabase, domains []*common.Domain, excludeVM string, config *AppConfig) error

CheckDomainsConflicts will detect if incoming domains conflicts with existing VMs of other mulchd servers (in case of proxy chaining) You can exclude a specific VM (every revisions) using its name (use empty string otherwise)

func CheckDomainsConflictsOnParent

func CheckDomainsConflictsOnParent(domains []*common.Domain, config *AppConfig) error

CheckDomainsConflictsOnParent will contact proxy-chain parent and ask if any domain is conflicting with another child mulchd

func CheckPortsConflicts

func CheckPortsConflicts(db *VMDatabase, ports []*VMPort, excludeVM string, log *Log) error

CheckPortsConflicts will detect exported port conflicts with existing VMs and warn if an imported port is not exported (yet?) by another VM (if log is not nil)

func CloudInitDataGen

func CloudInitDataGen(vm *VM, vmName *VMName, app *App) (string, string, error)

CloudInitDataGen will return CloudInit meta-data and user-data

func CopyReaderFlush

func CopyReaderFlush(dst io.Writer, src io.Reader) (written int64, err error)

CopyReaderFlush

func CopyStreamFlush

func CopyStreamFlush(dst io.Writer, src *libvirt.Stream, ctx context.Context) (written int64, err error)

CopyStreamFlush

func GetConsoleStream

func GetConsoleStream(vmName *VMName, app *App) (*libvirt.Stream, error)

func GetURLScheme

func GetURLScheme(urlStr string) (string, error)

GetURLScheme returns the scheme of the given URL

func IPIntToString

func IPIntToString(ipn uint32) string

IPIntToString convert an uint32 IPv4 to a string

func IPStringToInt

func IPStringToInt(ip string) uint32

IPStringToInt convert an IPv4 string to a unsigned int 32

func IsRebuildNeeded

func IsRebuildNeeded(rebuildSetting string, lastRebuild time.Time) bool

IsRebuildNeeded return true if lastRebuild is older than rebuildSetting

func IsValidGroupName

func IsValidGroupName(group string) bool

IsValidGroupName returns true if group is a valid group name (@ + isValidName)

func IsValidName

func IsValidName(token string) bool

IsValidName returns true if argument use only allowed chars for a name

func IsValidWord

func IsValidWord(token string) bool

IsValidWord returns true if argument use only allowed chars for a name

func LibvirtDomainStateToString

func LibvirtDomainStateToString(state libvirt.DomainState) string

LibvirtDomainStateToString translate a DomainState to string

func ListenAndServeProxy

func ListenAndServeProxy(
	addr string,
	serverConfig *ssh.ServerConfig,
	log *Log,
	connectCB func(c ssh.ConnMetadata) (*ssh.Client, error),
	closeCB func(c ssh.ConnMetadata) error,
) error

ListenAndServeProxy of our own SSH server

func MakeSSHKey

func MakeSSHKey() (private string, public string, err error)

MakeSSHKey generates a OpenSSH formatted key pair (ED25519)

func NewSSHProxyServer

func NewSSHProxyServer(app *App) error

NewSSHProxyServer creates and starts our SSH proxy to VMs

func NewVM

func NewVM(vmConfig *VMConfig, active bool, allowScriptFailure bool, authorKey string, app *App, log *Log) (*VM, *VMName, error)

NewVM builds a new virtual machine from config TODO: this function is HUUUGE and needs to be splitted. It's tricky because there's a "transaction" here.

func PublicKeyFile

func PublicKeyFile(file string) ssh.AuthMethod

PublicKeyFile returns an AuthMethod using a private key file

func RandString

func RandString(n int, rand *rand.Rand) string

RandString generate a random string of A-Za-z0-9 runes

func RandomUniqueIPv4

func RandomUniqueIPv4(app *App) (string, error)

RandomUniqueIPv4 generate a random unique IPv4 (among other Mulch VMs) inside libvirt DHCP range, excluding other "external" static leases

func RandomUniqueMAC

func RandomUniqueMAC(app *App) string

RandomUniqueMAC generate a random unique (among other Mulch VMs) MAC address (we use QEMU MAC prefix)

func SSHAgent

func SSHAgent(pubkeyFile string, log *Log) (ssh.AuthMethod, error)

SSHAgent returns an AuthMethod using SSH agent connection. The pubkeyFile params restricts the AuthMethod to only one key, so it wont spam the SSH server if the agent holds multiple keys.

func SSHSendKeepAlive

func SSHSendKeepAlive(sshConn ssh.Conn, timeout time.Duration) error

SSHSendKeepAlive sends a keepalive request using a timeout

func SearchSSHAuthorizedKey

func SearchSSHAuthorizedKey(searchedPubKey ssh.PublicKey, authorizedKeysFile string) (ssh.PublicKey, string, error)

SearchSSHAuthorizedKey search a public key in an authorized_keys formatted file and return key & comment

func VMAttachBackup

func VMAttachBackup(vmName *VMName, volName string, app *App) error

VMAttachBackup attach a backup volume to the VM

func VMBackup

func VMBackup(vmName *VMName, authorKey string, app *App, log *Log, compressAllow bool, expire time.Duration) (string, error)

VMBackup launch the backup process (returns backup filename)

func VMCreateBackupDisk

func VMCreateBackupDisk(vmName *VMName, volName string, volSize uint64, app *App, log *Log) error

VMCreateBackupDisk create a new backup volume TODO: make this function transactional: remove disk if we fail in last steps

func VMDelete

func VMDelete(vmName *VMName, app *App, log *Log) error

VMDelete will delete a VM (using its name) and linked storages.

func VMDetachBackup

func VMDetachBackup(vmName *VMName, app *App) error

VMDetachBackup detach the backup volume from the VM

func VMGetDiskName

func VMGetDiskName(name *VMName, app *App) (string, error)

VMGetDiskName return VM's disk filename

func VMIsRunning

func VMIsRunning(vmName *VMName, app *App) (bool, error)

VMIsRunning returns true if VM is up and running

func VMLoadGet

func VMLoadGet(vmName *VMName, app *App, sampleDuration time.Duration) (float64, error)

VMLoadGet returns the VM's load (in percentage)

func VMLockUnlock

func VMLockUnlock(vmName *VMName, locked bool, vmdb *VMDatabase) error

VMLockUnlock will lock or unlock a VM, preventing it from deletion

func VMRebuild

func VMRebuild(vmName *VMName, lock bool, authorKey string, app *App, log *Log) error

VMRebuild delete VM and rebuilds it from a backup (using revisions)

func VMRename

func VMRename(orgVMName *VMName, newVMName *VMName, app *App, log *Log) error

VMRename will rename the VM in Mulch and in libvirt (including disks) TODO: try to make some sort of transaction here WARNING: currently not used (old rebuild system) so… unproven code.

func VMRestoreNoChecks

func VMRestoreNoChecks(vm *VM, vmName *VMName, backup *Backup, app *App, log *Log) error

VMRestoreNoChecks launch the restore process, this function is a symetric of VMBackup, since a few checks are missing because it's supposed to be called -during VM creation- (and not after)

func VMStartByName

func VMStartByName(name *VMName, secretUUID string, app *App, log *Log) error

VMStartByName starts a VM using its name and waits until the VM phones home. (or timeouts)

func VMStopByName

func VMStopByName(name *VMName, force bool, timeout time.Duration, app *App, log *Log) error

VMStopByName stops a VM using its name and waits until the VM is down. (or timeouts)

Types

type APIKey

type APIKey struct {
	Comment    string
	Key        string
	SSHPrivate string
	SSHPublic  string
	Rights     []APIRight
}

APIKey describes an API key

func (*APIKey) AddNewRight

func (key *APIKey) AddNewRight(rightStr string) error

AddNewRight parse + add the right to the key WARNING: you may have to save the APIKeyDatabase to the disk! (see APIRight.String() form informations about the format)

func (*APIKey) IsAllowed

func (key *APIKey) IsAllowed(method string, path string, req *http.Request) bool

IsAllowed will return true if the APIKey is allowed to request this method/path/headers (req is optional, but will deny the access if the needed right requires some headers)

func (*APIKey) RemoveRight

func (key *APIKey) RemoveRight(rightStr string) error

RemoveRight will remove the parsed right from the key

type APIKeyDatabase

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

APIKeyDatabase describes a persistent API Key database

func NewAPIKeyDatabase

func NewAPIKeyDatabase(filename string, log *Log, rand *rand.Rand) (*APIKeyDatabase, error)

NewAPIKeyDatabase creates a new API key database

func (*APIKeyDatabase) AddNew

func (db *APIKeyDatabase) AddNew(comment string) (*APIKey, error)

AddNew generates a new key and adds it to the database

func (*APIKeyDatabase) GetByComment

func (db *APIKeyDatabase) GetByComment(comment string) *APIKey

GetByComment returns an API key by its comment, or nil if not found

func (*APIKeyDatabase) GetByPubKey

func (db *APIKeyDatabase) GetByPubKey(pub string) (*APIKey, error)

GetByPubKey returns an API key by its (marshaled) public key Returns nil and no error when key was not found

func (*APIKeyDatabase) IsValidKey

func (db *APIKeyDatabase) IsValidKey(key string) (bool, *APIKey)

IsValidKey return true if the key exists in the database (and returns the key as the second return value)

func (*APIKeyDatabase) List

func (db *APIKeyDatabase) List() []*APIKey

List returns all keys NOTE: This function signature may change in the future, since the current one does not offer much safety to interal structures.

func (*APIKeyDatabase) Save

func (db *APIKeyDatabase) Save() error

Save the database on the disk

type APIRight

type APIRight struct {
	Method  string
	Path    string
	Headers map[string]string
}

APIRight is a parsed "Rights" line

func (*APIRight) String

func (right *APIRight) String() string

String will convert a right to a string

type Alert

type Alert struct {
	Type    string
	Subject string
	Content string
}

Alert are used only for background big "events" (seed download failure, vm autorebuild failure, etc)

type AlertSender

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

AlertSender will be attached to the application

func NewAlertSender

func NewAlertSender(configPath string, log *Log) (*AlertSender, error)

NewAlertSender creates a new AlertSender

func (*AlertSender) RunKeepAlive

func (sender *AlertSender) RunKeepAlive(daysInterval int)

RunKeepAlive will send a keepalive alert every X days

func (*AlertSender) Send

func (sender *AlertSender) Send(alert *Alert) error

Send an alert using all alert scripts (etc/alerts/*.sh)

type App

type App struct {
	StartTime   time.Time
	Config      *AppConfig
	Libvirt     *Libvirt
	Hub         *Hub
	PhoneHome   *PhoneHomeHub
	Log         *Log
	LogHistory  *LogHistory
	MuxInternal *http.ServeMux
	MuxAPI      *http.ServeMux
	Rand        *rand.Rand
	SSHPairDB   *SSHPairDatabase
	SecretsDB   *SecretDatabase
	VMDB        *VMDatabase
	VMStateDB   *VMStateDatabase
	BackupsDB   *BackupDatabase
	APIKeysDB   *APIKeyDatabase
	AlertSender *AlertSender
	Seeder      *SeedDatabase
	Origins     *Origins

	Operations    *OperationList
	ProxyReloader *ProxyReloader
	// contains filtered or unexported fields
}

App describes an (the?) application

func NewApp

func NewApp(config *AppConfig, trace bool) (*App, error)

NewApp creates a new application

func (*App) AddRoute

func (app *App) AddRoute(route *Route, routeMuxer string) error

AddRoute adds a new route to the given route muxer

func (*App) Close

func (app *App) Close()

Close is not called yet

func (*App) Run

func (app *App) Run()

Run will start the app servers (foreground)

func (*App) Status

func (app *App) Status() (*common.APIStatus, error)

Status returns informations about Mulch server

type AppConfig

type AppConfig struct {
	// address where the API server will listen
	Listen string

	// port for "phone home" internal HTTP server
	// (do not change if any VM was already built!)
	InternalServerPort int

	// API server HTTPS domain name (fallbacks to HTTP if not set)
	ListenHTTPSDomain string

	// URI to libvirtd (qemu only, currently)
	LibVirtURI string

	// local path (so libvirtd shound run next to us, currently)
	StoragePath string

	// persistent storage (ex: VM database)
	// TODO: create path if needed on startup
	DataPath string

	// temporary files path
	TempPath string

	// prefix for VM names (in libvirt)
	VMPrefix string

	// SSH proxy listen address
	ProxyListenSSH string

	// extra (limited) SSH keys
	ProxySSHExtraKeysFile string

	// reverse Proxy Chaining mode
	ProxyChainMode int

	// if parent: listening API URL
	// if child: parent API URL
	ProxyChainParentURL string

	// child only: URL we will register to parent
	ProxyChainChildURL string

	// pre-shared key for the chain
	ProxyChainPSK string

	// user (sudoer) created by Mulch in VMs
	MulchSuperUser string

	// name of the SSH key in SSHPairDatabase for this sudoer
	MulchSuperUserSSHKey string

	// everyday VM auto-rebuild time ("HH:MM")
	AutoRebuildTime string

	// seeds
	Seeds map[string]ConfigSeed

	// peers
	Peers map[string]ConfigPeer

	// origins
	Origins map[string]*ConfigOrigin
	// contains filtered or unexported fields
}

AppConfig describes the general configuration of an App

func NewAppConfigFromTomlFile

func NewAppConfigFromTomlFile(configPath string) (*AppConfig, error)

NewAppConfigFromTomlFile return a AppConfig using mulchd.toml config file in the given configPath

func (*AppConfig) GetTemplateFilepath

func (conf *AppConfig) GetTemplateFilepath(name string) string

GetTemplateFilepath returns a path to a etc/template file

type Backup

type Backup struct {
	DiskName  string
	Created   time.Time
	Expire    time.Time
	AuthorKey string
	VM        *VM
}

Backup describes a VM backup

type BackupDatabase

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

BackupDatabase describes a persistent Backup instances database

func NewBackupDatabase

func NewBackupDatabase(filename string, app *App) (*BackupDatabase, error)

NewBackupDatabase instanciates a new BackupDatabase

func (*BackupDatabase) Add

func (db *BackupDatabase) Add(backup *Backup) error

Add a new Backup in the database

func (*BackupDatabase) Count

func (db *BackupDatabase) Count() int

Count returns the number of Backups in the database

func (*BackupDatabase) Delete

func (db *BackupDatabase) Delete(name string) error

Delete the Backup from the database using its name

func (*BackupDatabase) Expire

func (db *BackupDatabase) Expire(name string, expire time.Time) error

Expire defines the expiration date of a Backup (0 means no expiration)

func (*BackupDatabase) GetByName

func (db *BackupDatabase) GetByName(name string) *Backup

GetByName lookups a Backup by its name, or nil if not found

func (*BackupDatabase) GetNames

func (db *BackupDatabase) GetNames() []string

GetNames of all Backups in the database

func (*BackupDatabase) Run

func (db *BackupDatabase) Run() error

Run the database monitoring loop

type CertManager

type CertManager struct {
	CertDir string
	Domain  string
	Log     *Log
	// contains filtered or unexported fields
}

CertManager for HTTPS API server, using mulch-proxy certificates

func (*CertManager) GetAPICertificate

func (cm *CertManager) GetAPICertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)

GetAPICertificate implements tls.Config GetCertificate callback

func (*CertManager) ScheduleSelfCalls

func (cm *CertManager) ScheduleSelfCalls()

ScheduleSelfCalls call our own API HTTPS URL every 24 hour, refreshing the TLS certificate.

type ConfigOrigin

type ConfigOrigin struct {
	Name       string
	Type       string
	Path       string
	Dir        string
	Branch     string
	SSHKeyFile string
	SSHAgent   bool
}

ConfigOrigin describes an origin for scripts

type ConfigPeer

type ConfigPeer struct {
	Name        string
	URL         string
	Key         string
	SyncSecrets bool
}

ConfigPeer describes a peer

type ConfigSeed

type ConfigSeed struct {
	URL    string
	Seeder string
}

ConfigSeed describes a OS seed

type Hub

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

Hub structure allows multiple clients to receive messages from mulchd.

func NewHub

func NewHub(trace bool) *Hub

NewHub creates a new Hub

func (*Hub) Broadcast

func (h *Hub) Broadcast(message *common.Message)

Broadcast send a message to all clients of the Hub (if the target matches)

func (*Hub) Register

func (h *Hub) Register(info string, target string, trace bool) *HubClient

Register a new client of the Hub clientInfo is not currently used but is supposed to differentiate the client. Target may be common.MessageNoTarget.

func (*Hub) Run

func (h *Hub) Run()

Run will start the Hub, allowing messages to be sent and received

type HubClient

type HubClient struct {
	Messages chan *common.Message
	// contains filtered or unexported fields
}

HubClient describes a client of a Hub

func (*HubClient) SetTarget

func (hc *HubClient) SetTarget(target string)

SetTarget allows the client to change (receiving) target

func (*HubClient) Unregister

func (hc *HubClient) Unregister()

Unregister the client from the Hub

type Libvirt

type Libvirt struct {
	Pools      LibvirtPools
	Network    *libvirt.Network
	NetworkXML *libvirtxml.Network
	// contains filtered or unexported fields
}

Libvirt is an interface to libvirt library

func NewLibvirt

func NewLibvirt(uri string) (*Libvirt, error)

NewLibvirt create a new Libvirt instance

func (*Libvirt) AddTransientDHCPHost

func (lv *Libvirt) AddTransientDHCPHost(newHost *libvirtxml.NetworkDHCPHost, app *App) error

AddTransientDHCPHost will add a new transient DHCP static host You'll then need to remove this transient host on VM creation success/failure

func (*Libvirt) BackupCompress

func (lv *Libvirt) BackupCompress(volName string, template string, tmpPath string, log *Log) error

BackupCompress will TRY to compress backup

func (*Libvirt) CloneVolume

func (lv *Libvirt) CloneVolume(srcVolName string, srcPool *libvirt.StoragePool, dstVolName string, dstPool *libvirt.StoragePool, dstPoolXML *libvirtxml.StoragePool, volumeTemplateFile string, log *Log) error

CloneVolume clones a source volume to a destination volume in the same pool

func (*Libvirt) CloseConnection

func (lv *Libvirt) CloseConnection()

CloseConnection close connection to libvirt

func (*Libvirt) CreateDiskFromSeed

func (lv *Libvirt) CreateDiskFromSeed(seed string, disk string, volumeTemplateFile string, log *Log) error

CreateDiskFromSeed creates a disk (into "disks" pool) from seed image (from "seeds" pool)

func (*Libvirt) DeleteVolume

func (lv *Libvirt) DeleteVolume(name string, pool *libvirt.StoragePool) error

DeleteVolume for specified pool

func (*Libvirt) GetConnection

func (lv *Libvirt) GetConnection() (*libvirt.Connect, error)

GetConnection returns the current libvirt connection

func (*Libvirt) GetDomainByName

func (lv *Libvirt) GetDomainByName(domainName string) (*libvirt.Domain, error)

GetDomainByName returns a domain or nil if domain is not foud. Remember to call dom.Free() after use.

func (*Libvirt) GetOrCreateNWFilter

func (lv *Libvirt) GetOrCreateNWFilter(filterName string, templateFile string, log *Log) (*libvirt.NWFilter, error)

GetOrCreateNWFilter create (if necessary) and return a libvirt network filter

func (*Libvirt) GetOrCreateNetwork

func (lv *Libvirt) GetOrCreateNetwork(networkName string, templateFile string, log *Log) (*libvirt.Network, *libvirtxml.Network, error)

GetOrCreateNetwork retreives (and create, if necessary) a libvirt network

func (*Libvirt) GetOrCreateStoragePool

func (lv *Libvirt) GetOrCreateStoragePool(poolName string, poolPath string, templateFile string, mode string, log *Log) (*libvirt.StoragePool, *libvirtxml.StoragePool, error)

GetOrCreateStoragePool retreives (and create, if necessary) a storage pool (mode is the Unix access mode for the pool directory)

I've seen strange things once in a while, like: - Code=38, Domain=0, Message='cannot open directory '…/storage/cloud-init': No such file or directory' - Code=55, Domain=18, Message='Requested operation is not valid: storage pool 'mulch-cloud-init' is not active Added more precise error messages to diagnose this.

func (*Libvirt) RebuildDHCPStaticLeases

func (lv *Libvirt) RebuildDHCPStaticLeases(app *App) error

RebuildDHCPStaticLeases will clean static DHCP leases database

func (*Libvirt) RemoveTransientDHCPHost

func (lv *Libvirt) RemoveTransientDHCPHost(newHost *libvirtxml.NetworkDHCPHost, app *App) error

RemoveTransientDHCPHost will remove a transient DHCP lease

func (*Libvirt) ResizeDisk

func (lv *Libvirt) ResizeDisk(disk string, size uint64, pool *libvirt.StoragePool, log *Log) error

ResizeDisk will change volume ("disk") size (do not reduce a volume without knowing what you are doing!)

func (*Libvirt) UploadFileToLibvirt

func (lv *Libvirt) UploadFileToLibvirt(pool *libvirt.StoragePool, poolXML *libvirtxml.StoragePool, template string, localSourceFile string, asName string, log *Log) error

UploadFileToLibvirt is a variant using a file as source

func (*Libvirt) UploadFileToLibvirtFromReader

func (lv *Libvirt) UploadFileToLibvirtFromReader(pool *libvirt.StoragePool, poolXML *libvirtxml.StoragePool, template string, sourceRC io.ReadCloser, asName string, log *Log) error

UploadFileToLibvirtFromReader uploads a file to libvirt storage

func (*Libvirt) VolumeDownloadToWriter

func (lv *Libvirt) VolumeDownloadToWriter(srcVolName string, pool *libvirt.StoragePool, dst io.WriteCloser) (*volumes.VolumeDownload, error)

VolumeDownloadToWriter return a *VolumeDownload for a download operation to a writer

func (*Libvirt) VolumeInfos

func (lv *Libvirt) VolumeInfos(name string, pool *libvirt.StoragePool) (*libvirt.StorageVolInfo, error)

VolumeInfos returns volume informations, like physical allocated size

type LibvirtDHCPLeases

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

LibvirtDHCPLeases stores a list (map) of static DHCP leases

func NewLibvirtDHCPLeases

func NewLibvirtDHCPLeases() *LibvirtDHCPLeases

NewLibvirtDHCPLeases returns a new LibvirtDHCPLeases instance

type LibvirtPools

type LibvirtPools struct {
	Seeds   *libvirt.StoragePool
	Disks   *libvirt.StoragePool
	Backups *libvirt.StoragePool

	SeedsXML   *libvirtxml.StoragePool
	DisksXML   *libvirtxml.StoragePool
	BackupsXML *libvirtxml.StoragePool
}

LibvirtPools stores needed libvirt Pools for mulchd

type Log

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

Log provides error/warning/etc helpers for a Hub

func NewLog

func NewLog(target string, hub *Hub, history *LogHistory) *Log

NewLog creates a new log for the provided target and hub note: common.MessageNoTarget is an acceptable target

func (*Log) Error

func (log *Log) Error(message string)

Error sends a MessageError Message

func (*Log) Errorf

func (log *Log) Errorf(format string, args ...interface{})

Errorf sends a formated string MessageError Message

func (*Log) Failure

func (log *Log) Failure(message string)

Failure sends an MessageFailure Message

func (*Log) Failuref

func (log *Log) Failuref(format string, args ...interface{})

Failuref sends a formated string MessageFailure Message

func (*Log) Info

func (log *Log) Info(message string)

Info sends an MessageInfo Message

func (*Log) Infof

func (log *Log) Infof(format string, args ...interface{})

Infof sends a formated string MessageInfo Message

func (*Log) Log

func (log *Log) Log(message *common.Message)

Log is a low-level function for sending a Message

func (*Log) SetTarget

func (log *Log) SetTarget(target string)

SetTarget change the current "sending" target

func (*Log) Success

func (log *Log) Success(message string)

Success sends an MessageSuccess Message

func (*Log) Successf

func (log *Log) Successf(format string, args ...interface{})

Successf sends a formated string MessageSuccess Message

func (*Log) Trace

func (log *Log) Trace(message string)

Trace sends an MessageTrace Message

func (*Log) Tracef

func (log *Log) Tracef(format string, args ...interface{})

Tracef sends a formated string MessageTrace Message

func (*Log) Warning

func (log *Log) Warning(message string)

Warning sends a MessageWarning Message

func (*Log) Warningf

func (log *Log) Warningf(format string, args ...interface{})

Warningf sends a formated string MessageWarning Message

type LogHistory

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

LogHistory stores messages in a limited size double chain list

func NewLogHistory

func NewLogHistory(elems int) *LogHistory

NewLogHistory will create and initialize a new log message history

func (*LogHistory) Dump

func (lh *LogHistory) Dump()

Dump all logs in the buffer (temporary test)

func (*LogHistory) Push

func (lh *LogHistory) Push(message *common.Message)

Push a new message in the list

func (*LogHistory) Search

func (lh *LogHistory) Search(maxMessages int, target string) []*common.Message

Search return an array of messages (latest messages, up to maxMessages, for a specific target)

type Operation

type Operation struct {
	Origin        string // API Key, "[seeder]", "[autorebuild]", …
	Action        string // delete, remove, rebuild, …
	Ressource     string // backup, seed, vm, …
	RessourceName string // VM name, seed name, …
	StartTime     time.Time
}

Operation on the server

type OperationList

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

OperationList is a list of currently running operations

func NewOperationList

func NewOperationList(rand *rand.Rand) *OperationList

NewOperationList instanciates a new OperationList

func (*OperationList) Add

func (db *OperationList) Add(op *Operation) string

Add an operation to the list

func (*OperationList) Remove

func (db *OperationList) Remove(id string)

Remove an operation from the list

type Origin

type Origin struct {
	Log    *Log
	Config *ConfigOrigin
	// contains filtered or unexported fields
}

type OriginGitCache

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

type Origins

type Origins struct {
	Origins map[string]*Origin
}

func NewOrigins

func NewOrigins(app *App) *Origins

NewOrigins creates a new Origin list

func (*Origins) GetContent

func (o *Origins) GetContent(path string) (io.ReadCloser, error)

GetContent returns a ReadCloser to the file at the given URL/path - caller must Close() the returned value

func (*Origins) GetOriginFromPath

func (o *Origins) GetOriginFromPath(path string) (string, string, error)

GetOriginFromPath returns the origin, the subpath and an error if any - if the path does not use an origin, it returns an empty origin and no error

type OverflowBuffer

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

OverflowBuffer is a ring buffer that will overflow when full

func NewOverflowBuffer

func NewOverflowBuffer(size int) *OverflowBuffer

NewOverflowBuffer creates a new OverflowBuffer

func (*OverflowBuffer) IsEmpty

func (ob *OverflowBuffer) IsEmpty() bool

IsEmpty returns true if the buffer is empty

func (*OverflowBuffer) Read

func (ob *OverflowBuffer) Read(data []byte) (n int, err error)

Read reads data from the buffer

func (*OverflowBuffer) Write

func (ob *OverflowBuffer) Write(data []byte) (n int, err error)

Write writes data to the buffer (non blocking [overwrites])

type PeerCall

type PeerCall struct {
	Peer              ConfigPeer
	Method            string
	Path              string
	Args              map[string]string
	UploadVolume      *PeerCallLibvirtFile
	UploadString      *PeerCallStringFile
	TextCallback      func(body []byte) error
	JSONCallback      func(io.Reader, http.Header) error
	BinaryCallback    func(io.Reader, http.Header) error
	HTTPErrorCallback func(code int, body []byte, httpError error) error
	MessageCallback   func(m *common.Message) error

	Log     *Log
	Libvirt *Libvirt
}

func (*PeerCall) Do

func (call *PeerCall) Do() error

Do a call to a peer (with detailed error messages)

type PeerCallLibvirtFile

type PeerCallLibvirtFile struct {
	Name string
	As   string
	Pool *libvirt.StoragePool
}

type PeerCallStringFile

type PeerCallStringFile struct {
	FieldName string
	FileName  string
	Content   string
}

type PhoneCall

type PhoneCall struct {
	SecretUUID string
	RemoteIP   string
	CloutInit  bool
}

PhoneCall describes a call from a VM

type PhoneHomeHub

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

PhoneHomeHub stores our internal channels and our client list

func NewPhoneHomeHub

func NewPhoneHomeHub() *PhoneHomeHub

NewPhoneHomeHub creates a new PhoneHomeHub

func (*PhoneHomeHub) Broadcast

func (h *PhoneHomeHub) Broadcast(call *PhoneCall)

Broadcast a PhoneCall to all clients

func (*PhoneHomeHub) BroadcastPhoneCall

func (h *PhoneHomeHub) BroadcastPhoneCall(secretUUID string, remoteIP string, cloudInit bool)

BroadcastPhoneCall broadcasts a PhoneCall using its details

func (*PhoneHomeHub) Register

func (h *PhoneHomeHub) Register(secretUUID string) *PhoneHomeHubClient

Register will create PhoneHomeHubClient attached to the hub

type PhoneHomeHubClient

type PhoneHomeHubClient struct {
	PhoneCalls      chan *PhoneCall
	RequestedSecret string
	Hub             *PhoneHomeHub
}

PhoneHomeHubClient describes a client of an PhoneHomeHub

func (*PhoneHomeHubClient) Unregister

func (hc *PhoneHomeHubClient) Unregister()

Unregister a client from the hub

type ProxyReloader

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

ProxyReloader is able to reload Mulch Reverse Proxy using a system signal

func NewProxyReloader

func NewProxyReloader(app *App) *ProxyReloader

NewProxyReloader creates a new ProxyReloader instance

func (*ProxyReloader) Request

func (pr *ProxyReloader) Request()

Request a Reverse Proxy reload, if not already requested. The request is delayed in order to "mutualize" multiple requests in a short amount of time.

type Request

type Request struct {
	Route     *Route
	SubPath   string
	HTTP      *http.Request
	Response  http.ResponseWriter
	App       *App
	Stream    *Log
	HubClient *HubClient
	APIKey    *APIKey
	// contains filtered or unexported fields
}

Request describes a request and allows to build a response

func (*Request) IsAPIKeyAllowed

func (req *Request) IsAPIKeyAllowed() bool

IsAPIKeyAllowed will return true if the APIKey is allowed to do this request

func (*Request) Printf

func (req *Request) Printf(format string, args ...interface{})

Printf like helper for req.Response.Write

func (*Request) Println

func (req *Request) Println(message string)

Println like helper for req.Response.Write

func (*Request) SetTarget

func (req *Request) SetTarget(target string)

SetTarget define or change the default target for the request, for both sending (Stream) and receiving (HubClient)

func (*Request) StartStream

func (req *Request) StartStream()

StartStream indicates that headers have been sent and "body" stream can start

func (*Request) WaitStream

func (req *Request) WaitStream()

WaitStream waits for StartStream()

type Route

type Route struct {
	Route        string
	Type         int
	Public       bool
	NoProtoCheck bool
	Handler      func(*Request)
	// contains filtered or unexported fields
}

Route describes a route to a handler

type Run

type Run struct {
	Caption string
	SSHConn *SSHConnection
	Tasks   []*RunTask
	// CurrentTask int
	// StartTime    time.Time
	// Duration     time.Duration
	// DialDuration time.Duration
	Log            *Log
	StdoutCallback func(string)
}

Run is a list of Tasks on Host, including task results

func (*Run) Go

func (run *Run) Go(ctx context.Context) error

Go will execute the Run

type RunTask

type RunTask struct {
	ScriptName   string
	ScriptReader io.Reader
	As           string
	Arguments    string
	EnvWords     map[string]string
}

RunTask is a task (script) for a Run

type SSHConnection

type SSHConnection struct {
	User  string
	Auths []ssh.AuthMethod
	Host  string
	Port  int
	// Ciphers []string
	Session *ssh.Session
	Client  *ssh.Client
	Log     *Log
}

SSHConnection stores connection informations

func (*SSHConnection) Close

func (connection *SSHConnection) Close() error

Close will clone the connection and the session

func (*SSHConnection) Connect

func (connection *SSHConnection) Connect() error

Connect will dial SSH server and open a session

type SSHPair

type SSHPair struct {
	Name    string
	Private string
	Public  string
}

SSHPair describes an OpenSSH formatted key pair

type SSHPairDatabase

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

SSHPairDatabase describes a persistent SSHPair instances database

func NewSSHPairDatabase

func NewSSHPairDatabase(filename string) (*SSHPairDatabase, error)

NewSSHPairDatabase instanciates a new SSHPairDatabase

func (*SSHPairDatabase) AddNew

func (db *SSHPairDatabase) AddNew(name string) error

AddNew and add a SSH pair

func (*SSHPairDatabase) Count

func (db *SSHPairDatabase) Count() int

Count returns the number of SSHPair in the database

func (*SSHPairDatabase) GetByName

func (db *SSHPairDatabase) GetByName(name string) *SSHPair

GetByName lookups a SSHPair by its name, or nil if not found

func (*SSHPairDatabase) GetPublicKeyAuth

func (db *SSHPairDatabase) GetPublicKeyAuth(name string) (ssh.AuthMethod, error)

GetPublicKeyAuth return a PublicKey AuthMethod for named key pair

func (*SSHPairDatabase) Save

func (db *SSHPairDatabase) Save() error

Save the DB to disk

type SSHProxy

type SSHProxy struct {
	net.Conn
	// contains filtered or unexported fields
}

SSHProxy is a proxy between two SSH connections

func (*SSHProxy) ClientHandleChannelOpen

func (proxy *SSHProxy) ClientHandleChannelOpen(chanType string, client *ssh.Client, destConn ssh.Conn)

ClientHandleChannelOpen is called when the client (= the VM) asks for a new channel (ex: forwarded-tcpip)

func (*SSHProxy) ForwardRequestsToClient

func (proxy *SSHProxy) ForwardRequestsToClient(in <-chan *ssh.Request, client *ssh.Client)

ForwardRequestsToClient forwards server ("outside") global requests to the client ("VM")

type Secret

type Secret struct {
	Key       string
	Value     string
	Modified  time.Time
	AuthorKey string
	Deleted   bool
}

type SecretDatabase

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

func NewSecretDatabase

func NewSecretDatabase(dbFilename string, passFilename string, app *App) (*SecretDatabase, error)

NewSecretDatabase instanciates a new SecretDatabase, creating a new passphrase if needed.

func (*SecretDatabase) CleanKey

func (db *SecretDatabase) CleanKey(keyPath string) (string, error)

CleanKey returns a cleaned key path, if possible

func (*SecretDatabase) Decrypt

func (db *SecretDatabase) Decrypt(data []byte) ([]byte, error)

decrypt data with the passphrase using AES and GCM

func (*SecretDatabase) Delete

func (db *SecretDatabase) Delete(key string, authorKey string) error

Delete a secret value

func (*SecretDatabase) Encrypt

func (db *SecretDatabase) Encrypt(data []byte) ([]byte, error)

encrypt data with the passphrase using AES and GCM

func (*SecretDatabase) Get

func (db *SecretDatabase) Get(key string) (*Secret, error)

Get a secret value

func (*SecretDatabase) GetAllVMsUsingSecret

func (db *SecretDatabase) GetAllVMsUsingSecret(key string) ([]string, error)

GetAllVMsUsingSecret returns a list of VMs that use a given secret, including on other peers.

func (*SecretDatabase) GetKeys

func (db *SecretDatabase) GetKeys() []string

GetKeys returns all keys

func (*SecretDatabase) GetPeersVMsUsingSecret

func (db *SecretDatabase) GetPeersVMsUsingSecret(key string) ([]string, error)

GetPeersVMsUsingSecret returns a list of VMs that use a given secret on all our peers.

func (*SecretDatabase) GetSecretsUsage

func (db *SecretDatabase) GetSecretsUsage(with_peers bool) (common.APISecretUsageEntries, error)

GetSecretsUsage returns a list of secrets and the number of VMs using them

func (*SecretDatabase) GetVMsUsingSecret

func (db *SecretDatabase) GetVMsUsingSecret(key string) ([]string, error)

GetVMsUsingSecret returns a list of VMs that use a given secret, including other peers.

func (*SecretDatabase) Save

func (db *SecretDatabase) Save() error

Save the database to disk

func (*SecretDatabase) SaveToWriter

func (db *SecretDatabase) SaveToWriter(writer io.Writer) error

Save the database to a writer

func (*SecretDatabase) Set

func (db *SecretDatabase) Set(key string, value string, authorKey string) error

Set a secret value

func (*SecretDatabase) SyncPeer

func (db *SecretDatabase) SyncPeer(peer ConfigPeer) error

SyncPeer syncs the secret database with a peer

func (*SecretDatabase) SyncPeers

func (db *SecretDatabase) SyncPeers() error

SyncPeers syncs the secret database with peers

func (*SecretDatabase) SyncWithDatabase

func (db *SecretDatabase) SyncWithDatabase(other SecretDatabaseEntries) (SecretDatabaseEntries, error)

SyncWithDatabase syncs our secret database with another database (ex: from another peer) It returns (our) "newer" entries so the remote peer can merge them into its own database.

type SecretDatabaseEntries

type SecretDatabaseEntries map[string]*Secret

type Seed

type Seed struct {
	Name         string
	URL          string
	Seeder       string
	Ready        bool
	LastModified time.Time
	Size         uint64
	Status       string
	StatusTime   time.Time
	PausedUntil  time.Time
}

Seed entry in the DB

func (*Seed) GetVolumeName

func (seed *Seed) GetVolumeName() string

GetVolumeName return the seed volume file name

func (*Seed) IsPaused

func (seed *Seed) IsPaused() bool

IsPaused returns true if the seed is paused

func (*Seed) UpdateStatus

func (seed *Seed) UpdateStatus(status string)

UpdateStatus change status informations

type SeedDatabase

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

SeedDatabase describes a persistent DataBase of Seed structures

func NewSeeder

func NewSeeder(filename string, app *App) (*SeedDatabase, error)

NewSeeder instanciates a new SeedDatabase

func (*SeedDatabase) GetByName

func (db *SeedDatabase) GetByName(name string) (*Seed, error)

GetByName returns a seed using its name (or an error)

func (*SeedDatabase) GetNames

func (db *SeedDatabase) GetNames() []string

GetNames returns a list of seed names

func (*SeedDatabase) PauseSeed

func (db *SeedDatabase) PauseSeed(seed *Seed, unpauseTime time.Time) error

PauseSeed pause a seed until a given time (and save the DB)

func (*SeedDatabase) RefreshSeed

func (db *SeedDatabase) RefreshSeed(seed *Seed, force bool) error

RefreshSeed will download a seed image using its URL

func (*SeedDatabase) RefreshSeeder

func (db *SeedDatabase) RefreshSeeder(seed *Seed, force bool) error

RefreshSeeder will rebuild seeder using a VM

func (*SeedDatabase) Run

func (db *SeedDatabase) Run()

Run the seeder (check Last-Modified dates, download new releases, rebuilds seeders)

type VM

type VM struct {
	App                  *App `json:"-"`
	LibvirtUUID          string
	SecretUUID           string
	Config               *VMConfig
	AuthorKey            string
	MulchSuperUserSSHKey string
	InitDate             time.Time
	LastIP               string
	Locked               bool
	WIP                  VMOperation
	LastRebuildDuration  time.Duration
	LastRebuildDowntime  time.Duration
	AssignedMAC          string
	AssignedIPv4         string
}

VM defines a virtual machine ("domain")

func (*VM) GetEnvMap

func (vm *VM) GetEnvMap(vmName *VMName) (map[string]string, error)

func (*VM) GetSecretsMap

func (vm *VM) GetSecretsMap() (map[string]string, error)

GetSecretsMap returns a map of secrets for a VM The map contains all existing secrets, even if err is not nil

func (*VM) SetOperation

func (vm *VM) SetOperation(op VMOperation)

SetOperation change VM WIP

type VMConfig

type VMConfig struct {
	FileContent string // config file content

	Name           string
	Hostname       string
	Timezone       string
	AppUser        string
	Seed           string
	InitUpgrade    bool
	DiskSize       uint64
	RAMSize        uint64
	CPUCount       int
	Domains        []*common.Domain
	Env            map[string]string
	Secrets        []string
	Ports          []*VMPort
	BackupDiskSize uint64
	BackupCompress bool
	RestoreBackup  string
	AutoRebuild    string
	BuildTimeout   time.Duration

	Prepare []*VMConfigScript
	Install []*VMConfigScript
	Backup  []*VMConfigScript
	Restore []*VMConfigScript

	DoActions map[string]*VMDoAction
	Tags      map[string]bool
}

VMConfig stores needed parameters for a new VM

func NewVMConfigFromTomlReader

func NewVMConfigFromTomlReader(configIn io.Reader, app *App) (*VMConfig, error)

NewVMConfigFromTomlReader cretes a new VMConfig instance from a io.Reader containing VM configuration description

type VMConfigScript

type VMConfigScript struct {
	ScriptURL string
	As        string
}

VMConfigScript is a script for prepare, install, save and restore steps

type VMDatabase

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

VMDatabase describes a persistent DataBase of VMs structures --- It includes a greenhouse, where all new VM (= currently building) are stored. This transient database is not stored on disk. (this DB is used by GetBySecretUUID, for instance)

func NewVMDatabase

func NewVMDatabase(filename string, domainFilename string, portFilename string, onUpdate updateCallback, app *App) (*VMDatabase, error)

NewVMDatabase instanciates a new VMDatabase

func (*VMDatabase) Add

func (vmdb *VMDatabase) Add(vm *VM, name *VMName, active bool) error

Add a new VM in the database

func (*VMDatabase) AddToGreenhouse

func (vmdb *VMDatabase) AddToGreenhouse(vm *VM, name *VMName) error

AddToGreenhouse a new VM in the greenhouse database

func (*VMDatabase) Count

func (vmdb *VMDatabase) Count() int

Count returns the number of VMs in the database

func (*VMDatabase) Delete

func (vmdb *VMDatabase) Delete(name *VMName) error

Delete the VM from the database using its name

func (*VMDatabase) DeleteFromGreenhouse

func (vmdb *VMDatabase) DeleteFromGreenhouse(name *VMName) error

DeleteFromGreenhouse the VM from the greenhouse database using its name

func (*VMDatabase) GetActiveByName

func (vmdb *VMDatabase) GetActiveByName(name string) (*VM, error)

GetActiveByName return the active VM with the specified name

func (*VMDatabase) GetActiveEntryByName

func (vmdb *VMDatabase) GetActiveEntryByName(name string) (*VMDatabaseEntry, error)

GetActiveEntryByName return the active VM entry with the specified name

func (*VMDatabase) GetByName

func (vmdb *VMDatabase) GetByName(name *VMName) (*VM, error)

GetByName lookups a VM by its name

func (*VMDatabase) GetByNameID

func (vmdb *VMDatabase) GetByNameID(id string) (*VM, error)

GetByNameID lookups a VM by its name-id (low-level, should not use)

func (*VMDatabase) GetBySecretUUID

func (vmdb *VMDatabase) GetBySecretUUID(uuid string) (*VM, error)

GetBySecretUUID lookups a VM by its secretUUID Note: this function also search in greenhouseDB

func (*VMDatabase) GetCountForName

func (vmdb *VMDatabase) GetCountForName(name string) int

GetCountForName returns the amount of instances with the specified name (so 0 means none)

func (*VMDatabase) GetEntryByName

func (vmdb *VMDatabase) GetEntryByName(name *VMName) (*VMDatabaseEntry, error)

GetEntryByName lookups a VMDatabaseEntry entry by its name

func (*VMDatabase) GetEntryBySecretUUID

func (vmdb *VMDatabase) GetEntryBySecretUUID(uuid string) (*VMDatabaseEntry, error)

GetEntryBySecretUUID lookups a VMName by its secretUUID Note: this function also search in greenhouseDB

func (*VMDatabase) GetEntryByVM

func (vmdb *VMDatabase) GetEntryByVM(vm *VM) (*VMDatabaseEntry, error)

GetEntryByVM lookups a VM entry by it's VM pointer

func (*VMDatabase) GetGreenhouseEntryByName

func (vmdb *VMDatabase) GetGreenhouseEntryByName(name *VMName) (*VMDatabaseEntry, error)

GetGreenhouseEntryByName lookups a VMDatabaseEntry in greenhouseDB entry by its name

func (*VMDatabase) GetGreenhouseNames

func (vmdb *VMDatabase) GetGreenhouseNames() []*VMName

GetGreenhouseNames return all VMs in the greenhouse database

func (*VMDatabase) GetNames

func (vmdb *VMDatabase) GetNames() []*VMName

GetNames of all VMs in the database

func (*VMDatabase) GetNextRevisionForName

func (vmdb *VMDatabase) GetNextRevisionForName(name string) int

GetNextRevisionForName returns the next revision for a VM name

func (*VMDatabase) IsVMActive

func (vmdb *VMDatabase) IsVMActive(name *VMName) (bool, error)

IsVMActive returns true if VM is active

func (*VMDatabase) SearchGreenhouseEntries

func (vmdb *VMDatabase) SearchGreenhouseEntries(name string) []*VMDatabaseEntry

SearchGreenhouseEntries lists all VMs in the greenhouse matching the specified name

func (*VMDatabase) SetActiveRevision

func (vmdb *VMDatabase) SetActiveRevision(name string, revision int) error

SetActiveRevision change the active instance (RevisionNone is allowed)

func (*VMDatabase) Update

func (vmdb *VMDatabase) Update() error

Update saves the DB if data was modified using *VM pointers

type VMDatabaseEntry

type VMDatabaseEntry struct {
	Name   *VMName
	VM     *VM
	Active bool
}

VMDatabaseEntry is an entry in the DB: a name and a VM Only one entry can be active per name

type VMDatabaseMigrate

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

VMDatabaseMigrate allows old format VM database migration to new (v2) format

func NewVMDatabaseMigrate

func NewVMDatabaseMigrate() *VMDatabaseMigrate

NewVMDatabaseMigrate create an new VMDatabaseMigrate instance

type VMDoAction

type VMDoAction struct {
	Name        string
	ScriptURL   string
	User        string
	Description string
	FromConfig  bool
}

VMDoAction is a script for a "do" action (scripts for usual tasks in the VM)

type VMName

type VMName struct {
	Name     string
	Revision int
}

VMName hosts what makes a VM unique: a name and a revision

func NewVMName

func NewVMName(name string, revision int) *VMName

NewVMName instanciates a new VMName struct

func ParseVMName

func ParseVMName(nameID string) (*VMName, error)

ParseVMName parses a VM name and returns a VMName struct

func (*VMName) ID

func (name *VMName) ID() string

ID returns a unique ID for the VM

func (*VMName) LibvirtDomainName

func (name *VMName) LibvirtDomainName(app *App) string

LibvirtDomainName returns the libvirt domain name (using app prefix)

func (*VMName) String

func (name *VMName) String() string

type VMOperation

type VMOperation string

VMOperation defines heavy operations in the VM

type VMPort

type VMPort struct {
	Port       uint16
	Protocol   int // tcp (VMPortProtocol*)
	Direction  int // export / import
	Index      int // position in the direction (ex: 2nd exported port), 0 indexed
	Group      string
	PublicPort uint16 // exported PUBLIC port (0 = private)
	ProxyPort  uint16 // "PROXY protocol" port (0 = no proxy)
}

VMPort is a network port inside a VM

func NewVMPortArray

func NewVMPortArray(strPorts []string) ([]*VMPort, error)

NewVMPortArray will parse an array of strings and return an array of *VMPort

func (*VMPort) GlobalID

func (p *VMPort) GlobalID() string

GlobalID will return a "global" ID for the port (public ports are merged) Useful for deduplication

func (*VMPort) String

func (p *VMPort) String() string

String version of the VMPort (Index is not part of the string)

type VMStateDatabase

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

VMStateDatabase describes a persistent DataBase of VM state (up or down)

func NewVMStateDatabase

func NewVMStateDatabase(filename string, app *App) (*VMStateDatabase, error)

NewVMStateDatabase instanciates a new VMStateDatabase

func (*VMStateDatabase) Cycles

func (vmsdb *VMStateDatabase) Cycles() uint64

Cycles returns the number of cycles

func (*VMStateDatabase) Get

func (vmsdb *VMStateDatabase) Get() map[string]string

Get returns the state of all VMs

func (*VMStateDatabase) Run

func (vmsdb *VMStateDatabase) Run() error

Run the VM state monitoring loop

func (*VMStateDatabase) Update

func (vmsdb *VMStateDatabase) Update() error

Update saves the DB with current VM states

func (*VMStateDatabase) WaitRestore

func (vmsdb *VMStateDatabase) WaitRestore()

WaitRestore blocks until VM states are not restored, so non-crucial tasks can kindly wait for a "quiter" system load. NOTE: very crude timeout-baed implementation, should use sync.Cond

Jump to

Keyboard shortcuts

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