diff --git a/GNUmakefile b/GNUmakefile index f09f0fc30..d1f64d27e 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -16,14 +16,9 @@ ifeq (,$(findstring $(THIS_OS),Darwin Linux FreeBSD)) $(error Building Nomad is currently only supported on Darwin and Linux.) endif -# On Linux we build for Linux, Windows, and potentially Linux+LXC +# On Linux we build for Linux and Windows ifeq (Linux,$(THIS_OS)) -# Detect if we have LXC on the path -ifeq (0,$(shell pkg-config --exists lxc; echo $$?)) -HAS_LXC="true" -endif - ifeq ($(TRAVIS),true) $(info Running in Travis, verbose mode is disabled) else @@ -38,9 +33,6 @@ ALL_TARGETS += linux_386 \ windows_386 \ windows_amd64 -ifeq ("true",$(HAS_LXC)) -ALL_TARGETS += linux_amd64-lxc -endif endif # On MacOS, we only build for MacOS @@ -122,14 +114,6 @@ pkg/windows_amd64/nomad: $(SOURCE_FILES) ## Build Nomad for windows/amd64 -tags "$(GO_TAGS)" \ -o "$@.exe" -pkg/linux_amd64-lxc/nomad: $(SOURCE_FILES) ## Build Nomad+LXC for linux/amd64 - @echo "==> Building $@ with tags $(GO_TAGS)..." - @CGO_ENABLED=1 GOOS=linux GOARCH=amd64 \ - go build \ - -ldflags $(GO_LDFLAGS) \ - -tags "$(GO_TAGS) lxc" \ - -o "$@" - # Define package targets for each of the build targets we actually have on this system define makePackageTarget @@ -222,7 +206,7 @@ changelogfmt: dev: GOOS=$(shell go env GOOS) dev: GOARCH=$(shell go env GOARCH) dev: GOPATH=$(shell go env GOPATH) -dev: DEV_TARGET=pkg/$(GOOS)_$(GOARCH)$(if $(HAS_LXC),-lxc)/nomad +dev: DEV_TARGET=pkg/$(GOOS)_$(GOARCH)/nomad dev: vendorfmt changelogfmt ## Build for the current development platform @echo "==> Removing old development build..." @rm -f $(PROJECT_ROOT)/$(DEV_TARGET) @@ -268,7 +252,7 @@ test-nomad: dev ## Run Nomad test suites $(if $(ENABLE_RACE),-race) $(if $(VERBOSE),-v) \ -cover \ -timeout=15m \ - -tags="$(if $(HAS_LXC),lxc)" ./... $(if $(VERBOSE), >test.log ; echo $$? > exit-code) + ./... $(if $(VERBOSE), >test.log ; echo $$? > exit-code) @if [ $(VERBOSE) ] ; then \ bash -C "$(PROJECT_ROOT)/scripts/test_check.sh" ; \ fi diff --git a/drivers/lxc/driver.go b/drivers/lxc/driver.go deleted file mode 100644 index d9d1ea97e..000000000 --- a/drivers/lxc/driver.go +++ /dev/null @@ -1,513 +0,0 @@ -//+build linux,lxc - -package lxc - -import ( - "context" - "fmt" - "strconv" - "time" - - "github.com/hashicorp/go-hclog" - "github.com/hashicorp/nomad/client/stats" - "github.com/hashicorp/nomad/drivers/shared/eventer" - "github.com/hashicorp/nomad/plugins/base" - "github.com/hashicorp/nomad/plugins/drivers" - "github.com/hashicorp/nomad/plugins/shared/hclspec" - "github.com/hashicorp/nomad/plugins/shared/loader" - pstructs "github.com/hashicorp/nomad/plugins/shared/structs" - "gopkg.in/lxc/go-lxc.v2" -) - -const ( - // pluginName is the name of the plugin - pluginName = "lxc" - - // fingerprintPeriod is the interval at which the driver will send fingerprint responses - fingerprintPeriod = 30 * time.Second -) - -var ( - // PluginID is the rawexec plugin metadata registered in the plugin - // catalog. - PluginID = loader.PluginID{ - Name: pluginName, - PluginType: base.PluginTypeDriver, - } - - // PluginConfig is the rawexec factory function registered in the - // plugin catalog. - PluginConfig = &loader.InternalPluginConfig{ - Config: map[string]interface{}{}, - Factory: func(l hclog.Logger) interface{} { return NewLXCDriver(l) }, - } -) - -// PluginLoader maps pre-0.9 client driver options to post-0.9 plugin options. -func PluginLoader(opts map[string]string) (map[string]interface{}, error) { - conf := map[string]interface{}{} - if v, err := strconv.ParseBool(opts["driver.lxc.enable"]); err == nil { - conf["enabled"] = v - } - if v, err := strconv.ParseBool(opts["lxc.volumes.enabled"]); err == nil { - conf["volumes"] = v - } - if v, ok := opts["driver.lxc.path"]; ok { - conf["path"] = v - } - return conf, nil -} - -var ( - // pluginInfo is the response returned for the PluginInfo RPC - pluginInfo = &base.PluginInfoResponse{ - Type: base.PluginTypeDriver, - PluginApiVersions: []string{drivers.ApiVersion010}, - PluginVersion: "0.1.0", - Name: pluginName, - } - - // configSpec is the hcl specification returned by the ConfigSchema RPC - configSpec = hclspec.NewObject(map[string]*hclspec.Spec{ - "enabled": hclspec.NewDefault( - hclspec.NewAttr("enabled", "bool", false), - hclspec.NewLiteral("true"), - ), - "volumes": hclspec.NewDefault( - hclspec.NewAttr("volumes", "bool", false), - hclspec.NewLiteral("true"), - ), - "path": hclspec.NewDefault( - hclspec.NewAttr("path", "string", false), - hclspec.NewLiteral("\"\""), - ), - }) - - // taskConfigSpec is the hcl specification for the driver config section of - // a task within a job. It is returned in the TaskConfigSchema RPC - taskConfigSpec = hclspec.NewObject(map[string]*hclspec.Spec{ - "template": hclspec.NewAttr("template", "string", true), - "distro": hclspec.NewAttr("distro", "string", false), - "release": hclspec.NewAttr("release", "string", false), - "arch": hclspec.NewAttr("arch", "string", false), - "image_variant": hclspec.NewAttr("image_variant", "string", false), - "image_server": hclspec.NewAttr("image_server", "string", false), - "gpg_key_id": hclspec.NewAttr("gpg_key_id", "string", false), - "gpg_key_server": hclspec.NewAttr("gpg_key_server", "string", false), - "disable_gpg": hclspec.NewAttr("disable_gpg", "string", false), - "flush_cache": hclspec.NewAttr("flush_cache", "string", false), - "force_cache": hclspec.NewAttr("force_cache", "string", false), - "template_args": hclspec.NewAttr("template_args", "list(string)", false), - "log_level": hclspec.NewAttr("log_level", "string", false), - "verbosity": hclspec.NewAttr("verbosity", "string", false), - "volumes": hclspec.NewAttr("volumes", "list(string)", false), - }) - - // capabilities is returned by the Capabilities RPC and indicates what - // optional features this driver supports - capabilities = &drivers.Capabilities{ - SendSignals: false, - Exec: false, - FSIsolation: drivers.FSIsolationImage, - } -) - -// Driver is a driver for running LXC containers -type Driver struct { - // eventer is used to handle multiplexing of TaskEvents calls such that an - // event can be broadcast to all callers - eventer *eventer.Eventer - - // config is the driver configuration set by the SetConfig RPC - config *Config - - // nomadConfig is the client config from nomad - nomadConfig *base.ClientDriverConfig - - // tasks is the in memory datastore mapping taskIDs to rawExecDriverHandles - tasks *taskStore - - // ctx is the context for the driver. It is passed to other subsystems to - // coordinate shutdown - ctx context.Context - - // signalShutdown is called when the driver is shutting down and cancels the - // ctx passed to any subsystems - signalShutdown context.CancelFunc - - // logger will log to the Nomad agent - logger hclog.Logger -} - -// Config is the driver configuration set by the SetConfig RPC call -type Config struct { - // Enabled is set to true to enable the lxc driver - Enabled bool `codec:"enabled"` - - AllowVolumes bool `codec:"volumes"` - - Path string `codec:"path"` -} - -// TaskConfig is the driver configuration of a task within a job -type TaskConfig struct { - Template string `codec:"template"` - Distro string `codec:"distro"` - Release string `codec:"release"` - Arch string `codec:"arch"` - ImageVariant string `codec:"image_variant"` - ImageServer string `codec:"image_server"` - GPGKeyID string `codec:"gpg_key_id"` - GPGKeyServer string `codec:"gpg_key_server"` - DisableGPGValidation bool `codec:"disable_gpg"` - FlushCache bool `codec:"flush_cache"` - ForceCache bool `codec:"force_cache"` - TemplateArgs []string `codec:"template_args"` - LogLevel string `codec:"log_level"` - Verbosity string `codec:"verbosity"` - Volumes []string `codec:"volumes"` -} - -// TaskState is the state which is encoded in the handle returned in -// StartTask. This information is needed to rebuild the task state and handler -// during recovery. -type TaskState struct { - TaskConfig *drivers.TaskConfig - ContainerName string - StartedAt time.Time -} - -// NewLXCDriver returns a new DriverPlugin implementation -func NewLXCDriver(logger hclog.Logger) drivers.DriverPlugin { - ctx, cancel := context.WithCancel(context.Background()) - logger = logger.Named(pluginName) - return &Driver{ - eventer: eventer.NewEventer(ctx, logger), - config: &Config{}, - tasks: newTaskStore(), - ctx: ctx, - signalShutdown: cancel, - logger: logger, - } -} - -func (d *Driver) PluginInfo() (*base.PluginInfoResponse, error) { - return pluginInfo, nil -} - -func (d *Driver) ConfigSchema() (*hclspec.Spec, error) { - return configSpec, nil -} - -func (d *Driver) SetConfig(cfg *base.Config) error { - var config Config - if len(cfg.PluginConfig) != 0 { - if err := base.MsgPackDecode(cfg.PluginConfig, &config); err != nil { - return err - } - } - - d.config = &config - if cfg.AgentConfig != nil { - d.nomadConfig = cfg.AgentConfig.Driver - } - - return nil -} - -func (d *Driver) Shutdown() { - d.signalShutdown() -} - -func (d *Driver) TaskConfigSchema() (*hclspec.Spec, error) { - return taskConfigSpec, nil -} - -func (d *Driver) Capabilities() (*drivers.Capabilities, error) { - return capabilities, nil -} - -func (d *Driver) Fingerprint(ctx context.Context) (<-chan *drivers.Fingerprint, error) { - ch := make(chan *drivers.Fingerprint) - go d.handleFingerprint(ctx, ch) - return ch, nil -} - -func (d *Driver) handleFingerprint(ctx context.Context, ch chan<- *drivers.Fingerprint) { - defer close(ch) - ticker := time.NewTimer(0) - for { - select { - case <-ctx.Done(): - return - case <-d.ctx.Done(): - return - case <-ticker.C: - ticker.Reset(fingerprintPeriod) - ch <- d.buildFingerprint() - } - } -} - -func (d *Driver) buildFingerprint() *drivers.Fingerprint { - var health drivers.HealthState - var desc string - attrs := map[string]*pstructs.Attribute{} - - lxcVersion := lxc.Version() - - if d.config.Enabled && lxcVersion != "" { - health = drivers.HealthStateHealthy - desc = "ready" - attrs["driver.lxc"] = pstructs.NewBoolAttribute(true) - attrs["driver.lxc.version"] = pstructs.NewStringAttribute(lxcVersion) - } else { - health = drivers.HealthStateUndetected - desc = "disabled" - } - - if d.config.AllowVolumes { - attrs["driver.lxc.volumes.enabled"] = pstructs.NewBoolAttribute(true) - } - - return &drivers.Fingerprint{ - Attributes: attrs, - Health: health, - HealthDescription: desc, - } -} - -func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error { - if handle == nil { - return fmt.Errorf("error: handle cannot be nil") - } - - if _, ok := d.tasks.Get(handle.Config.ID); ok { - return nil - } - - var taskState TaskState - if err := handle.GetDriverState(&taskState); err != nil { - return fmt.Errorf("failed to decode task state from handle: %v", err) - } - - var driverConfig TaskConfig - if err := taskState.TaskConfig.DecodeDriverConfig(&driverConfig); err != nil { - return fmt.Errorf("failed to decode driver config: %v", err) - } - - c, err := lxc.NewContainer(taskState.ContainerName, d.lxcPath()) - if err != nil { - return fmt.Errorf("failed to create container ref: %v", err) - } - - initPid := c.InitPid() - h := &taskHandle{ - container: c, - initPid: initPid, - taskConfig: taskState.TaskConfig, - procState: drivers.TaskStateRunning, - startedAt: taskState.StartedAt, - exitResult: &drivers.ExitResult{}, - - totalCpuStats: stats.NewCpuStats(), - userCpuStats: stats.NewCpuStats(), - systemCpuStats: stats.NewCpuStats(), - } - - d.tasks.Set(taskState.TaskConfig.ID, h) - - go h.run() - return nil -} - -func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) { - if _, ok := d.tasks.Get(cfg.ID); ok { - return nil, nil, fmt.Errorf("task with ID %q already started", cfg.ID) - } - - var driverConfig TaskConfig - if err := cfg.DecodeDriverConfig(&driverConfig); err != nil { - return nil, nil, fmt.Errorf("failed to decode driver config: %v", err) - } - - d.logger.Info("starting lxc task", "driver_cfg", hclog.Fmt("%+v", driverConfig)) - handle := drivers.NewTaskHandle(pluginName) - handle.Config = cfg - - c, err := d.initializeContainer(cfg, driverConfig) - if err != nil { - return nil, nil, err - } - - opt := toLXCCreateOptions(driverConfig) - if err := c.Create(opt); err != nil { - return nil, nil, fmt.Errorf("unable to create container: %v", err) - } - - cleanup := func() { - if err := c.Destroy(); err != nil { - d.logger.Error("failed to clean up from an error in Start", "error", err) - } - } - - if err := d.configureContainerNetwork(c); err != nil { - cleanup() - return nil, nil, err - } - - if err := d.mountVolumes(c, cfg, driverConfig); err != nil { - cleanup() - return nil, nil, err - } - - if err := c.Start(); err != nil { - cleanup() - return nil, nil, fmt.Errorf("unable to start container: %v", err) - } - - if err := d.setResourceLimits(c, cfg); err != nil { - cleanup() - return nil, nil, err - } - - pid := c.InitPid() - - h := &taskHandle{ - container: c, - initPid: pid, - taskConfig: cfg, - procState: drivers.TaskStateRunning, - startedAt: time.Now().Round(time.Millisecond), - logger: d.logger, - - totalCpuStats: stats.NewCpuStats(), - userCpuStats: stats.NewCpuStats(), - systemCpuStats: stats.NewCpuStats(), - } - - driverState := TaskState{ - ContainerName: c.Name(), - TaskConfig: cfg, - StartedAt: h.startedAt, - } - - if err := handle.SetDriverState(&driverState); err != nil { - d.logger.Error("failed to start task, error setting driver state", "error", err) - cleanup() - return nil, nil, fmt.Errorf("failed to set driver state: %v", err) - } - - d.tasks.Set(cfg.ID, h) - - go h.run() - - return handle, nil, nil -} - -func (d *Driver) WaitTask(ctx context.Context, taskID string) (<-chan *drivers.ExitResult, error) { - handle, ok := d.tasks.Get(taskID) - if !ok { - return nil, drivers.ErrTaskNotFound - } - - ch := make(chan *drivers.ExitResult) - go d.handleWait(ctx, handle, ch) - - return ch, nil -} - -func (d *Driver) handleWait(ctx context.Context, handle *taskHandle, ch chan *drivers.ExitResult) { - defer close(ch) - - // - // Wait for process completion by polling status from handler. - // We cannot use the following alternatives: - // * Process.Wait() requires LXC container processes to be children - // of self process; but LXC runs container in separate PID hierarchy - // owned by PID 1. - // * lxc.Container.Wait() holds a write lock on container and prevents - // any other calls, including stats. - // - // Going with simplest approach of polling for handler to mark exit. - ticker := time.NewTicker(2 * time.Second) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return - case <-d.ctx.Done(): - return - case <-ticker.C: - s := handle.TaskStatus() - if s.State == drivers.TaskStateExited { - ch <- handle.exitResult - } - } - } -} - -func (d *Driver) StopTask(taskID string, timeout time.Duration, signal string) error { - handle, ok := d.tasks.Get(taskID) - if !ok { - return drivers.ErrTaskNotFound - } - - if err := handle.shutdown(timeout); err != nil { - return fmt.Errorf("executor Shutdown failed: %v", err) - } - - return nil -} - -func (d *Driver) DestroyTask(taskID string, force bool) error { - handle, ok := d.tasks.Get(taskID) - if !ok { - return drivers.ErrTaskNotFound - } - - if handle.IsRunning() && !force { - return fmt.Errorf("cannot destroy running task") - } - - if handle.IsRunning() { - // grace period is chosen arbitrary here - if err := handle.shutdown(1 * time.Minute); err != nil { - handle.logger.Error("failed to destroy executor", "err", err) - } - } - - d.tasks.Delete(taskID) - return nil -} - -func (d *Driver) InspectTask(taskID string) (*drivers.TaskStatus, error) { - handle, ok := d.tasks.Get(taskID) - if !ok { - return nil, drivers.ErrTaskNotFound - } - - return handle.TaskStatus(), nil -} - -func (d *Driver) TaskStats(taskID string) (*drivers.TaskResourceUsage, error) { - handle, ok := d.tasks.Get(taskID) - if !ok { - return nil, drivers.ErrTaskNotFound - } - - return handle.stats() -} - -func (d *Driver) TaskEvents(ctx context.Context) (<-chan *drivers.TaskEvent, error) { - return d.eventer.TaskEvents(ctx) -} - -func (d *Driver) SignalTask(taskID string, signal string) error { - return fmt.Errorf("LXC driver does not support signals") -} - -func (d *Driver) ExecTask(taskID string, cmd []string, timeout time.Duration) (*drivers.ExecTaskResult, error) { - return nil, fmt.Errorf("LXC driver does not support exec") -} diff --git a/drivers/lxc/driver_test.go b/drivers/lxc/driver_test.go deleted file mode 100644 index 313c9e480..000000000 --- a/drivers/lxc/driver_test.go +++ /dev/null @@ -1,280 +0,0 @@ -// +build linux,lxc - -package lxc - -import ( - "context" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" - "time" - - "github.com/hashicorp/hcl2/hcl" - ctestutil "github.com/hashicorp/nomad/client/testutil" - "github.com/hashicorp/nomad/helper/testlog" - "github.com/hashicorp/nomad/helper/uuid" - "github.com/hashicorp/nomad/nomad/structs" - "github.com/hashicorp/nomad/plugins/drivers" - dtestutil "github.com/hashicorp/nomad/plugins/drivers/testutils" - "github.com/hashicorp/nomad/plugins/shared/hclspec" - "github.com/hashicorp/nomad/plugins/shared/hclutils" - "github.com/hashicorp/nomad/testutil" - "github.com/stretchr/testify/require" - lxc "gopkg.in/lxc/go-lxc.v2" -) - -func TestLXCDriver_Fingerprint(t *testing.T) { - t.Parallel() - requireLXC(t) - - require := require.New(t) - - d := NewLXCDriver(testlog.HCLogger(t)).(*Driver) - d.config.Enabled = true - harness := dtestutil.NewDriverHarness(t, d) - - fingerCh, err := harness.Fingerprint(context.Background()) - require.NoError(err) - select { - case finger := <-fingerCh: - require.Equal(drivers.HealthStateHealthy, finger.Health) - require.True(finger.Attributes["driver.lxc"].GetBool()) - require.NotEmpty(finger.Attributes["driver.lxc.version"].GetString()) - case <-time.After(time.Duration(testutil.TestMultiplier()*5) * time.Second): - require.Fail("timeout receiving fingerprint") - } -} - -func TestLXCDriver_FingerprintNotEnabled(t *testing.T) { - t.Parallel() - requireLXC(t) - - require := require.New(t) - - d := NewLXCDriver(testlog.HCLogger(t)).(*Driver) - d.config.Enabled = false - harness := dtestutil.NewDriverHarness(t, d) - - fingerCh, err := harness.Fingerprint(context.Background()) - require.NoError(err) - select { - case finger := <-fingerCh: - require.Equal(drivers.HealthStateUndetected, finger.Health) - require.Empty(finger.Attributes["driver.lxc"]) - require.Empty(finger.Attributes["driver.lxc.version"]) - case <-time.After(time.Duration(testutil.TestMultiplier()*5) * time.Second): - require.Fail("timeout receiving fingerprint") - } -} - -func TestLXCDriver_Start_Wait(t *testing.T) { - if !testutil.IsTravis() { - t.Parallel() - } - requireLXC(t) - ctestutil.RequireRoot(t) - - require := require.New(t) - - // prepare test file - testFileContents := []byte("this should be visible under /mnt/tmp") - tmpFile, err := ioutil.TempFile("/tmp", "testlxcdriver_start_wait") - if err != nil { - t.Fatalf("error writing temp file: %v", err) - } - defer os.Remove(tmpFile.Name()) - if _, err := tmpFile.Write(testFileContents); err != nil { - t.Fatalf("error writing temp file: %v", err) - } - if err := tmpFile.Close(); err != nil { - t.Fatalf("error closing temp file: %v", err) - } - - d := NewLXCDriver(testlog.HCLogger(t)).(*Driver) - d.config.Enabled = true - d.config.AllowVolumes = true - - harness := dtestutil.NewDriverHarness(t, d) - task := &drivers.TaskConfig{ - ID: uuid.Generate(), - Name: "test", - Resources: &drivers.Resources{ - NomadResources: &structs.AllocatedTaskResources{ - Memory: structs.AllocatedMemoryResources{ - MemoryMB: 2, - }, - Cpu: structs.AllocatedCpuResources{ - CpuShares: 1024, - }, - }, - LinuxResources: &drivers.LinuxResources{ - CPUShares: 1024, - MemoryLimitBytes: 2 * 1024, - }, - }, - } - taskConfig := map[string]interface{}{ - "template": "/usr/share/lxc/templates/lxc-busybox", - "volumes": []string{"/tmp/:mnt/tmp"}, - } - encodeDriverHelper(require, task, taskConfig) - - cleanup := harness.MkAllocDir(task, false) - defer cleanup() - - handle, _, err := harness.StartTask(task) - require.NoError(err) - require.NotNil(handle) - - lxcHandle, ok := d.tasks.Get(task.ID) - require.True(ok) - - container := lxcHandle.container - - // Destroy container after test - defer func() { - container.Stop() - container.Destroy() - }() - - // Test that container is running - testutil.WaitForResult(func() (bool, error) { - state := container.State() - if state == lxc.RUNNING { - return true, nil - } - return false, fmt.Errorf("container in state: %v", state) - }, func(err error) { - t.Fatalf("container failed to start: %v", err) - }) - - // Test that directories are mounted in their proper location - containerName := container.Name() - for _, mnt := range []string{"alloc", "local", "secrets", "mnt/tmp"} { - fullpath := filepath.Join(d.lxcPath(), containerName, "rootfs", mnt) - stat, err := os.Stat(fullpath) - require.NoError(err) - require.True(stat.IsDir()) - } - - // Test bind mount volumes exist in container: - mountedContents, err := exec.Command("lxc-attach", - "-n", containerName, "--", - "cat", filepath.Join("/mnt/", tmpFile.Name()), - ).Output() - require.NoError(err) - require.Equal(string(testFileContents), string(mountedContents)) - - // Test that killing container marks container as stopped - require.NoError(container.Stop()) - - testutil.WaitForResult(func() (bool, error) { - status, err := d.InspectTask(task.ID) - if err == nil && status.State == drivers.TaskStateExited { - return true, nil - } - return false, fmt.Errorf("task in state: %v", status.State) - }, func(err error) { - t.Fatalf("task was not marked as stopped: %v", err) - }) -} - -func TestLXCDriver_Start_Stop(t *testing.T) { - if !testutil.IsTravis() { - t.Parallel() - } - requireLXC(t) - ctestutil.RequireRoot(t) - - require := require.New(t) - - d := NewLXCDriver(testlog.HCLogger(t)).(*Driver) - d.config.Enabled = true - d.config.AllowVolumes = true - - harness := dtestutil.NewDriverHarness(t, d) - task := &drivers.TaskConfig{ - ID: uuid.Generate(), - Name: "test", - Resources: &drivers.Resources{ - NomadResources: &structs.AllocatedTaskResources{ - Memory: structs.AllocatedMemoryResources{ - MemoryMB: 2, - }, - Cpu: structs.AllocatedCpuResources{ - CpuShares: 1024, - }, - }, - LinuxResources: &drivers.LinuxResources{ - CPUShares: 1024, - MemoryLimitBytes: 2 * 1024, - }, - }, - } - taskConfig := map[string]interface{}{ - "template": "/usr/share/lxc/templates/lxc-busybox", - } - encodeDriverHelper(require, task, taskConfig) - - cleanup := harness.MkAllocDir(task, false) - defer cleanup() - - handle, _, err := harness.StartTask(task) - require.NoError(err) - require.NotNil(handle) - - lxcHandle, ok := d.tasks.Get(task.ID) - require.True(ok) - - container := lxcHandle.container - - // Destroy container after test - defer func() { - container.Stop() - container.Destroy() - }() - - // Test that container is running - testutil.WaitForResult(func() (bool, error) { - state := container.State() - if state == lxc.RUNNING { - return true, nil - } - return false, fmt.Errorf("container in state: %v", state) - }, func(err error) { - t.Fatalf("container failed to start: %v", err) - }) - - require.NoError(d.StopTask(task.ID, 5*time.Second, "kill")) - - testutil.WaitForResult(func() (bool, error) { - status, err := d.InspectTask(task.ID) - if err == nil && status.State == drivers.TaskStateExited { - return true, nil - } - return false, fmt.Errorf("task in state: %v", status.State) - }, func(err error) { - t.Fatalf("task was not marked as stopped: %v", err) - }) -} - -func requireLXC(t *testing.T) { - if lxc.Version() == "" { - t.Skip("skipping, lxc not present") - } -} - -func encodeDriverHelper(require *require.Assertions, task *drivers.TaskConfig, taskConfig map[string]interface{}) { - evalCtx := &hcl.EvalContext{ - Functions: hclutils.GetStdlibFuncs(), - } - spec, diag := hclspec.Convert(taskConfigSpec) - require.False(diag.HasErrors()) - taskConfigCtyVal, diag := hclutils.ParseHclInterface(taskConfig, spec, evalCtx) - require.False(diag.HasErrors()) - err := task.EncodeDriverConfig(taskConfigCtyVal) - require.Nil(err) -} diff --git a/drivers/lxc/handle.go b/drivers/lxc/handle.go deleted file mode 100644 index 059f5d3db..000000000 --- a/drivers/lxc/handle.go +++ /dev/null @@ -1,199 +0,0 @@ -//+build linux,lxc - -package lxc - -import ( - "fmt" - "strconv" - "strings" - "sync" - "time" - - hclog "github.com/hashicorp/go-hclog" - "github.com/hashicorp/nomad/client/stats" - "github.com/hashicorp/nomad/plugins/drivers" - lxc "gopkg.in/lxc/go-lxc.v2" -) - -type taskHandle struct { - container *lxc.Container - initPid int - logger hclog.Logger - - totalCpuStats *stats.CpuStats - userCpuStats *stats.CpuStats - systemCpuStats *stats.CpuStats - - // stateLock syncs access to all fields below - stateLock sync.RWMutex - - taskConfig *drivers.TaskConfig - procState drivers.TaskState - startedAt time.Time - completedAt time.Time - exitResult *drivers.ExitResult -} - -var ( - LXCMeasuredCpuStats = []string{"System Mode", "User Mode", "Percent"} - - LXCMeasuredMemStats = []string{"RSS", "Cache", "Swap", "Max Usage", "Kernel Usage", "Kernel Max Usage"} -) - -func (h *taskHandle) TaskStatus() *drivers.TaskStatus { - h.stateLock.RLock() - defer h.stateLock.RUnlock() - - return &drivers.TaskStatus{ - ID: h.taskConfig.ID, - Name: h.taskConfig.Name, - State: h.procState, - StartedAt: h.startedAt, - CompletedAt: h.completedAt, - ExitResult: h.exitResult, - DriverAttributes: map[string]string{ - "pid": strconv.Itoa(h.initPid), - }, - } -} - -func (h *taskHandle) IsRunning() bool { - h.stateLock.RLock() - defer h.stateLock.RUnlock() - return h.procState == drivers.TaskStateRunning -} - -func (h *taskHandle) run() { - h.stateLock.Lock() - if h.exitResult == nil { - h.exitResult = &drivers.ExitResult{} - } - h.stateLock.Unlock() - - if ok, err := waitTillStopped(h.container); !ok { - h.logger.Error("failed to find container process", "error", err) - return - } - - h.stateLock.Lock() - defer h.stateLock.Unlock() - - h.procState = drivers.TaskStateExited - h.exitResult.ExitCode = 0 - h.exitResult.Signal = 0 - h.completedAt = time.Now() - - // TODO: detect if the task OOMed -} - -func (h *taskHandle) stats() (*drivers.TaskResourceUsage, error) { - cpuStats, err := h.container.CPUStats() - if err != nil { - h.logger.Error("failed to get container cpu stats", "error", err) - return nil, nil - } - total, err := h.container.CPUTime() - if err != nil { - h.logger.Error("failed to get container cpu time", "error", err) - return nil, nil - } - - t := time.Now() - - // Get the cpu stats - system := cpuStats["system"] - user := cpuStats["user"] - cs := &drivers.CpuStats{ - SystemMode: h.systemCpuStats.Percent(float64(system)), - UserMode: h.systemCpuStats.Percent(float64(user)), - Percent: h.totalCpuStats.Percent(float64(total)), - TotalTicks: float64(user + system), - Measured: LXCMeasuredCpuStats, - } - - // Get the Memory Stats - memData := map[string]uint64{ - "rss": 0, - "cache": 0, - "swap": 0, - } - rawMemStats := h.container.CgroupItem("memory.stat") - for _, rawMemStat := range rawMemStats { - key, val, err := keysToVal(rawMemStat) - if err != nil { - h.logger.Error("failed to get stat", "line", rawMemStat, "error", err) - continue - } - if _, ok := memData[key]; ok { - memData[key] = val - - } - } - ms := &drivers.MemoryStats{ - RSS: memData["rss"], - Cache: memData["cache"], - Swap: memData["swap"], - Measured: LXCMeasuredMemStats, - } - - mu := h.container.CgroupItem("memory.max_usage_in_bytes") - for _, rawMemMaxUsage := range mu { - val, err := strconv.ParseUint(rawMemMaxUsage, 10, 64) - if err != nil { - h.logger.Error("failed to get max memory usage", "error", err) - continue - } - ms.MaxUsage = val - } - ku := h.container.CgroupItem("memory.kmem.usage_in_bytes") - for _, rawKernelUsage := range ku { - val, err := strconv.ParseUint(rawKernelUsage, 10, 64) - if err != nil { - h.logger.Error("failed to get kernel memory usage", "error", err) - continue - } - ms.KernelUsage = val - } - - mku := h.container.CgroupItem("memory.kmem.max_usage_in_bytes") - for _, rawMaxKernelUsage := range mku { - val, err := strconv.ParseUint(rawMaxKernelUsage, 10, 64) - if err != nil { - h.logger.Error("failed tog get max kernel memory usage", "error", err) - continue - } - ms.KernelMaxUsage = val - } - - taskResUsage := drivers.TaskResourceUsage{ - ResourceUsage: &drivers.ResourceUsage{ - CpuStats: cs, - MemoryStats: ms, - }, - Timestamp: t.UTC().UnixNano(), - } - - return &taskResUsage, nil - -} - -func keysToVal(line string) (string, uint64, error) { - tokens := strings.Split(line, " ") - if len(tokens) != 2 { - return "", 0, fmt.Errorf("line isn't a k/v pair") - } - key := tokens[0] - val, err := strconv.ParseUint(tokens[1], 10, 64) - return key, val, err -} - -// shutdown shuts down the container, with `timeout` grace period -// before killing the container with SIGKILL. -func (h *taskHandle) shutdown(timeout time.Duration) error { - err := h.container.Shutdown(timeout) - if err == nil { - return nil - } - - return h.container.Stop() -} diff --git a/drivers/lxc/lxc.go b/drivers/lxc/lxc.go deleted file mode 100644 index c1431591b..000000000 --- a/drivers/lxc/lxc.go +++ /dev/null @@ -1,253 +0,0 @@ -//+build linux,lxc - -package lxc - -import ( - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "syscall" - "time" - - "github.com/hashicorp/nomad/plugins/drivers" - ldevices "github.com/opencontainers/runc/libcontainer/devices" - "gopkg.in/lxc/go-lxc.v2" -) - -var ( - verbosityLevels = map[string]lxc.Verbosity{ - "": lxc.Quiet, - "verbose": lxc.Verbose, - "quiet": lxc.Quiet, - } - - logLevels = map[string]lxc.LogLevel{ - "": lxc.ERROR, - "debug": lxc.DEBUG, - "error": lxc.ERROR, - "info": lxc.INFO, - "trace": lxc.TRACE, - "warn": lxc.WARN, - } -) - -const ( - // containerMonitorIntv is the interval at which the driver checks if the - // container is still alive - containerMonitorIntv = 2 * time.Second -) - -func (d *Driver) lxcPath() string { - lxcPath := d.config.Path - if lxcPath == "" { - lxcPath = lxc.DefaultConfigPath() - } - return lxcPath - -} -func (d *Driver) initializeContainer(cfg *drivers.TaskConfig, taskConfig TaskConfig) (*lxc.Container, error) { - lxcPath := d.lxcPath() - - containerName := fmt.Sprintf("%s-%s", cfg.Name, cfg.AllocID) - c, err := lxc.NewContainer(containerName, lxcPath) - if err != nil { - return nil, fmt.Errorf("failed to initialize container: %v", err) - } - - if v, ok := verbosityLevels[taskConfig.Verbosity]; ok { - c.SetVerbosity(v) - } else { - return nil, fmt.Errorf("lxc driver config 'verbosity' can only be either quiet or verbose") - } - - if v, ok := logLevels[taskConfig.LogLevel]; ok { - c.SetLogLevel(v) - } else { - return nil, fmt.Errorf("lxc driver config 'log_level' can only be trace, debug, info, warn or error") - } - - logFile := filepath.Join(cfg.TaskDir().Dir, fmt.Sprintf("%v-lxc.log", cfg.Name)) - c.SetLogFile(logFile) - - return c, nil -} - -func (d *Driver) configureContainerNetwork(c *lxc.Container) error { - // Set the network type to none - if err := c.SetConfigItem(networkTypeConfigKey(), "none"); err != nil { - return fmt.Errorf("error setting network type configuration: %v", err) - } - return nil -} - -func networkTypeConfigKey() string { - if lxc.VersionAtLeast(2, 1, 0) { - return "lxc.net.0.type" - } - - // prior to 2.1, network used - return "lxc.network.type" -} - -func (d *Driver) mountVolumes(c *lxc.Container, cfg *drivers.TaskConfig, taskConfig TaskConfig) error { - mounts, err := d.mountEntries(cfg, taskConfig) - if err != nil { - return err - } - - devCgroupAllows, err := d.devicesCgroupEntries(cfg) - if err != nil { - return err - } - - for _, mnt := range mounts { - if err := c.SetConfigItem("lxc.mount.entry", mnt); err != nil { - return fmt.Errorf("error setting bind mount %q error: %v", mnt, err) - } - } - - for _, cgroupDev := range devCgroupAllows { - if err := c.SetConfigItem("lxc.cgroup.devices.allow", cgroupDev); err != nil { - return fmt.Errorf("error setting cgroup permission %q error: %v", cgroupDev, err) - } - } - - return nil -} - -// mountEntries compute the mount entries to be set on the container -func (d *Driver) mountEntries(cfg *drivers.TaskConfig, taskConfig TaskConfig) ([]string, error) { - // Bind mount the shared alloc dir and task local dir in the container - mounts := []string{ - fmt.Sprintf("%s local none rw,bind,create=dir", cfg.TaskDir().LocalDir), - fmt.Sprintf("%s alloc none rw,bind,create=dir", cfg.TaskDir().SharedAllocDir), - fmt.Sprintf("%s secrets none rw,bind,create=dir", cfg.TaskDir().SecretsDir), - } - - mounts = append(mounts, d.formatTaskMounts(cfg.Mounts)...) - mounts = append(mounts, d.formatTaskDevices(cfg.Devices)...) - - volumesEnabled := d.config.AllowVolumes - - for _, volDesc := range taskConfig.Volumes { - // the format was checked in Validate() - paths := strings.Split(volDesc, ":") - - if filepath.IsAbs(paths[0]) { - if !volumesEnabled { - return nil, fmt.Errorf("absolute bind-mount volume in config but volumes are disabled") - } - } else { - // Relative source paths are treated as relative to alloc dir - paths[0] = filepath.Join(cfg.TaskDir().Dir, paths[0]) - } - - // LXC assumes paths are relative with respect to rootfs - target := strings.TrimLeft(paths[1], "/") - mounts = append(mounts, fmt.Sprintf("%s %s none rw,bind,create=dir", paths[0], target)) - } - - return mounts, nil - -} - -func (d *Driver) devicesCgroupEntries(cfg *drivers.TaskConfig) ([]string, error) { - entries := make([]string, len(cfg.Devices)) - - for i, d := range cfg.Devices { - hd, err := ldevices.DeviceFromPath(d.HostPath, d.Permissions) - if err != nil { - return nil, err - } - - entries[i] = hd.CgroupString() - } - - return entries, nil -} - -func (d *Driver) formatTaskMounts(mounts []*drivers.MountConfig) []string { - result := make([]string, len(mounts)) - - for i, m := range mounts { - result[i] = d.formatMount(m.HostPath, m.TaskPath, m.Readonly) - } - - return result -} - -func (d *Driver) formatTaskDevices(devices []*drivers.DeviceConfig) []string { - result := make([]string, len(devices)) - - for i, m := range devices { - result[i] = d.formatMount(m.HostPath, m.TaskPath, - !strings.Contains(m.Permissions, "w")) - } - - return result -} - -func (d *Driver) formatMount(hostPath, taskPath string, readOnly bool) string { - typ := "dir" - s, err := os.Stat(hostPath) - if err != nil { - d.logger.Warn("failed to find mount host path type, defaulting to dir type", "path", hostPath, "error", err) - } else if !s.IsDir() { - typ = "file" - } - - perm := "rw" - if readOnly { - perm = "ro" - } - - // LXC assumes paths are relative with respect to rootfs - target := strings.TrimLeft(taskPath, "/") - return fmt.Sprintf("%s %s none %s,bind,create=%s", hostPath, target, perm, typ) -} - -func (d *Driver) setResourceLimits(c *lxc.Container, cfg *drivers.TaskConfig) error { - if err := c.SetMemoryLimit(lxc.ByteSize(cfg.Resources.NomadResources.Memory.MemoryMB) * lxc.MB); err != nil { - return fmt.Errorf("unable to set memory limits: %v", err) - } - - if err := c.SetCgroupItem("cpu.shares", strconv.FormatInt(cfg.Resources.LinuxResources.CPUShares, 10)); err != nil { - return fmt.Errorf("unable to set cpu shares: %v", err) - } - - return nil -} - -func toLXCCreateOptions(taskConfig TaskConfig) lxc.TemplateOptions { - return lxc.TemplateOptions{ - Template: taskConfig.Template, - Distro: taskConfig.Distro, - Release: taskConfig.Release, - Arch: taskConfig.Arch, - FlushCache: taskConfig.FlushCache, - DisableGPGValidation: taskConfig.DisableGPGValidation, - ExtraArgs: taskConfig.TemplateArgs, - } -} - -// waitTillStopped blocks and returns true when container stops; -// returns false with an error message if the container processes cannot be identified. -// -// Use this in preference to c.Wait() - lxc Wait() function holds a write lock on the container -// blocking any other operation on container, including looking up container stats -func waitTillStopped(c *lxc.Container) (bool, error) { - ps, err := os.FindProcess(c.InitPid()) - if err != nil { - return false, err - } - - for { - if err := ps.Signal(syscall.Signal(0)); err != nil { - return true, nil - } - - time.Sleep(containerMonitorIntv) - } -} diff --git a/drivers/lxc/lxc_test.go b/drivers/lxc/lxc_test.go deleted file mode 100644 index 2aed490a7..000000000 --- a/drivers/lxc/lxc_test.go +++ /dev/null @@ -1,95 +0,0 @@ -//+build linux,lxc - -package lxc - -import ( - "testing" - - "github.com/hashicorp/nomad/helper/testlog" - "github.com/hashicorp/nomad/helper/uuid" - "github.com/hashicorp/nomad/nomad/structs" - "github.com/hashicorp/nomad/plugins/drivers" - "github.com/stretchr/testify/require" -) - -func TestLXCDriver_Mounts(t *testing.T) { - t.Parallel() - - task := &drivers.TaskConfig{ - ID: uuid.Generate(), - Name: "test", - Resources: &drivers.Resources{ - NomadResources: &structs.AllocatedTaskResources{ - Memory: structs.AllocatedMemoryResources{ - MemoryMB: 2, - }, - Cpu: structs.AllocatedCpuResources{ - CpuShares: 1024, - }, - }, - LinuxResources: &drivers.LinuxResources{ - CPUShares: 1024, - MemoryLimitBytes: 2 * 1024, - }, - }, - Mounts: []*drivers.MountConfig{ - {HostPath: "/dev", TaskPath: "/task-mounts/dev-path"}, - {HostPath: "/bin/sh", TaskPath: "/task-mounts/task-path-ro", Readonly: true}, - }, - Devices: []*drivers.DeviceConfig{ - {HostPath: "/dev", TaskPath: "/task-devices/dev-path", Permissions: "rw"}, - {HostPath: "/bin/sh", TaskPath: "/task-devices/task-path-ro", Permissions: "ro"}, - }, - } - taskConfig := TaskConfig{ - Template: "busybox", - Volumes: []string{ - "relative/path:/usr-config/container/path", - "relative/path2:usr-config/container/relative", - }, - } - - d := NewLXCDriver(testlog.HCLogger(t)).(*Driver) - d.config.Enabled = true - - entries, err := d.mountEntries(task, taskConfig) - require.NoError(t, err) - - expectedEntries := []string{ - "test/relative/path usr-config/container/path none rw,bind,create=dir", - "test/relative/path2 usr-config/container/relative none rw,bind,create=dir", - "/dev task-mounts/dev-path none rw,bind,create=dir", - "/bin/sh task-mounts/task-path-ro none ro,bind,create=file", - "/dev task-devices/dev-path none rw,bind,create=dir", - "/bin/sh task-devices/task-path-ro none ro,bind,create=file", - } - - for _, e := range expectedEntries { - require.Contains(t, entries, e) - } -} - -func TestLXCDriver_DevicesCgroup(t *testing.T) { - t.Parallel() - - task := &drivers.TaskConfig{ - ID: uuid.Generate(), - Name: "test", - Devices: []*drivers.DeviceConfig{ - {HostPath: "/dev/random", TaskPath: "/task-devices/devrandom", Permissions: "rw"}, - {HostPath: "/dev/null", TaskPath: "/task-devices/devnull", Permissions: "rwm"}, - }, - } - - d := NewLXCDriver(testlog.HCLogger(t)).(*Driver) - d.config.Enabled = true - - cgroupEntries, err := d.devicesCgroupEntries(task) - require.NoError(t, err) - - expected := []string{ - "c 1:8 rw", - "c 1:3 rwm", - } - require.EqualValues(t, expected, cgroupEntries) -} diff --git a/drivers/lxc/state.go b/drivers/lxc/state.go deleted file mode 100644 index c316a6cc6..000000000 --- a/drivers/lxc/state.go +++ /dev/null @@ -1,35 +0,0 @@ -//+build linux,lxc - -package lxc - -import ( - "sync" -) - -type taskStore struct { - store map[string]*taskHandle - lock sync.RWMutex -} - -func newTaskStore() *taskStore { - return &taskStore{store: map[string]*taskHandle{}} -} - -func (ts *taskStore) Set(id string, handle *taskHandle) { - ts.lock.Lock() - defer ts.lock.Unlock() - ts.store[id] = handle -} - -func (ts *taskStore) Get(id string) (*taskHandle, bool) { - ts.lock.RLock() - defer ts.lock.RUnlock() - t, ok := ts.store[id] - return t, ok -} - -func (ts *taskStore) Delete(id string) { - ts.lock.Lock() - defer ts.lock.Unlock() - delete(ts.store, id) -} diff --git a/helper/funcs.go b/helper/funcs.go index cf9cc3dae..d3ccfd8d4 100644 --- a/helper/funcs.go +++ b/helper/funcs.go @@ -366,6 +366,4 @@ func FormatFloat(f float64, maxPrec int) string { } return v[:sublen] - - return v } diff --git a/plugins/shared/catalog/register_lxc.go b/plugins/shared/catalog/register_lxc.go deleted file mode 100644 index 6a029ec3f..000000000 --- a/plugins/shared/catalog/register_lxc.go +++ /dev/null @@ -1,14 +0,0 @@ -//+build linux,lxc - -package catalog - -import ( - "github.com/hashicorp/nomad/drivers/lxc" -) - -// This file is where all builtin plugins should be registered in the catalog. -// Plugins with build restrictions should be placed in the appropriate -// register_XXX.go file. -func init() { - RegisterDeferredConfig(lxc.PluginID, lxc.PluginConfig, lxc.PluginLoader) -} diff --git a/scheduler/preemption.go b/scheduler/preemption.go index d65c2f71c..6c71a53fa 100644 --- a/scheduler/preemption.go +++ b/scheduler/preemption.go @@ -160,7 +160,7 @@ func (p *Preemptor) SetPreemptions(allocs []*structs.Allocation) { // Initialize counts for _, alloc := range allocs { - id := structs.NamespacedID{alloc.JobID, alloc.Namespace} + id := structs.NewNamespacedID(alloc.JobID, alloc.Namespace) countMap, ok := p.currentPreemptions[id] if !ok { countMap = make(map[string]int) @@ -173,7 +173,7 @@ func (p *Preemptor) SetPreemptions(allocs []*structs.Allocation) { // getNumPreemptions counts the number of other allocations being preempted that match the job and task group of // the alloc under consideration. This is used as a scoring factor to minimize too many allocs of the same job being preempted at once func (p *Preemptor) getNumPreemptions(alloc *structs.Allocation) int { - c, ok := p.currentPreemptions[structs.NamespacedID{alloc.JobID, alloc.Namespace}][alloc.TaskGroup] + c, ok := p.currentPreemptions[structs.NewNamespacedID(alloc.JobID, alloc.Namespace)][alloc.TaskGroup] if !ok { return 0 } diff --git a/scripts/travis-linux.sh b/scripts/travis-linux.sh index aeb022189..6f25b9b3c 100644 --- a/scripts/travis-linux.sh +++ b/scripts/travis-linux.sh @@ -10,8 +10,7 @@ sudo service docker restart # true errors would fail in the apt-get install phase apt-get update || true -apt-get install -y liblxc1 lxc-dev lxc lxc-templates shellcheck -apt-get install -y qemu +apt-get install -y qemu shellcheck bash ./scripts/travis-rkt.sh bash ./scripts/travis-consul.sh bash ./scripts/travis-vault.sh diff --git a/scripts/vagrant-linux-priv-config.sh b/scripts/vagrant-linux-priv-config.sh index 4c23f41b5..7c8b38c52 100755 --- a/scripts/vagrant-linux-priv-config.sh +++ b/scripts/vagrant-linux-priv-config.sh @@ -26,11 +26,8 @@ apt-get install -y \ build-essential \ git \ libc6-dev-i386 \ - liblxc1 \ libpcre3-dev \ linux-libc-dev:i386 \ - lxc-dev \ - lxc-templates \ pkg-config \ zip diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/AUTHORS b/vendor/gopkg.in/lxc/go-lxc.v2/AUTHORS deleted file mode 100644 index a4aff7d5c..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/AUTHORS +++ /dev/null @@ -1,16 +0,0 @@ -# This is the official list of Go-LXC authors for copyright purposes. - -# Names should be added to this file as -#Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -David Cramer -Fatih Arslan -Kelsey Hightower -S.Çağlar Onur -Serge Hallyn -Stéphane Graber -Syed -Tycho Andersen diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/LICENSE b/vendor/gopkg.in/lxc/go-lxc.v2/LICENSE deleted file mode 100644 index f22c6c94c..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/LICENSE +++ /dev/null @@ -1,522 +0,0 @@ -This software is licensed under the LGPLv2.1, included below. - -As a special exception to the GNU Lesser General Public License version 2.1 -("LGPL2.1"), the copyright holders of this Library give you permission to -convey to a third party a Combined Work that links statically or dynamically -to this Library without providing any Minimal Corresponding Source or -Minimal Application Code or providing the installation information, -provided that you comply with the other provisions of LGPL2.1 -and provided that you meet, for the Application the terms and conditions -of the license(s) which apply to the Application. - -Except as stated in this special exception, the provisions of LGPL2.1 will -continue to comply in full to this Library. If you modify this Library, you -may apply this exception to your version of this Library, but you are not -obliged to do so. If you do not wish to do so, delete this exception -statement from your version. This exception does not (and cannot) modify any -license terms which apply to the Application, with which you must still -comply. - - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/Makefile b/vendor/gopkg.in/lxc/go-lxc.v2/Makefile deleted file mode 100644 index 149ce6636..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/Makefile +++ /dev/null @@ -1,60 +0,0 @@ -NO_COLOR=\033[0m -OK_COLOR=\033[0;32m - -all: format vet lint - -format: - @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" - @gofmt -s -w *.go - @goimports -w *.go || true - -test: - @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" - @sudo `which go` test -v - -test-race: - @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" - @sudo `which go` test -race -v - -test-unprivileged: - @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" - @`which go` test -v - -test-unprivileged-race: - @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" - @`which go` test -race -v - -cover: - @sudo `which go` test -v -coverprofile=coverage.out - @`which go` tool cover -func=coverage.out - -doc: - @`which godoc` gopkg.in/lxc/go-lxc.v2 | less - -vet: - @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" - @`which go` vet . - -lint: - @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" - @`which golint` . || true - -escape-analysis: - @go build -gcflags -m - -ctags: - @ctags -R --languages=c,go - -scope: - @echo "$(OK_COLOR)==> Exported container calls in container.go $(NO_COLOR)" - @/bin/grep -E "\bc+\.([A-Z])\w+" container.go || true - -setup-test-cgroup: - for d in /sys/fs/cgroup/*; do \ - [ -f $$d/cgroup.clone_children ] && echo 1 | sudo tee $$d/cgroup.clone_children; \ - [ -f $$d/cgroup.use_hierarchy ] && echo 1 | sudo tee $$d/cgroup.use_hierarchy; \ - sudo mkdir -p $$d/lxc; \ - sudo chown -R $$USER: $$d/lxc; \ - done - -.PHONY: all format test doc vet lint ctags diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/README.md b/vendor/gopkg.in/lxc/go-lxc.v2/README.md deleted file mode 100644 index d737fa79b..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Go Bindings for LXC (Linux Containers) - -This package implements [Go](http://golang.org) bindings for the [LXC](http://linuxcontainers.org/) C API (liblxc). - -## Requirements - -This package requires [LXC 1.x](https://github.com/lxc/lxc/releases) and its development package to be installed. Works with [Go 1.x](http://golang.org/dl). Following command should install required dependencies on Ubuntu: - - apt-get install -y pkg-config lxc-dev - -## Installing - -To install it, run: - - go get gopkg.in/lxc/go-lxc.v2 - -## Documentation - -Documentation can be found at [GoDoc](http://godoc.org/gopkg.in/lxc/go-lxc.v2). - -## Stability - -The package API will remain stable as described in [gopkg.in](https://gopkg.in). - -## Examples - -See the [examples](https://github.com/lxc/go-lxc/tree/v2/examples) directory for some. - -## Contributing - -We'd love to see go-lxc improve. To contribute to go-lxc; - -* **Fork** the repository -* **Modify** your fork -* Ensure your fork **passes all tests** -* **Send** a pull request - * Bonus points if the pull request includes *what* you changed, *why* you changed it, and *tests* attached. - * For the love of all that is holy, please use `go fmt` *before* you send the pull request. - -We'll review it and merge it in if it's appropriate. diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/container.go b/vendor/gopkg.in/lxc/go-lxc.v2/container.go deleted file mode 100644 index 58f1d7f2f..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/container.go +++ /dev/null @@ -1,1909 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -package lxc - -// #include -// #include -// #include "lxc-binding.h" -import "C" - -import ( - "fmt" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "reflect" - "strconv" - "strings" - "sync" - "syscall" - "time" - "unsafe" -) - -// Container struct -type Container struct { - mu sync.RWMutex - container *C.struct_lxc_container - - verbosity Verbosity -} - -// Snapshot struct -type Snapshot struct { - Name string - CommentPath string - Timestamp string - Path string -} - -const ( - isDefined = 1 << iota - isNotDefined - isRunning - isNotRunning - isPrivileged - isUnprivileged - isGreaterEqualThanLXC11 - isGreaterEqualThanLXC20 -) - -func (c *Container) makeSure(flags int) error { - if flags&isDefined != 0 && !c.defined() { - return fmt.Errorf("%s: %q", ErrNotDefined, c.name()) - } - - if flags&isNotDefined != 0 && c.defined() { - return fmt.Errorf("%s: %q", ErrAlreadyDefined, c.name()) - } - - if flags&isRunning != 0 && !c.running() { - return fmt.Errorf("%s: %q", ErrNotRunning, c.name()) - } - - if flags&isNotRunning != 0 && c.running() { - return fmt.Errorf("%s: %q", ErrAlreadyRunning, c.name()) - } - - if flags&isPrivileged != 0 && os.Geteuid() != 0 { - return ErrMethodNotAllowed - } - - if flags&isGreaterEqualThanLXC11 != 0 && !VersionAtLeast(1, 1, 0) { - return ErrNotSupported - } - - if flags&isGreaterEqualThanLXC20 != 0 && !VersionAtLeast(2, 0, 0) { - return ErrNotSupported - } - - return nil -} - -func (c *Container) cgroupItemAsByteSize(filename string, missing error) (ByteSize, error) { - size, err := strconv.ParseFloat(c.cgroupItem(filename)[0], 64) - if err != nil { - return -1, missing - } - return ByteSize(size), nil -} - -func (c *Container) setCgroupItemWithByteSize(filename string, limit ByteSize, missing error) error { - if err := c.setCgroupItem(filename, fmt.Sprintf("%.f", limit)); err != nil { - return missing - } - return nil -} - -func (c *Container) name() string { - return C.GoString(c.container.name) -} - -// Name returns the name of the container. -func (c *Container) Name() string { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.name() -} - -// String returns the string represantation of container. -func (c *Container) String() string { - c.mu.RLock() - defer c.mu.RUnlock() - - return path.Join(c.configPath(), c.name()) -} - -// Caller needs to hold the lock -func (c *Container) defined() bool { - return bool(C.go_lxc_defined(c.container)) -} - -// Defined returns true if the container is already defined. -func (c *Container) Defined() bool { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.defined() -} - -// Caller needs to hold the lock -func (c *Container) running() bool { - return bool(C.go_lxc_running(c.container)) -} - -// Running returns true if the container is already running. -func (c *Container) Running() bool { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.running() -} - -// Controllable returns true if the caller can control the container. -func (c *Container) Controllable() bool { - c.mu.RLock() - defer c.mu.RUnlock() - - return bool(C.go_lxc_may_control(c.container)) -} - -// CreateSnapshot creates a new snapshot. -func (c *Container) CreateSnapshot() (*Snapshot, error) { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined | isNotRunning); err != nil { - return nil, err - } - - ret := int(C.go_lxc_snapshot(c.container)) - if ret < 0 { - return nil, ErrCreateSnapshotFailed - } - return &Snapshot{Name: fmt.Sprintf("snap%d", ret)}, nil -} - -// RestoreSnapshot creates a new container based on a snapshot. -func (c *Container) RestoreSnapshot(snapshot Snapshot, name string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined); err != nil { - return err - } - - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - - csnapname := C.CString(snapshot.Name) - defer C.free(unsafe.Pointer(csnapname)) - - if !bool(C.go_lxc_snapshot_restore(c.container, csnapname, cname)) { - return ErrRestoreSnapshotFailed - } - return nil -} - -// DestroySnapshot destroys the specified snapshot. -func (c *Container) DestroySnapshot(snapshot Snapshot) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined); err != nil { - return err - } - - csnapname := C.CString(snapshot.Name) - defer C.free(unsafe.Pointer(csnapname)) - - if !bool(C.go_lxc_snapshot_destroy(c.container, csnapname)) { - return ErrDestroySnapshotFailed - } - return nil -} - -// DestroyAllSnapshots destroys all the snapshot. -func (c *Container) DestroyAllSnapshots() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined | isGreaterEqualThanLXC11); err != nil { - return err - } - - if !bool(C.go_lxc_snapshot_destroy_all(c.container)) { - return ErrDestroyAllSnapshotsFailed - } - return nil -} - -// Snapshots returns the list of container snapshots. -func (c *Container) Snapshots() ([]Snapshot, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isDefined); err != nil { - return nil, err - } - - var csnapshots *C.struct_lxc_snapshot - - size := int(C.go_lxc_snapshot_list(c.container, &csnapshots)) - defer freeSnapshots(csnapshots, size) - - if size < 1 { - return nil, ErrNoSnapshot - } - - hdr := reflect.SliceHeader{ - Data: uintptr(unsafe.Pointer(csnapshots)), - Len: size, - Cap: size, - } - gosnapshots := *(*[]C.struct_lxc_snapshot)(unsafe.Pointer(&hdr)) - - snapshots := make([]Snapshot, size, size) - for i := 0; i < size; i++ { - snapshots[i] = Snapshot{ - Name: C.GoString(gosnapshots[i].name), - Timestamp: C.GoString(gosnapshots[i].timestamp), - CommentPath: C.GoString(gosnapshots[i].comment_pathname), - Path: C.GoString(gosnapshots[i].lxcpath), - } - } - - return snapshots, nil -} - -// Caller needs to hold the lock -func (c *Container) state() State { - return StateMap[C.GoString(C.go_lxc_state(c.container))] -} - -// State returns the state of the container. -func (c *Container) State() State { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.state() -} - -// InitPid returns the process ID of the container's init process -// seen from outside the container. -func (c *Container) InitPid() int { - c.mu.RLock() - defer c.mu.RUnlock() - - return int(C.go_lxc_init_pid(c.container)) -} - -// Daemonize returns true if the container wished to be daemonized. -func (c *Container) Daemonize() bool { - c.mu.RLock() - defer c.mu.RUnlock() - - return bool(c.container.daemonize) -} - -// WantDaemonize determines if the container wants to run daemonized. -func (c *Container) WantDaemonize(state bool) error { - c.mu.Lock() - defer c.mu.Unlock() - - if !bool(C.go_lxc_want_daemonize(c.container, C.bool(state))) { - return ErrDaemonizeFailed - } - return nil -} - -// WantCloseAllFds determines whether container wishes all file descriptors -// to be closed on startup. -func (c *Container) WantCloseAllFds(state bool) error { - c.mu.Lock() - defer c.mu.Unlock() - - if !bool(C.go_lxc_want_close_all_fds(c.container, C.bool(state))) { - return ErrCloseAllFdsFailed - } - return nil -} - -// SetVerbosity sets the verbosity level of some API calls -func (c *Container) SetVerbosity(verbosity Verbosity) { - c.mu.Lock() - defer c.mu.Unlock() - - c.verbosity = verbosity -} - -// Freeze freezes the running container. -func (c *Container) Freeze() error { - c.mu.Lock() - defer c.mu.Unlock() - - // check the state using lockless version - if c.state() == FROZEN { - return ErrAlreadyFrozen - } - - if !bool(C.go_lxc_freeze(c.container)) { - return ErrFreezeFailed - } - - return nil -} - -// Unfreeze thaws the frozen container. -func (c *Container) Unfreeze() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - // check the state using lockless version - if c.state() != FROZEN { - return ErrNotFrozen - } - - if !bool(C.go_lxc_unfreeze(c.container)) { - return ErrUnfreezeFailed - } - - return nil -} - -// Create creates the container using given TemplateOptions -func (c *Container) Create(options TemplateOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - // FIXME: Support bdev_specs - // - // bdev_specs: - // zfs requires zfsroot - // lvm requires lvname/vgname/thinpool as well as fstype and fssize - // btrfs requires nothing - // dir requires nothing - if err := c.makeSure(isNotDefined); err != nil { - return err - } - - // use download template if not set - if options.Template == "" { - options.Template = "download" - } - - // use Directory backend if not set - if options.Backend == 0 { - options.Backend = Directory - } - - var args []string - if options.Template == "download" { - // required parameters - if options.Distro == "" || options.Release == "" || options.Arch == "" { - return ErrInsufficientNumberOfArguments - } - args = append(args, "--dist", options.Distro, "--release", options.Release, "--arch", options.Arch) - - // optional arguments - if options.Variant != "" { - args = append(args, "--variant", options.Variant) - } - if options.Server != "" { - args = append(args, "--server", options.Server) - } - if options.KeyID != "" { - args = append(args, "--keyid", options.KeyID) - } - if options.KeyServer != "" { - args = append(args, "--keyserver", options.KeyServer) - } - if options.DisableGPGValidation { - args = append(args, "--no-validate") - } - if options.FlushCache { - args = append(args, "--flush-cache") - } - if options.ForceCache { - args = append(args, "--force-cache") - } - } else { - // optional arguments - if options.Release != "" { - args = append(args, "--release", options.Release) - } - if options.Arch != "" { - args = append(args, "--arch", options.Arch) - } - if options.FlushCache { - args = append(args, "--flush-cache") - } - } - - if options.ExtraArgs != nil { - args = append(args, options.ExtraArgs...) - } - - ctemplate := C.CString(options.Template) - defer C.free(unsafe.Pointer(ctemplate)) - - cbackend := C.CString(options.Backend.String()) - defer C.free(unsafe.Pointer(cbackend)) - - ret := false - if args != nil { - cargs := makeNullTerminatedArgs(args) - if cargs == nil { - return ErrAllocationFailed - } - defer freeNullTerminatedArgs(cargs, len(args)) - - ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), cargs)) - } else { - ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), nil)) - } - - if !ret { - return ErrCreateFailed - } - return nil -} - -// Start starts the container. -func (c *Container) Start() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isNotRunning); err != nil { - return err - } - - if !bool(C.go_lxc_start(c.container, 0, nil)) { - return ErrStartFailed - } - return nil -} - -// StartWithArgs starts the container using given arguments. -func (c *Container) StartWithArgs(args []string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isNotRunning); err != nil { - return err - } - - if !bool(C.go_lxc_start(c.container, 0, makeNullTerminatedArgs(args))) { - return ErrStartFailed - } - return nil -} - -// StartExecute starts a container. It runs a minimal init as PID 1 and the -// requested program as the second process. -func (c *Container) StartExecute(args []string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isNotRunning); err != nil { - return err - } - - if !bool(C.go_lxc_start(c.container, 1, makeNullTerminatedArgs(args))) { - return ErrStartFailed - } - - return nil -} - -// Execute executes the given command in a temporary container. -func (c *Container) Execute(args ...string) ([]byte, error) { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isNotDefined); err != nil { - return nil, err - } - - os.MkdirAll(filepath.Join(c.configPath(), c.name()), 0700) - c.saveConfigFile(filepath.Join(c.configPath(), c.name(), "config")) - defer os.RemoveAll(filepath.Join(c.configPath(), c.name())) - - cargs := []string{"lxc-execute", "-n", c.name(), "-P", c.configPath(), "--"} - cargs = append(cargs, args...) - - // FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now - // go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ - output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput() - if err != nil { - // Do not suppress stderr if the exit code != 0. Return with err. - if len(output) > 1 { - return output, ErrExecuteFailed - } - - return nil, ErrExecuteFailed - } - - return output, nil -} - -// Stop stops the container. -func (c *Container) Stop() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - if !bool(C.go_lxc_stop(c.container)) { - return ErrStopFailed - } - return nil -} - -// Reboot reboots the container. -func (c *Container) Reboot() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - if !bool(C.go_lxc_reboot(c.container)) { - return ErrRebootFailed - } - return nil -} - -// Shutdown shuts down the container. -func (c *Container) Shutdown(timeout time.Duration) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - if !bool(C.go_lxc_shutdown(c.container, C.int(timeout.Seconds()))) { - return ErrShutdownFailed - } - return nil -} - -// Destroy destroys the container. -func (c *Container) Destroy() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined | isNotRunning); err != nil { - return err - } - - if !bool(C.go_lxc_destroy(c.container)) { - return ErrDestroyFailed - } - return nil -} - -// DestroyWithAllSnapshots destroys the container and its snapshots -func (c *Container) DestroyWithAllSnapshots() error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined | isNotRunning | isGreaterEqualThanLXC11); err != nil { - return err - } - - if !bool(C.go_lxc_destroy_with_snapshots(c.container)) { - return ErrDestroyWithAllSnapshotsFailed - } - return nil -} - -// Clone clones the container using given arguments with specified backend. -func (c *Container) Clone(name string, options CloneOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - // FIXME: bdevdata, newsize and hookargs - // - // bdevdata: - // zfs requires zfsroot - // lvm requires lvname/vgname/thinpool as well as fstype and fssize - // btrfs requires nothing - // dir requires nothing - // - // newsize: for blockdev-backed backingstores - // - // hookargs: additional arguments to pass to the clone hook script - if err := c.makeSure(isDefined | isNotRunning); err != nil { - return err - } - - // use Directory backend if not set - if options.Backend == 0 { - options.Backend = Directory - } - - var flags int - if options.KeepName { - flags |= C.LXC_CLONE_KEEPNAME - } - if options.KeepMAC { - flags |= C.LXC_CLONE_KEEPMACADDR - } - if options.Snapshot { - flags |= C.LXC_CLONE_SNAPSHOT - } - - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - - cbackend := C.CString(options.Backend.String()) - defer C.free(unsafe.Pointer(cbackend)) - - if options.ConfigPath != "" { - clxcpath := C.CString(options.ConfigPath) - defer C.free(unsafe.Pointer(clxcpath)) - - if !bool(C.go_lxc_clone(c.container, cname, clxcpath, C.int(flags), cbackend)) { - return ErrCloneFailed - } - } else { - if !bool(C.go_lxc_clone(c.container, cname, nil, C.int(flags), cbackend)) { - return ErrCloneFailed - } - } - return nil -} - -// Rename renames the container. -func (c *Container) Rename(name string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isDefined | isNotRunning); err != nil { - return err - } - - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - - if !bool(C.go_lxc_rename(c.container, cname)) { - return ErrRenameFailed - } - return nil -} - -// Wait waits for container to reach a particular state. -func (c *Container) Wait(state State, timeout time.Duration) bool { - c.mu.Lock() - defer c.mu.Unlock() - - cstate := C.CString(state.String()) - defer C.free(unsafe.Pointer(cstate)) - - return bool(C.go_lxc_wait(c.container, cstate, C.int(timeout.Seconds()))) -} - -// ConfigFileName returns the container's configuration file's name. -func (c *Container) ConfigFileName() string { - c.mu.RLock() - defer c.mu.RUnlock() - - // allocated in lxc.c - configFileName := C.go_lxc_config_file_name(c.container) - defer C.free(unsafe.Pointer(configFileName)) - - return C.GoString(configFileName) -} - -func (c *Container) configItem(key string) []string { - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - // allocated in lxc.c - configItem := C.go_lxc_get_config_item(c.container, ckey) - defer C.free(unsafe.Pointer(configItem)) - - ret := strings.TrimSpace(C.GoString(configItem)) - return strings.Split(ret, "\n") -} - -// ConfigItem returns the value of the given config item. -func (c *Container) ConfigItem(key string) []string { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.configItem(key) -} - -func (c *Container) setConfigItem(key string, value string) error { - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - cvalue := C.CString(value) - defer C.free(unsafe.Pointer(cvalue)) - - if !bool(C.go_lxc_set_config_item(c.container, ckey, cvalue)) { - return ErrSettingConfigItemFailed - } - return nil -} - -// SetConfigItem sets the value of the given config item. -func (c *Container) SetConfigItem(key string, value string) error { - c.mu.Lock() - defer c.mu.Unlock() - - return c.setConfigItem(key, value) -} - -func (c *Container) runningConfigItem(key string) []string { - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - // allocated in lxc.c - configItem := C.go_lxc_get_running_config_item(c.container, ckey) - defer C.free(unsafe.Pointer(configItem)) - - ret := strings.TrimSpace(C.GoString(configItem)) - return strings.Split(ret, "\n") -} - -// RunningConfigItem returns the value of the given config item. -func (c *Container) RunningConfigItem(key string) []string { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.runningConfigItem(key) -} - -func (c *Container) cgroupItem(key string) []string { - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - // allocated in lxc.c - cgroupItem := C.go_lxc_get_cgroup_item(c.container, ckey) - defer C.free(unsafe.Pointer(cgroupItem)) - - ret := strings.TrimSpace(C.GoString(cgroupItem)) - return strings.Split(ret, "\n") -} - -func (c *Container) setCgroupItem(key string, value string) error { - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - cvalue := C.CString(value) - defer C.free(unsafe.Pointer(cvalue)) - - if !bool(C.go_lxc_set_cgroup_item(c.container, ckey, cvalue)) { - return ErrSettingCgroupItemFailed - } - return nil -} - -// CgroupItem returns the value of the given cgroup subsystem value. -func (c *Container) CgroupItem(key string) []string { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.cgroupItem(key) -} - -// SetCgroupItem sets the value of given cgroup subsystem value. -func (c *Container) SetCgroupItem(key string, value string) error { - c.mu.Lock() - defer c.mu.Unlock() - - return c.setCgroupItem(key, value) -} - -// ClearConfig completely clears the containers in-memory configuration. -func (c *Container) ClearConfig() { - c.mu.Lock() - defer c.mu.Unlock() - - C.go_lxc_clear_config(c.container) -} - -// ClearConfigItem clears the value of given config item. -func (c *Container) ClearConfigItem(key string) error { - c.mu.Lock() - defer c.mu.Unlock() - - ckey := C.CString(key) - defer C.free(unsafe.Pointer(ckey)) - - if !bool(C.go_lxc_clear_config_item(c.container, ckey)) { - return ErrClearingConfigItemFailed - } - return nil -} - -// ConfigKeys returns the names of the config items. -func (c *Container) ConfigKeys(key ...string) []string { - c.mu.RLock() - defer c.mu.RUnlock() - - var keys *_Ctype_char - - if key != nil && len(key) == 1 { - ckey := C.CString(key[0]) - defer C.free(unsafe.Pointer(ckey)) - - // allocated in lxc.c - keys = C.go_lxc_get_keys(c.container, ckey) - defer C.free(unsafe.Pointer(keys)) - } else { - // allocated in lxc.c - keys = C.go_lxc_get_keys(c.container, nil) - defer C.free(unsafe.Pointer(keys)) - } - ret := strings.TrimSpace(C.GoString(keys)) - return strings.Split(ret, "\n") -} - -// LoadConfigFile loads the configuration file from given path. -func (c *Container) LoadConfigFile(path string) error { - c.mu.Lock() - defer c.mu.Unlock() - - cpath := C.CString(path) - defer C.free(unsafe.Pointer(cpath)) - - if !bool(C.go_lxc_load_config(c.container, cpath)) { - return ErrLoadConfigFailed - } - return nil -} - -func (c *Container) saveConfigFile(path string) error { - cpath := C.CString(path) - defer C.free(unsafe.Pointer(cpath)) - - if !bool(C.go_lxc_save_config(c.container, cpath)) { - return ErrSaveConfigFailed - } - return nil -} - -// SaveConfigFile saves the configuration file to given path. -func (c *Container) SaveConfigFile(path string) error { - c.mu.Lock() - defer c.mu.Unlock() - - return c.saveConfigFile(path) -} - -func (c *Container) configPath() string { - return C.GoString(C.go_lxc_get_config_path(c.container)) -} - -// ConfigPath returns the configuration file's path. -func (c *Container) ConfigPath() string { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.configPath() -} - -// SetConfigPath sets the configuration file's path. -func (c *Container) SetConfigPath(path string) error { - c.mu.Lock() - defer c.mu.Unlock() - - cpath := C.CString(path) - defer C.free(unsafe.Pointer(cpath)) - - if !bool(C.go_lxc_set_config_path(c.container, cpath)) { - return ErrSettingConfigPathFailed - } - return nil -} - -// MemoryUsage returns memory usage of the container in bytes. -func (c *Container) MemoryUsage() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit) -} - -// MemoryLimit returns memory limit of the container in bytes. -func (c *Container) MemoryLimit() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit) -} - -// SetMemoryLimit sets memory limit of the container in bytes. -func (c *Container) SetMemoryLimit(limit ByteSize) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed) -} - -// SoftMemoryLimit returns soft memory limit of the container in bytes. -func (c *Container) SoftMemoryLimit() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit) -} - -// SetSoftMemoryLimit sets soft memory limit of the container in bytes. -func (c *Container) SetSoftMemoryLimit(limit ByteSize) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed) -} - -// KernelMemoryUsage returns current kernel memory allocation of the container in bytes. -func (c *Container) KernelMemoryUsage() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) -} - -// KernelMemoryLimit returns kernel memory limit of the container in bytes. -func (c *Container) KernelMemoryLimit() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.kmem.limit_in_bytes", ErrKMemLimit) -} - -// SetKernelMemoryLimit sets kernel memory limit of the container in bytes. -func (c *Container) SetKernelMemoryLimit(limit ByteSize) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed) -} - -// MemorySwapUsage returns memory+swap usage of the container in bytes. -func (c *Container) MemorySwapUsage() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit) -} - -// MemorySwapLimit returns the memory+swap limit of the container in bytes. -func (c *Container) MemorySwapLimit() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit) -} - -// SetMemorySwapLimit sets memory+swap limit of the container in bytes. -func (c *Container) SetMemorySwapLimit(limit ByteSize) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed) -} - -// BlkioUsage returns number of bytes transferred to/from the disk by the container. -func (c *Container) BlkioUsage() (ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - ioServiceBytes := c.cgroupItem("blkio.throttle.io_service_bytes") - if ioServiceBytes[0] == "" { - return 0, nil - } - - for _, v := range ioServiceBytes { - b := strings.Split(v, " ") - if b[0] == "Total" { - blkioUsed, err := strconv.ParseFloat(b[1], 64) - if err != nil { - return -1, err - } - return ByteSize(blkioUsed), nil - } - } - return -1, ErrBlkioUsage -} - -// CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks -// in this cgroup (including tasks lower in the hierarchy). -func (c *Container) CPUTime() (time.Duration, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - usage := c.cgroupItem("cpuacct.usage") - if usage[0] == "" { - return 0, nil - } - - cpuUsage, err := strconv.ParseInt(usage[0], 10, 64) - if err != nil { - return -1, err - } - return time.Duration(cpuUsage), nil -} - -// CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by -// all tasks in this cgroup (including tasks lower in the hierarchy). -func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - usagePerCPU := c.cgroupItem("cpuacct.usage_percpu") - if usagePerCPU[0] == "" { - return map[int]time.Duration{0: 0}, nil - } - - cpuTimes := make(map[int]time.Duration) - for i, v := range strings.Split(usagePerCPU[0], " ") { - cpuUsage, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return nil, err - } - cpuTimes[i] = time.Duration(cpuUsage) - } - return cpuTimes, nil -} - -// CPUStats returns the number of CPU cycles (in the units defined by USER_HZ on the system) -// consumed by tasks in this cgroup and its children in both user mode and system (kernel) mode. -func (c *Container) CPUStats() (map[string]int64, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - stat := c.cgroupItem("cpuacct.stat") - if stat[0] == "" { - return map[string]int64{"user": 0, "system": 0}, nil - } - - user, err := strconv.ParseInt(strings.Split(stat[0], "user ")[1], 10, 64) - if err != nil { - return nil, err - } - system, err := strconv.ParseInt(strings.Split(stat[1], "system ")[1], 10, 64) - if err != nil { - return nil, err - } - - return map[string]int64{"user": user, "system": system}, nil -} - -// ConsoleFd allocates a console tty from container -// ttynum: tty number to attempt to allocate or -1 to allocate the first available tty -// -// Returns "ttyfd" on success, -1 on failure. The returned "ttyfd" is -// used to keep the tty allocated. The caller should close "ttyfd" to -// indicate that it is done with the allocated console so that it can -// be allocated by another caller. -func (c *Container) ConsoleFd(ttynum int) (int, error) { - c.mu.Lock() - defer c.mu.Unlock() - - // FIXME: Make idiomatic - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - ret := int(C.go_lxc_console_getfd(c.container, C.int(ttynum))) - if ret < 0 { - return ret, ErrAttachFailed - } - return ret, nil -} - -// Console allocates and runs a console tty from container -// -// This function will not return until the console has been exited by the user. -func (c *Container) Console(options ConsoleOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - ret := bool(C.go_lxc_console(c.container, - C.int(options.Tty), - C.int(options.StdinFd), - C.int(options.StdoutFd), - C.int(options.StderrFd), - C.int(options.EscapeCharacter))) - - if !ret { - return ErrAttachFailed - } - return nil -} - -// AttachShell attaches a shell to the container. -// It clears all environment variables before attaching. -func (c *Container) AttachShell(options AttachOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning); err != nil { - return err - } - - cenv := makeNullTerminatedArgs(options.Env) - if cenv == nil { - return ErrAllocationFailed - } - defer freeNullTerminatedArgs(cenv, len(options.Env)) - - cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) - if cenvToKeep == nil { - return ErrAllocationFailed - } - defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) - - cwd := C.CString(options.Cwd) - defer C.free(unsafe.Pointer(cwd)) - - ret := int(C.go_lxc_attach(c.container, - C.bool(options.ClearEnv), - C.int(options.Namespaces), - C.long(options.Arch), - C.uid_t(options.UID), - C.gid_t(options.GID), - C.int(options.StdinFd), - C.int(options.StdoutFd), - C.int(options.StderrFd), - cwd, - cenv, - cenvToKeep, - )) - if ret < 0 { - return ErrAttachFailed - } - return nil -} - -func (c *Container) runCommandStatus(args []string, options AttachOptions) (int, error) { - if len(args) == 0 { - return -1, ErrInsufficientNumberOfArguments - } - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - cargs := makeNullTerminatedArgs(args) - if cargs == nil { - return -1, ErrAllocationFailed - } - defer freeNullTerminatedArgs(cargs, len(args)) - - cenv := makeNullTerminatedArgs(options.Env) - if cenv == nil { - return -1, ErrAllocationFailed - } - defer freeNullTerminatedArgs(cenv, len(options.Env)) - - cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) - if cenvToKeep == nil { - return -1, ErrAllocationFailed - } - defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) - - cwd := C.CString(options.Cwd) - defer C.free(unsafe.Pointer(cwd)) - - ret := int(C.go_lxc_attach_run_wait( - c.container, - C.bool(options.ClearEnv), - C.int(options.Namespaces), - C.long(options.Arch), - C.uid_t(options.UID), - C.gid_t(options.GID), - C.int(options.StdinFd), - C.int(options.StdoutFd), - C.int(options.StderrFd), - cwd, - cenv, - cenvToKeep, - cargs, - )) - - if ret < 0 { - return ret, nil - } - - // Mirror the behavior of WEXITSTATUS(). - return int((ret & 0xFF00) >> 8), nil -} - -// RunCommandStatus attachs a shell and runs the command within the container. -// The process will wait for the command to finish and return the result of -// waitpid(), i.e. the process' exit status. An error is returned only when -// invocation of the command completely fails. -func (c *Container) RunCommandStatus(args []string, options AttachOptions) (int, error) { - c.mu.Lock() - defer c.mu.Unlock() - - return c.runCommandStatus(args, options) -} - -// RunCommandNoWait runs the given command and returns without waiting it to finish. -func (c *Container) RunCommandNoWait(args []string, options AttachOptions) (int, error) { - c.mu.Lock() - defer c.mu.Unlock() - - if len(args) == 0 { - return -1, ErrInsufficientNumberOfArguments - } - - if err := c.makeSure(isRunning); err != nil { - return -1, err - } - - cargs := makeNullTerminatedArgs(args) - if cargs == nil { - return -1, ErrAllocationFailed - } - defer freeNullTerminatedArgs(cargs, len(args)) - - cenv := makeNullTerminatedArgs(options.Env) - if cenv == nil { - return -1, ErrAllocationFailed - } - defer freeNullTerminatedArgs(cenv, len(options.Env)) - - cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) - if cenvToKeep == nil { - return -1, ErrAllocationFailed - } - defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) - - cwd := C.CString(options.Cwd) - defer C.free(unsafe.Pointer(cwd)) - - var attachedPid C.pid_t - ret := int(C.go_lxc_attach_no_wait( - c.container, - C.bool(options.ClearEnv), - C.int(options.Namespaces), - C.long(options.Arch), - C.uid_t(options.UID), - C.gid_t(options.GID), - C.int(options.StdinFd), - C.int(options.StdoutFd), - C.int(options.StderrFd), - cwd, - cenv, - cenvToKeep, - cargs, - &attachedPid, - )) - - if ret < 0 { - return ret, ErrAttachFailed - } - - return int(attachedPid), nil -} - -// RunCommand attachs a shell and runs the command within the container. -// The process will wait for the command to finish and return a success status. An error -// is returned only when invocation of the command completely fails. -func (c *Container) RunCommand(args []string, options AttachOptions) (bool, error) { - c.mu.Lock() - defer c.mu.Unlock() - - ret, err := c.runCommandStatus(args, options) - if err != nil { - return false, err - } - if ret < 0 { - return false, ErrAttachFailed - } - return ret == 0, nil -} - -// Interfaces returns the names of the network interfaces. -func (c *Container) Interfaces() ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - result := C.go_lxc_get_interfaces(c.container) - if result == nil { - return nil, ErrInterfaces - } - return convertArgs(result), nil -} - -// InterfaceStats returns the stats about container's network interfaces -func (c *Container) InterfaceStats() (map[string]map[string]ByteSize, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - var interfaceName string - - statistics := make(map[string]map[string]ByteSize) - - netPrefix := "lxc.net" - if !VersionAtLeast(2, 1, 0) { - netPrefix = "lxc.network" - } - - for i := 0; i < len(c.configItem(netPrefix)); i++ { - interfaceType := c.runningConfigItem(fmt.Sprintf("%s.%d.type", netPrefix, i)) - if interfaceType == nil { - continue - } - - if interfaceType[0] == "veth" { - interfaceName = c.runningConfigItem(fmt.Sprintf("%s.%d.veth.pair", netPrefix, i))[0] - } else { - interfaceName = c.runningConfigItem(fmt.Sprintf("%s.%d.link", netPrefix, i))[0] - } - - for _, v := range []string{"rx", "tx"} { - /* tx and rx are reversed from the host vs container */ - content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/statistics/%s_bytes", interfaceName, v)) - if err != nil { - return nil, err - } - - bytes, err := strconv.ParseInt(strings.Split(string(content), "\n")[0], 10, 64) - if err != nil { - return nil, err - } - - if statistics[interfaceName] == nil { - statistics[interfaceName] = make(map[string]ByteSize) - } - statistics[interfaceName][v] = ByteSize(bytes) - } - } - - return statistics, nil -} - -// IPAddress returns the IP address of the given network interface. -func (c *Container) IPAddress(interfaceName string) ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - cinterface := C.CString(interfaceName) - defer C.free(unsafe.Pointer(cinterface)) - - result := C.go_lxc_get_ips(c.container, cinterface, nil, 0) - if result == nil { - return nil, ErrIPAddress - } - return convertArgs(result), nil -} - -// IPv4Address returns the IPv4 address of the given network interface. -func (c *Container) IPv4Address(interfaceName string) ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - cinterface := C.CString(interfaceName) - defer C.free(unsafe.Pointer(cinterface)) - - cfamily := C.CString("inet") - defer C.free(unsafe.Pointer(cfamily)) - - result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0) - if result == nil { - return nil, ErrIPv4Addresses - } - return convertArgs(result), nil -} - -// IPv6Address returns the IPv6 address of the given network interface. -func (c *Container) IPv6Address(interfaceName string) ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - cinterface := C.CString(interfaceName) - defer C.free(unsafe.Pointer(cinterface)) - - cfamily := C.CString("inet6") - defer C.free(unsafe.Pointer(cfamily)) - - result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0) - if result == nil { - return nil, ErrIPv6Addresses - } - return convertArgs(result), nil -} - -// WaitIPAddresses waits until IPAddresses call returns something or time outs -func (c *Container) WaitIPAddresses(timeout time.Duration) ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - now := time.Now() - for { - if result, err := c.ipAddresses(); err == nil && len(result) > 0 { - return result, nil - } - // Python API sleeps 1 second as well - time.Sleep(1 * time.Second) - - if time.Since(now) >= timeout { - return nil, ErrIPAddresses - } - } -} - -func (c *Container) ipAddresses() ([]string, error) { - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - result := C.go_lxc_get_ips(c.container, nil, nil, 0) - if result == nil { - return nil, ErrIPAddresses - } - return convertArgs(result), nil - -} - -// IPAddresses returns all IP addresses. -func (c *Container) IPAddresses() ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - return c.ipAddresses() -} - -// IPv4Addresses returns all IPv4 addresses. -func (c *Container) IPv4Addresses() ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - cfamily := C.CString("inet") - defer C.free(unsafe.Pointer(cfamily)) - - result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) - if result == nil { - return nil, ErrIPv4Addresses - } - return convertArgs(result), nil -} - -// IPv6Addresses returns all IPv6 addresses. -func (c *Container) IPv6Addresses() ([]string, error) { - c.mu.RLock() - defer c.mu.RUnlock() - - if err := c.makeSure(isRunning); err != nil { - return nil, err - } - - cfamily := C.CString("inet6") - defer C.free(unsafe.Pointer(cfamily)) - - result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) - if result == nil { - return nil, ErrIPv6Addresses - } - return convertArgs(result), nil -} - -// LogFile returns the name of the logfile. -func (c *Container) LogFile() string { - c.mu.RLock() - defer c.mu.RUnlock() - - if VersionAtLeast(2, 1, 0) { - return c.configItem("lxc.log.file")[0] - } - - return c.configItem("lxc.logfile")[0] -} - -// SetLogFile sets the name of the logfile. -func (c *Container) SetLogFile(filename string) error { - c.mu.Lock() - defer c.mu.Unlock() - - var err error - if VersionAtLeast(2, 1, 0) { - err = c.setConfigItem("lxc.log.file", filename) - } else { - err = c.setConfigItem("lxc.logfile", filename) - } - if err != nil { - return err - } - - return nil -} - -// LogLevel returns the level of the logfile. -func (c *Container) LogLevel() LogLevel { - c.mu.RLock() - defer c.mu.RUnlock() - - if VersionAtLeast(2, 1, 0) { - return logLevelMap[c.configItem("lxc.log.level")[0]] - } - - return logLevelMap[c.configItem("lxc.loglevel")[0]] -} - -// SetLogLevel sets the level of the logfile. -func (c *Container) SetLogLevel(level LogLevel) error { - c.mu.Lock() - defer c.mu.Unlock() - - var err error - if VersionAtLeast(2, 1, 0) { - err = c.setConfigItem("lxc.log.level", level.String()) - } else { - err = c.setConfigItem("lxc.loglevel", level.String()) - } - if err != nil { - return err - } - return nil -} - -// AddDeviceNode adds specified device to the container. -func (c *Container) AddDeviceNode(source string, destination ...string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning | isPrivileged); err != nil { - return err - } - - csource := C.CString(source) - defer C.free(unsafe.Pointer(csource)) - - if destination != nil && len(destination) == 1 { - cdestination := C.CString(destination[0]) - defer C.free(unsafe.Pointer(cdestination)) - - if !bool(C.go_lxc_add_device_node(c.container, csource, cdestination)) { - return ErrAddDeviceNodeFailed - } - return nil - } - - if !bool(C.go_lxc_add_device_node(c.container, csource, nil)) { - return ErrAddDeviceNodeFailed - } - return nil -} - -// RemoveDeviceNode removes the specified device from the container. -func (c *Container) RemoveDeviceNode(source string, destination ...string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning | isPrivileged); err != nil { - return err - } - - csource := C.CString(source) - defer C.free(unsafe.Pointer(csource)) - - if destination != nil && len(destination) == 1 { - cdestination := C.CString(destination[0]) - defer C.free(unsafe.Pointer(cdestination)) - - if !bool(C.go_lxc_remove_device_node(c.container, csource, cdestination)) { - return ErrRemoveDeviceNodeFailed - } - return nil - } - - if !bool(C.go_lxc_remove_device_node(c.container, csource, nil)) { - return ErrRemoveDeviceNodeFailed - } - return nil -} - -// Checkpoint checkpoints the container. -func (c *Container) Checkpoint(opts CheckpointOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning | isGreaterEqualThanLXC11); err != nil { - return err - } - - cdirectory := C.CString(opts.Directory) - defer C.free(unsafe.Pointer(cdirectory)) - - cstop := C.bool(opts.Stop) - cverbose := C.bool(opts.Verbose) - - if !C.go_lxc_checkpoint(c.container, cdirectory, cstop, cverbose) { - return ErrCheckpointFailed - } - return nil -} - -// Restore restores the container from a checkpoint. -func (c *Container) Restore(opts RestoreOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isGreaterEqualThanLXC11); err != nil { - return err - } - - cdirectory := C.CString(opts.Directory) - defer C.free(unsafe.Pointer(cdirectory)) - - cverbose := C.bool(opts.Verbose) - - if !C.bool(C.go_lxc_restore(c.container, cdirectory, cverbose)) { - return ErrRestoreFailed - } - return nil -} - -// Migrate migrates the container. -func (c *Container) Migrate(cmd uint, opts MigrateOptions) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isNotDefined | isGreaterEqualThanLXC20); err != nil { - return err - } - - if cmd != MIGRATE_RESTORE { - if err := c.makeSure(isRunning); err != nil { - return err - } - } - - cdirectory := C.CString(opts.Directory) - defer C.free(unsafe.Pointer(cdirectory)) - - var cpredumpdir *C.char - - if opts.PredumpDir != "" { - cpredumpdir = C.CString(opts.PredumpDir) - defer C.free(unsafe.Pointer(cpredumpdir)) - } - - /* Since we can't do conditional compilation here, we allocate the - * "extras" struct and then merge them in the C code. - */ - copts := C.struct_migrate_opts{ - directory: cdirectory, - verbose: C.bool(opts.Verbose), - stop: C.bool(opts.Stop), - predump_dir: cpredumpdir, - } - - var cActionScript *C.char - if opts.ActionScript != "" { - cActionScript = C.CString(opts.ActionScript) - defer C.free(unsafe.Pointer(cActionScript)) - } - - extras := C.struct_extra_migrate_opts{ - preserves_inodes: C.bool(opts.PreservesInodes), - action_script: cActionScript, - ghost_limit: C.uint64_t(opts.GhostLimit), - features_to_check: C.uint64_t(opts.FeaturesToCheck), - } - - ret := C.int(C.go_lxc_migrate(c.container, C.uint(cmd), &copts, &extras)) - if ret != 0 { - return fmt.Errorf("migration failed %d", ret) - } - - return nil -} - -// AttachInterface attaches specifed netdev to the container. -func (c *Container) AttachInterface(source, destination string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { - return err - } - - csource := C.CString(source) - defer C.free(unsafe.Pointer(csource)) - - cdestination := C.CString(destination) - defer C.free(unsafe.Pointer(cdestination)) - - if !bool(C.go_lxc_attach_interface(c.container, csource, cdestination)) { - return ErrAttachInterfaceFailed - } - return nil -} - -// DetachInterface detaches specifed netdev from the container. -func (c *Container) DetachInterface(source string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { - return err - } - - csource := C.CString(source) - defer C.free(unsafe.Pointer(csource)) - - if !bool(C.go_lxc_detach_interface(c.container, csource, nil)) { - return ErrDetachInterfaceFailed - } - return nil -} - -// DetachInterfaceRename detaches specifed netdev from the container and renames it. -func (c *Container) DetachInterfaceRename(source, target string) error { - c.mu.Lock() - defer c.mu.Unlock() - - if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { - return err - } - - csource := C.CString(source) - defer C.free(unsafe.Pointer(csource)) - - ctarget := C.CString(target) - defer C.free(unsafe.Pointer(ctarget)) - - if !bool(C.go_lxc_detach_interface(c.container, csource, ctarget)) { - return ErrDetachInterfaceFailed - } - return nil -} - -// ConsoleLog allows to perform operations on the container's in-memory console -// buffer. -func (c *Container) ConsoleLog(opt ConsoleLogOptions) ([]byte, error) { - c.mu.Lock() - defer c.mu.Unlock() - - cl := C.struct_lxc_console_log{ - clear: C.bool(opt.ClearLog), - read: C.bool(opt.ReadLog), - data: nil, - } - // CGO is a fickle little beast: - // We need to manually allocate memory here that we pass to C. If we - // were to pass a GO pointer by passing a C.uint64_t pointer we'd end in - // the situation where we have a GO pointer that points to a GO pointer. - // Go will freak out when this happens. So give C its own memory. - var buf unsafe.Pointer - buf = C.malloc(C.sizeof_uint64_t) - if buf == nil { - return nil, syscall.ENOMEM - } - defer C.free(buf) - - cl.read_max = (*C.uint64_t)(buf) - *cl.read_max = C.uint64_t(opt.ReadMax) - - ret := C.go_lxc_console_log(c.container, &cl) - if ret < 0 { - return nil, syscall.Errno(-ret) - } - - numBytes := C.int(*cl.read_max) - if C.uint64_t(numBytes) != *cl.read_max { - return nil, syscall.ERANGE - } - - return C.GoBytes(unsafe.Pointer(cl.data), numBytes), nil -} - -// ErrorNum returns the error_num field of the container. -func (c *Container) ErrorNum() int { - cError := C.go_lxc_error_num(c.container) - return int(cError) -} diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/doc.go b/vendor/gopkg.in/lxc/go-lxc.v2/doc.go deleted file mode 100644 index 68c41437a..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -/* -Package lxc provides Go Bindings for LXC (Linux Containers) C API. - -LXC (LinuX Containers) is an operating system–level virtualization method for running multiple isolated Linux systems (containers) on a single control host. - -LXC combines cgroups and namespace support to provide an isolated environment for applications. -*/ -package lxc diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/error.go b/vendor/gopkg.in/lxc/go-lxc.v2/error.go deleted file mode 100644 index b89d90352..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/error.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -package lxc - -var ( - ErrAddDeviceNodeFailed = NewError("adding device to container failed") - ErrAllocationFailed = NewError("allocating memory failed") - ErrAlreadyDefined = NewError("container already defined") - ErrAlreadyFrozen = NewError("container is already frozen") - ErrAlreadyRunning = NewError("container is already running") - ErrAttachFailed = NewError("attaching to the container failed") - ErrAttachInterfaceFailed = NewError("attaching specified netdev to the container failed") - ErrBlkioUsage = NewError("BlkioUsage for the container failed") - ErrCheckpointFailed = NewError("checkpoint failed") - ErrClearingConfigItemFailed = NewError("clearing config item for the container failed") - ErrClearingCgroupItemFailed = NewError("clearing cgroup item for the container failed") - ErrCloneFailed = NewError("cloning the container failed") - ErrCloseAllFdsFailed = NewError("setting close_all_fds flag for container failed") - ErrCreateFailed = NewError("creating the container failed") - ErrCreateSnapshotFailed = NewError("snapshotting the container failed") - ErrDaemonizeFailed = NewError("setting daemonize flag for container failed") - ErrDestroyAllSnapshotsFailed = NewError("destroying all snapshots failed") - ErrDestroyFailed = NewError("destroying the container failed") - ErrDestroySnapshotFailed = NewError("destroying the snapshot failed") - ErrDestroyWithAllSnapshotsFailed = NewError("destroying the container with all snapshots failed") - ErrDetachInterfaceFailed = NewError("detaching specified netdev to the container failed") - ErrExecuteFailed = NewError("executing the command in a temporary container failed") - ErrFreezeFailed = NewError("freezing the container failed") - ErrInsufficientNumberOfArguments = NewError("insufficient number of arguments were supplied") - ErrInterfaces = NewError("getting interface names for the container failed") - ErrIPAddresses = NewError("getting IP addresses of the container failed") - ErrIPAddress = NewError("getting IP address on the interface of the container failed") - ErrIPv4Addresses = NewError("getting IPv4 addresses of the container failed") - ErrIPv6Addresses = NewError("getting IPv6 addresses of the container failed") - ErrKMemLimit = NewError("your kernel does not support cgroup kernel memory controller") - ErrLoadConfigFailed = NewError("loading config file for the container failed") - ErrMemLimit = NewError("your kernel does not support cgroup memory controller") - ErrMemorySwapLimit = NewError("your kernel does not support cgroup swap controller") - ErrMethodNotAllowed = NewError("the requested method is not currently supported with unprivileged containers") - ErrNewFailed = NewError("allocating the container failed") - ErrNoSnapshot = NewError("container has no snapshot") - ErrNotDefined = NewError("container is not defined") - ErrNotFrozen = NewError("container is not frozen") - ErrNotRunning = NewError("container is not running") - ErrNotSupported = NewError("method is not supported by this LXC version") - ErrRebootFailed = NewError("rebooting the container failed") - ErrRemoveDeviceNodeFailed = NewError("removing device from container failed") - ErrRenameFailed = NewError("renaming the container failed") - ErrRestoreFailed = NewError("restore failed") - ErrRestoreSnapshotFailed = NewError("restoring the container failed") - ErrSaveConfigFailed = NewError("saving config file for the container failed") - ErrSettingCgroupItemFailed = NewError("setting cgroup item for the container failed") - ErrSettingConfigItemFailed = NewError("setting config item for the container failed") - ErrSettingConfigPathFailed = NewError("setting config file for the container failed") - ErrSettingKMemoryLimitFailed = NewError("setting kernel memory limit for the container failed") - ErrSettingMemoryLimitFailed = NewError("setting memory limit for the container failed") - ErrSettingMemorySwapLimitFailed = NewError("setting memory+swap limit for the container failed") - ErrSettingSoftMemoryLimitFailed = NewError("setting soft memory limit for the container failed") - ErrShutdownFailed = NewError("shutting down the container failed") - ErrSoftMemLimit = NewError("your kernel does not support cgroup memory controller") - ErrStartFailed = NewError("starting the container failed") - ErrStopFailed = NewError("stopping the container failed") - ErrTemplateNotAllowed = NewError("unprivileged users only allowed to use \"download\" template") - ErrUnfreezeFailed = NewError("unfreezing the container failed") - ErrUnknownBackendStore = NewError("unknown backend type") -) - -// Error represents a basic error that implies the error interface. -type Error struct { - Message string -} - -// NewError creates a new error with the given msg argument. -func NewError(msg string) error { - return &Error{ - Message: msg, - } -} - -func (e *Error) Error() string { - return e.Message -} diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.c b/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.c deleted file mode 100644 index 7e408c0ed..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.c +++ /dev/null @@ -1,503 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -#include -#include -#include -#include - -#include -#include -#include - -#include "lxc-binding.h" - -#ifndef LXC_DEVEL -#define LXC_DEVEL 0 -#endif - -bool go_lxc_defined(struct lxc_container *c) { - return c->is_defined(c); -} - -const char* go_lxc_state(struct lxc_container *c) { - return c->state(c); -} - -bool go_lxc_running(struct lxc_container *c) { - return c->is_running(c); -} - -bool go_lxc_freeze(struct lxc_container *c) { - return c->freeze(c); -} - -bool go_lxc_unfreeze(struct lxc_container *c) { - return c->unfreeze(c); -} - -pid_t go_lxc_init_pid(struct lxc_container *c) { - return c->init_pid(c); -} - -bool go_lxc_want_daemonize(struct lxc_container *c, bool state) { - return c->want_daemonize(c, state); -} - -bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state) { - return c->want_close_all_fds(c, state); -} - -bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]) { - return c->create(c, t, bdevtype, NULL, !!(flags & LXC_CREATE_QUIET), argv); -} - -bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]) { - return c->start(c, useinit, argv); -} - -bool go_lxc_stop(struct lxc_container *c) { - return c->stop(c); -} - -bool go_lxc_reboot(struct lxc_container *c) { - return c->reboot(c); -} - -bool go_lxc_shutdown(struct lxc_container *c, int timeout) { - return c->shutdown(c, timeout); -} - -char* go_lxc_config_file_name(struct lxc_container *c) { - return c->config_file_name(c); -} - -bool go_lxc_destroy(struct lxc_container *c) { - return c->destroy(c); -} - -bool go_lxc_destroy_with_snapshots(struct lxc_container *c) { -#if VERSION_AT_LEAST(1, 1, 0) - return c->destroy_with_snapshots(c); -#else - return false; -#endif -} - -bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout) { - return c->wait(c, state, timeout); -} - -char *go_lxc_get_config_item(struct lxc_container *c, const char *key) -{ - char *value = NULL; - - int len = c->get_config_item(c, key, NULL, 0); - if (len <= 0) - return NULL; - -again: - value = (char *)malloc(sizeof(char) * len + 1); - if (value == NULL) - goto again; - - if (c->get_config_item(c, key, value, len + 1) != len) { - free(value); - return NULL; - } - - return value; -} - -bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value) { - return c->set_config_item(c, key, value); -} - -void go_lxc_clear_config(struct lxc_container *c) { - c->clear_config(c); -} - -bool go_lxc_clear_config_item(struct lxc_container *c, const char *key) { - return c->clear_config_item(c, key); -} - -char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key) { - return c->get_running_config_item(c, key); -} - -char *go_lxc_get_keys(struct lxc_container *c, const char *key) -{ - char *value = NULL; - - int len = c->get_keys(c, key, NULL, 0); - if (len <= 0) - return NULL; - -again: - value = (char *)malloc(sizeof(char) * len + 1); - if (value == NULL) - goto again; - - if (c->get_keys(c, key, value, len + 1) != len) { - free(value); - return NULL; - } - - return value; -} - -char *go_lxc_get_cgroup_item(struct lxc_container *c, const char *key) -{ - char *value = NULL; - - int len = c->get_cgroup_item(c, key, NULL, 0); - if (len <= 0) - return NULL; - -again: - value = (char *)malloc(sizeof(char) * len + 1); - if (value == NULL) - goto again; - - if (c->get_cgroup_item(c, key, value, len + 1) != len) { - free(value); - return NULL; - } - - return value; -} - -bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value) { - return c->set_cgroup_item(c, key, value); -} - -const char* go_lxc_get_config_path(struct lxc_container *c) { - return c->get_config_path(c); -} - -bool go_lxc_set_config_path(struct lxc_container *c, const char *path) { - return c->set_config_path(c, path); -} - -bool go_lxc_load_config(struct lxc_container *c, const char *alt_file) { - return c->load_config(c, alt_file); -} - -bool go_lxc_save_config(struct lxc_container *c, const char *alt_file) { - return c->save_config(c, alt_file); -} - -bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype) { - return c->clone(c, newname, lxcpath, flags, bdevtype, NULL, 0, NULL) != NULL; -} - -int go_lxc_console_getfd(struct lxc_container *c, int ttynum) { - int masterfd; - int ret = 0; - - ret = c->console_getfd(c, &ttynum, &masterfd); - if (ret < 0) - return ret; - - return masterfd; -} - -bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape) { - - if (c->console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape) == 0) { - return true; - } - return false; -} - -char** go_lxc_get_interfaces(struct lxc_container *c) { - return c->get_interfaces(c); -} - -char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope) { - return c->get_ips(c, interface, family, scope); -} - -int wait_for_pid_status(pid_t pid) -{ - int status, ret; - -again: - ret = waitpid(pid, &status, 0); - if (ret == -1) { - if (errno == EINTR) - goto again; - return -1; - } - if (ret != pid) - goto again; - return status; -} - -int go_lxc_attach_no_wait(struct lxc_container *c, - bool clear_env, - int namespaces, - long personality, - uid_t uid, gid_t gid, - int stdinfd, int stdoutfd, int stderrfd, - char *initial_cwd, - char **extra_env_vars, - char **extra_keep_env, - const char * const argv[], - pid_t *attached_pid) { - int ret; - - lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; - lxc_attach_command_t command = (lxc_attach_command_t){.program = NULL}; - - attach_options.env_policy = LXC_ATTACH_KEEP_ENV; - if (clear_env) { - attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; - } - - attach_options.namespaces = namespaces; - attach_options.personality = personality; - - attach_options.uid = uid; - attach_options.gid = gid; - - attach_options.stdin_fd = stdinfd; - attach_options.stdout_fd = stdoutfd; - attach_options.stderr_fd = stderrfd; - - attach_options.initial_cwd = initial_cwd; - attach_options.extra_env_vars = extra_env_vars; - attach_options.extra_keep_env = extra_keep_env; - - command.program = (char *)argv[0]; - command.argv = (char **)argv; - - ret = c->attach(c, lxc_attach_run_command, &command, &attach_options, attached_pid); - if (ret < 0) - return ret; - - return 0; -} - -int go_lxc_attach(struct lxc_container *c, - bool clear_env, - int namespaces, - long personality, - uid_t uid, gid_t gid, - int stdinfd, int stdoutfd, int stderrfd, - char *initial_cwd, - char **extra_env_vars, - char **extra_keep_env) { - int ret; - pid_t pid; - - lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; - - attach_options.env_policy = LXC_ATTACH_KEEP_ENV; - if (clear_env) { - attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; - } - - attach_options.namespaces = namespaces; - attach_options.personality = personality; - - attach_options.uid = uid; - attach_options.gid = gid; - - attach_options.stdin_fd = stdinfd; - attach_options.stdout_fd = stdoutfd; - attach_options.stderr_fd = stderrfd; - - attach_options.initial_cwd = initial_cwd; - attach_options.extra_env_vars = extra_env_vars; - attach_options.extra_keep_env = extra_keep_env; - - /* - remount_sys_proc - When using -s and the mount namespace is not included, this flag will cause lxc-attach to remount /proc and /sys to reflect the current other namespace contexts. - default_options.attach_flags |= LXC_ATTACH_REMOUNT_PROC_SYS; - - elevated_privileges - Do not drop privileges when running command inside the container. If this option is specified, the new process will not be added to the container's cgroup(s) and it will not drop its capabilities before executing. - default_options.attach_flags &= ~(LXC_ATTACH_MOVE_TO_CGROUP | LXC_ATTACH_DROP_CAPABILITIES | LXC_ATTACH_APPARMOR); - */ - - ret = c->attach(c, lxc_attach_run_shell, NULL, &attach_options, &pid); - if (ret < 0) - return ret; - - ret = wait_for_pid_status(pid); - if (ret < 0) - return ret; - - if (WIFEXITED(ret)) - return WEXITSTATUS(ret); - - return ret; -} - -int go_lxc_attach_run_wait(struct lxc_container *c, - bool clear_env, - int namespaces, - long personality, - uid_t uid, gid_t gid, - int stdinfd, int stdoutfd, int stderrfd, - char *initial_cwd, - char **extra_env_vars, - char **extra_keep_env, - const char * const argv[]) { - int ret; - - lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; - - attach_options.env_policy = LXC_ATTACH_KEEP_ENV; - if (clear_env) { - attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; - } - - attach_options.namespaces = namespaces; - attach_options.personality = personality; - - attach_options.uid = uid; - attach_options.gid = gid; - - attach_options.stdin_fd = stdinfd; - attach_options.stdout_fd = stdoutfd; - attach_options.stderr_fd = stderrfd; - - attach_options.initial_cwd = initial_cwd; - attach_options.extra_env_vars = extra_env_vars; - attach_options.extra_keep_env = extra_keep_env; - - ret = c->attach_run_wait(c, &attach_options, argv[0], argv); - if (WIFEXITED(ret) && WEXITSTATUS(ret) == 255) - return -1; - return ret; -} - -bool go_lxc_may_control(struct lxc_container *c) { - return c->may_control(c); -} - -int go_lxc_snapshot(struct lxc_container *c) { - return c->snapshot(c, NULL); -} - -int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret) { - return c->snapshot_list(c, ret); -} - -bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname) { - return c->snapshot_restore(c, snapname, newname); -} - -bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname) { - return c->snapshot_destroy(c, snapname); -} - -bool go_lxc_snapshot_destroy_all(struct lxc_container *c) { -#if VERSION_AT_LEAST(1, 1, 0) - return c->snapshot_destroy_all(c); -#else - return false; -#endif - -} - -bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { - return c->add_device_node(c, src_path, dest_path); -} - -bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { - return c->remove_device_node(c, src_path, dest_path); -} - -bool go_lxc_rename(struct lxc_container *c, const char *newname) { - return c->rename(c, newname); -} - -bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose) { -#if VERSION_AT_LEAST(1, 1, 0) - return c->checkpoint(c, directory, stop, verbose); -#else - return false; -#endif -} - -bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose) { -#if VERSION_AT_LEAST(1, 1, 0) - return c->restore(c, directory, verbose); -#else - return false; -#endif -} - -int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras) { -#if VERSION_AT_LEAST(3, 0, 0) - opts->features_to_check = extras->features_to_check; -#endif -#if VERSION_AT_LEAST(2, 0, 4) - opts->action_script = extras->action_script; - opts->ghost_limit = extras->ghost_limit; -#endif - -#if VERSION_AT_LEAST(2, 0, 1) - opts->preserves_inodes = extras->preserves_inodes; -#endif - -#if VERSION_AT_LEAST(2, 0, 0) - return c->migrate(c, cmd, opts, sizeof(*opts)); -#else - return -EINVAL; -#endif -} - -bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { -#if VERSION_AT_LEAST(1, 1, 0) - return c->attach_interface(c, dev, dst_dev); -#else - return false; -#endif -} - -bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { -#if VERSION_AT_LEAST(1, 1, 0) - return c->detach_interface(c, dev, dst_dev); -#else - return false; -#endif -} - -bool go_lxc_config_item_is_supported(const char *key) -{ -#if VERSION_AT_LEAST(2, 1, 0) - return lxc_config_item_is_supported(key); -#else - return false; -#endif -} - -int go_lxc_error_num(struct lxc_container *c) -{ - return c->error_num; -} - -int go_lxc_console_log(struct lxc_container *c, struct lxc_console_log *log) { -#if VERSION_AT_LEAST(3, 0, 0) - return c->console_log(c, log); -#else - return false; -#endif -} - -bool go_lxc_has_api_extension(const char *extension) -{ -#if VERSION_AT_LEAST(3, 1, 0) - return lxc_has_api_extension(extension); -#else - return false; -#endif -} diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.go b/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.go deleted file mode 100644 index 3cd38d618..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -package lxc - -// #cgo pkg-config: lxc -// #cgo LDFLAGS: -llxc -lutil -// #include -// #include -// #include "lxc-binding.h" -// #ifndef LXC_DEVEL -// #define LXC_DEVEL 0 -// #endif -import "C" - -import ( - "fmt" - "runtime" - "strconv" - "strings" - "unsafe" -) - -// NewContainer returns a new container struct. -func NewContainer(name string, lxcpath ...string) (*Container, error) { - var container *C.struct_lxc_container - - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - - if lxcpath != nil && len(lxcpath) == 1 { - clxcpath := C.CString(lxcpath[0]) - defer C.free(unsafe.Pointer(clxcpath)) - - container = C.lxc_container_new(cname, clxcpath) - } else { - container = C.lxc_container_new(cname, nil) - } - - if container == nil { - return nil, ErrNewFailed - } - c := &Container{container: container, verbosity: Quiet} - - // http://golang.org/pkg/runtime/#SetFinalizer - runtime.SetFinalizer(c, Release) - return c, nil -} - -// Acquire increments the reference counter of the container object. -func Acquire(c *Container) bool { - return C.lxc_container_get(c.container) == 1 -} - -// Release decrements the reference counter of the container object. -func Release(c *Container) bool { - // http://golang.org/pkg/runtime/#SetFinalizer - runtime.SetFinalizer(c, nil) - - // Go is bad at refcounting sometimes - c.mu.Lock() - - return C.lxc_container_put(c.container) == 1 -} - -// Version returns the LXC version. -func Version() string { - version := C.GoString(C.lxc_get_version()) - - // New liblxc versions append "-devel" when LXC_DEVEL is set. - if strings.HasSuffix(version, "-devel") { - return fmt.Sprintf("%s (devel)", version[:(len(version)-len("-devel"))]) - } - - return version -} - -// GlobalConfigItem returns the value of the given global config key. -func GlobalConfigItem(name string) string { - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - - return C.GoString(C.lxc_get_global_config_item(cname)) -} - -// DefaultConfigPath returns default config path. -func DefaultConfigPath() string { - return GlobalConfigItem("lxc.lxcpath") -} - -// DefaultLvmVg returns the name of the default LVM volume group. -func DefaultLvmVg() string { - return GlobalConfigItem("lxc.bdev.lvm.vg") -} - -// DefaultZfsRoot returns the name of the default ZFS root. -func DefaultZfsRoot() string { - return GlobalConfigItem("lxc.bdev.zfs.root") -} - -// ContainerNames returns the names of defined and active containers on the system. -func ContainerNames(lxcpath ...string) []string { - var size int - var cnames **C.char - - if lxcpath != nil && len(lxcpath) == 1 { - clxcpath := C.CString(lxcpath[0]) - defer C.free(unsafe.Pointer(clxcpath)) - - size = int(C.list_all_containers(clxcpath, &cnames, nil)) - } else { - - size = int(C.list_all_containers(nil, &cnames, nil)) - } - - if size < 1 { - return nil - } - return convertNArgs(cnames, size) -} - -// Containers returns the defined and active containers on the system. Only -// containers that could retrieved successfully are returned. -func Containers(lxcpath ...string) []*Container { - var containers []*Container - - for _, v := range ContainerNames(lxcpath...) { - if container, err := NewContainer(v, lxcpath...); err == nil { - containers = append(containers, container) - } - } - - return containers -} - -// DefinedContainerNames returns the names of the defined containers on the system. -func DefinedContainerNames(lxcpath ...string) []string { - var size int - var cnames **C.char - - if lxcpath != nil && len(lxcpath) == 1 { - clxcpath := C.CString(lxcpath[0]) - defer C.free(unsafe.Pointer(clxcpath)) - - size = int(C.list_defined_containers(clxcpath, &cnames, nil)) - } else { - - size = int(C.list_defined_containers(nil, &cnames, nil)) - } - - if size < 1 { - return nil - } - return convertNArgs(cnames, size) -} - -// DefinedContainers returns the defined containers on the system. Only -// containers that could retrieved successfully are returned. -func DefinedContainers(lxcpath ...string) []*Container { - var containers []*Container - - for _, v := range DefinedContainerNames(lxcpath...) { - if container, err := NewContainer(v, lxcpath...); err == nil { - containers = append(containers, container) - } - } - - return containers -} - -// ActiveContainerNames returns the names of the active containers on the system. -func ActiveContainerNames(lxcpath ...string) []string { - var size int - var cnames **C.char - - if lxcpath != nil && len(lxcpath) == 1 { - clxcpath := C.CString(lxcpath[0]) - defer C.free(unsafe.Pointer(clxcpath)) - - size = int(C.list_active_containers(clxcpath, &cnames, nil)) - } else { - - size = int(C.list_active_containers(nil, &cnames, nil)) - } - - if size < 1 { - return nil - } - return convertNArgs(cnames, size) -} - -// ActiveContainers returns the active containers on the system. Only -// containers that could retrieved successfully are returned. -func ActiveContainers(lxcpath ...string) []*Container { - var containers []*Container - - for _, v := range ActiveContainerNames(lxcpath...) { - if container, err := NewContainer(v, lxcpath...); err == nil { - containers = append(containers, container) - } - } - - return containers -} - -// VersionNumber returns the LXC version. -func VersionNumber() (major int, minor int) { - major = C.LXC_VERSION_MAJOR - minor = C.LXC_VERSION_MINOR - - return -} - -// VersionAtLeast returns true when the tested version >= current version. -func VersionAtLeast(major int, minor int, micro int) bool { - if C.LXC_DEVEL == 1 { - return true - } - - if major > C.LXC_VERSION_MAJOR { - return false - } - - if major == C.LXC_VERSION_MAJOR && - minor > C.LXC_VERSION_MINOR { - return false - } - - if major == C.LXC_VERSION_MAJOR && - minor == C.LXC_VERSION_MINOR && - micro > C.LXC_VERSION_MICRO { - return false - } - - return true -} - -// IsSupportedConfigItem returns true if the key belongs to a supported config item. -func IsSupportedConfigItem(key string) bool { - configItem := C.CString(key) - defer C.free(unsafe.Pointer(configItem)) - return bool(C.go_lxc_config_item_is_supported(configItem)) -} - -// runtimeLiblxcVersionAtLeast checks if the system's liblxc matches the -// provided version requirement -func runtimeLiblxcVersionAtLeast(major int, minor int, micro int) bool { - version := Version() - version = strings.Replace(version, " (devel)", "-devel", 1) - parts := strings.Split(version, ".") - partsLen := len(parts) - if partsLen == 0 { - return false - } - - develParts := strings.Split(parts[partsLen-1], "-") - if len(develParts) == 2 && develParts[1] == "devel" { - return true - } - - maj := -1 - min := -1 - mic := -1 - - for i, v := range parts { - if i > 2 { - break - } - - num, err := strconv.Atoi(v) - if err != nil { - return false - } - - switch i { - case 0: - maj = num - case 1: - min = num - case 2: - mic = num - } - } - - /* Major version is greater. */ - if maj > major { - return true - } - - if maj < major { - return false - } - - /* Minor number is greater.*/ - if min > minor { - return true - } - - if min < minor { - return false - } - - /* Patch number is greater. */ - if mic > micro { - return true - } - - if mic < micro { - return false - } - - return true -} - -// HasApiExtension returns true if the extension is supported. -func HasApiExtension(extension string) bool { - if runtimeLiblxcVersionAtLeast(3, 1, 0) { - apiExtension := C.CString(extension) - defer C.free(unsafe.Pointer(apiExtension)) - return bool(C.go_lxc_has_api_extension(apiExtension)) - } - return false -} diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.h b/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.h deleted file mode 100644 index da2cb961a..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/lxc-binding.h +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -#define VERSION_AT_LEAST(major, minor, micro) \ - ((LXC_DEVEL == 1) || (!(major > LXC_VERSION_MAJOR || \ - major == LXC_VERSION_MAJOR && minor > LXC_VERSION_MINOR || \ - major == LXC_VERSION_MAJOR && minor == LXC_VERSION_MINOR && micro > LXC_VERSION_MICRO))) - -extern bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); -extern void go_lxc_clear_config(struct lxc_container *c); -extern bool go_lxc_clear_config_item(struct lxc_container *c, const char *key); -extern bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype); -extern bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape); -extern bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]); -extern bool go_lxc_defined(struct lxc_container *c); -extern bool go_lxc_destroy(struct lxc_container *c); -extern bool go_lxc_destroy_with_snapshots(struct lxc_container *c); -extern bool go_lxc_freeze(struct lxc_container *c); -extern bool go_lxc_load_config(struct lxc_container *c, const char *alt_file); -extern bool go_lxc_may_control(struct lxc_container *c); -extern bool go_lxc_reboot(struct lxc_container *c); -extern bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); -extern bool go_lxc_rename(struct lxc_container *c, const char *newname); -extern bool go_lxc_running(struct lxc_container *c); -extern bool go_lxc_save_config(struct lxc_container *c, const char *alt_file); -extern bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value); -extern bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value); -extern bool go_lxc_set_config_path(struct lxc_container *c, const char *path); -extern bool go_lxc_shutdown(struct lxc_container *c, int timeout); -extern bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname); -extern bool go_lxc_snapshot_destroy_all(struct lxc_container *c); -extern bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname); -extern bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]); -extern bool go_lxc_stop(struct lxc_container *c); -extern bool go_lxc_unfreeze(struct lxc_container *c); -extern bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout); -extern bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state); -extern bool go_lxc_want_daemonize(struct lxc_container *c, bool state); -extern char* go_lxc_config_file_name(struct lxc_container *c); -extern char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key); -extern char* go_lxc_get_config_item(struct lxc_container *c, const char *key); -extern char** go_lxc_get_interfaces(struct lxc_container *c); -extern char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope); -extern char* go_lxc_get_keys(struct lxc_container *c, const char *key); -extern char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key); -extern const char* go_lxc_get_config_path(struct lxc_container *c); -extern const char* go_lxc_state(struct lxc_container *c); -extern int go_lxc_attach_run_wait(struct lxc_container *c, - bool clear_env, - int namespaces, - long personality, - uid_t uid, gid_t gid, - int stdinfd, int stdoutfd, int stderrfd, - char *initial_cwd, - char **extra_env_vars, - char **extra_keep_env, - const char * const argv[]); -extern int go_lxc_attach(struct lxc_container *c, - bool clear_env, - int namespaces, - long personality, - uid_t uid, gid_t gid, - int stdinfd, int stdoutfd, int stderrfd, - char *initial_cwd, - char **extra_env_vars, - char **extra_keep_env); -extern int go_lxc_attach_no_wait(struct lxc_container *c, - bool clear_env, - int namespaces, - long personality, - uid_t uid, gid_t gid, - int stdinfd, int stdoutfd, int stderrfd, - char *initial_cwd, - char **extra_env_vars, - char **extra_keep_env, - const char * const argv[], - pid_t *attached_pid); -extern int go_lxc_console_getfd(struct lxc_container *c, int ttynum); -extern int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret); -extern int go_lxc_snapshot(struct lxc_container *c); -extern pid_t go_lxc_init_pid(struct lxc_container *c); -extern bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose); -extern bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose); -extern bool go_lxc_config_item_is_supported(const char *key); -extern bool go_lxc_has_api_extension(const char *extension); - -/* n.b. that we're just adding the fields here to shorten the definition - * of go_lxc_migrate; in the case where we don't have the ->migrate API call, - * we don't want to have to pass all the arguments in to let conditional - * compilation handle things, but the call will still fail - */ -#if !VERSION_AT_LEAST(2, 0, 0) -struct migrate_opts { - char *directory; - bool verbose; - bool stop; - char *predump_dir; -}; -#endif - -/* This is a struct that we can add "extra" (i.e. options added after 2.0.0) - * migrate options to, so that we don't have to have a massive function - * signature when the list of options grows. - */ -struct extra_migrate_opts { - bool preserves_inodes; - char *action_script; - uint64_t ghost_limit; - uint64_t features_to_check; -}; -int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras); - -extern bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); -extern bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); - -#if !VERSION_AT_LEAST(3, 0, 0) -struct lxc_console_log { - bool clear; - bool read; - uint64_t *read_max; - char *data; -}; -#endif - -extern int go_lxc_console_log(struct lxc_container *c, struct lxc_console_log *log); -extern int go_lxc_error_num(struct lxc_container *c); diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/options.go b/vendor/gopkg.in/lxc/go-lxc.v2/options.go deleted file mode 100644 index 23d1bc071..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/options.go +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -package lxc - -import ( - "os" -) - -// AttachOptions type is used for defining various attach options. -type AttachOptions struct { - - // Specify the namespaces to attach to, as OR'ed list of clone flags (syscall.CLONE_NEWNS | syscall.CLONE_NEWUTS ...). - Namespaces int - - // Specify the architecture which the kernel should appear to be running as to the command executed. - Arch Personality - - // Cwd specifies the working directory of the command. - Cwd string - - // UID specifies the user id to run as. - UID int - - // GID specifies the group id to run as. - GID int - - // If ClearEnv is true the environment is cleared before running the command. - ClearEnv bool - - // Env specifies the environment of the process. - Env []string - - // EnvToKeep specifies the environment of the process when ClearEnv is true. - EnvToKeep []string - - // StdinFd specifies the fd to read input from. - StdinFd uintptr - - // StdoutFd specifies the fd to write output to. - StdoutFd uintptr - - // StderrFd specifies the fd to write error output to. - StderrFd uintptr -} - -// DefaultAttachOptions is a convenient set of options to be used. -var DefaultAttachOptions = AttachOptions{ - Namespaces: -1, - Arch: -1, - Cwd: "/", - UID: -1, - GID: -1, - ClearEnv: false, - Env: nil, - EnvToKeep: nil, - StdinFd: os.Stdin.Fd(), - StdoutFd: os.Stdout.Fd(), - StderrFd: os.Stderr.Fd(), -} - -// TemplateOptions type is used for defining various template options. -type TemplateOptions struct { - - // Template specifies the name of the template. - Template string - - // Backend specifies the type of the backend. - Backend BackendStore - - // Distro specifies the name of the distribution. - Distro string - - // Release specifies the name/version of the distribution. - Release string - - // Arch specified the architecture of the container. - Arch string - - // Variant specifies the variant of the image (default: "default"). - Variant string - - // Image server (default: "images.linuxcontainers.org"). - Server string - - // GPG keyid (default: 0x...). - KeyID string - - // GPG keyserver to use. - KeyServer string - - // Disable GPG validation (not recommended). - DisableGPGValidation bool - - // Flush the local copy (if present). - FlushCache bool - - // Force the use of the local copy even if expired. - ForceCache bool - - // ExtraArgs provides a way to specify template specific args. - ExtraArgs []string -} - -// DownloadTemplateOptions is a convenient set of options for "download" template. -var DownloadTemplateOptions = TemplateOptions{ - Template: "download", - Distro: "ubuntu", - Release: "trusty", - Arch: "amd64", -} - -// BusyboxTemplateOptions is a convenient set of options for "busybox" template. -var BusyboxTemplateOptions = TemplateOptions{ - Template: "busybox", -} - -// UbuntuTemplateOptions is a convenient set of options for "ubuntu" template. -var UbuntuTemplateOptions = TemplateOptions{ - Template: "ubuntu", -} - -// ConsoleOptions type is used for defining various console options. -type ConsoleOptions struct { - - // Tty number to attempt to allocate, -1 to allocate the first available tty, or 0 to allocate the console. - Tty int - - // StdinFd specifies the fd to read input from. - StdinFd uintptr - - // StdoutFd specifies the fd to write output to. - StdoutFd uintptr - - // StderrFd specifies the fd to write error output to. - StderrFd uintptr - - // EscapeCharacter (a means , b maens ). - EscapeCharacter rune -} - -// DefaultConsoleOptions is a convenient set of options to be used. -var DefaultConsoleOptions = ConsoleOptions{ - Tty: -1, - StdinFd: os.Stdin.Fd(), - StdoutFd: os.Stdout.Fd(), - StderrFd: os.Stderr.Fd(), - EscapeCharacter: 'a', -} - -// CloneOptions type is used for defining various clone options. -type CloneOptions struct { - - // Backend specifies the type of the backend. - Backend BackendStore - - // lxcpath in which to create the new container. If not set the original container's lxcpath will be used. - ConfigPath string - - // Do not change the hostname of the container (in the root filesystem). - KeepName bool - - // Use the same MAC address as the original container, rather than generating a new random one. - KeepMAC bool - - // Create a snapshot rather than copy. - Snapshot bool -} - -// DefaultCloneOptions is a convenient set of options to be used. -var DefaultCloneOptions = CloneOptions{ - Backend: Directory, -} - -// CheckpointOptions type is used for defining checkpoint options for CRIU. -type CheckpointOptions struct { - Directory string - Stop bool - Verbose bool -} - -// RestoreOptions type is used for defining restore options for CRIU. -type RestoreOptions struct { - Directory string - Verbose bool -} - -// MigrateOptions type is used for defining migrate options. -type MigrateOptions struct { - Directory string - PredumpDir string - ActionScript string - Verbose bool - Stop bool - PreservesInodes bool - GhostLimit uint64 - FeaturesToCheck CriuFeatures -} - -// ConsoleLogOptioins type is used for defining console log options. -type ConsoleLogOptions struct { - ClearLog bool - ReadLog bool - ReadMax uint64 - WriteToLogFile bool -} diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/type.go b/vendor/gopkg.in/lxc/go-lxc.v2/type.go deleted file mode 100644 index ced3c3396..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/type.go +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -package lxc - -// #include -import "C" - -import "fmt" - -// Verbosity type -type Verbosity int - -const ( - // Quiet makes some API calls not to write anything to stdout - Quiet Verbosity = 1 << iota - // Verbose makes some API calls write to stdout - Verbose -) - -// BackendStore type specifies possible backend types. -type BackendStore int - -const ( - // Btrfs backendstore type - Btrfs BackendStore = iota + 1 - // Directory backendstore type - Directory - // LVM backendstore type - LVM - // ZFS backendstore type - ZFS - // Aufs backendstore type - Aufs - // Overlayfs backendstore type - Overlayfs - // Loopback backendstore type - Loopback - // Best backendstore type - Best -) - -// BackendStore as string -func (t BackendStore) String() string { - switch t { - case Directory: - return "dir" - case ZFS: - return "zfs" - case Btrfs: - return "btrfs" - case LVM: - return "lvm" - case Aufs: - return "aufs" - case Overlayfs: - return "overlayfs" - case Loopback: - return "loopback" - case Best: - return "best" - } - return "" -} - -var backendStoreMap = map[string]BackendStore{ - "dir": Directory, - "zfs": ZFS, - "btrfs": Btrfs, - "lvm": LVM, - "aufs": Aufs, - "overlayfs": Overlayfs, - "loopback": Loopback, - "best": Best, -} - -// Set is the method to set the flag value, part of the flag.Value interface. -func (t *BackendStore) Set(value string) error { - backend, ok := backendStoreMap[value] - if ok { - *t = backend - return nil - } - return ErrUnknownBackendStore -} - -// State type specifies possible container states. -type State int - -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 -) - -// StateMap provides the mapping betweens the state names and states -var StateMap = map[string]State{ - "STOPPED": STOPPED, - "STARTING": STARTING, - "RUNNING": RUNNING, - "STOPPING": STOPPING, - "ABORTING": ABORTING, - "FREEZING": FREEZING, - "FROZEN": FROZEN, - "THAWED": THAWED, -} - -// State as string -func (t State) String() string { - switch t { - case STOPPED: - return "STOPPED" - case STARTING: - return "STARTING" - case RUNNING: - return "RUNNING" - case STOPPING: - return "STOPPING" - case ABORTING: - return "ABORTING" - case FREEZING: - return "FREEZING" - case FROZEN: - return "FROZEN" - case THAWED: - return "THAWED" - } - return "" -} - -// Taken from http://golang.org/doc/effective_go.html#constants - -// ByteSize type -type ByteSize float64 - -const ( - _ = iota - // KB - kilobyte - KB ByteSize = 1 << (10 * iota) - // MB - megabyte - MB - // GB - gigabyte - GB - // TB - terabyte - TB - // PB - petabyte - PB - // EB - exabyte - EB - // ZB - zettabyte - ZB - // YB - yottabyte - YB -) - -func (b ByteSize) String() string { - switch { - case b >= YB: - return fmt.Sprintf("%.2fYB", b/YB) - case b >= ZB: - return fmt.Sprintf("%.2fZB", b/ZB) - case b >= EB: - return fmt.Sprintf("%.2fEB", b/EB) - case b >= PB: - return fmt.Sprintf("%.2fPB", b/PB) - case b >= TB: - return fmt.Sprintf("%.2fTB", b/TB) - case b >= GB: - return fmt.Sprintf("%.2fGB", b/GB) - case b >= MB: - return fmt.Sprintf("%.2fMB", b/MB) - case b >= KB: - return fmt.Sprintf("%.2fKB", b/KB) - } - return fmt.Sprintf("%.2fB", b) -} - -// LogLevel type specifies possible log levels. -type LogLevel int - -const ( - // TRACE priority - TRACE LogLevel = iota - // DEBUG priority - DEBUG - // INFO priority - INFO - // NOTICE priority - NOTICE - // WARN priority - WARN - // ERROR priority - ERROR - // CRIT priority - CRIT - // ALERT priority - ALERT - // FATAL priority - FATAL -) - -var logLevelMap = map[string]LogLevel{ - "TRACE": TRACE, - "DEBUG": DEBUG, - "INFO": INFO, - "NOTICE": NOTICE, - "WARN": WARN, - "ERROR": ERROR, - "CRIT": CRIT, - "ALERT": ALERT, - "FATAL": FATAL, -} - -func (l LogLevel) String() string { - switch l { - case TRACE: - return "TRACE" - case DEBUG: - return "DEBUG" - case INFO: - return "INFO" - case NOTICE: - return "NOTICE" - case WARN: - return "WARN" - case ERROR: - return "ERROR" - case CRIT: - return "CRIT" - case ALERT: - return "ALERT" - case FATAL: - return "FATAL" - } - return "NOTSET" -} - -// Personality allows to set the architecture for the container. -type Personality int64 - -const ( - X86 Personality = 0x0008 - X86_64 = 0x0000 -) - -const ( - MIGRATE_PRE_DUMP = 0 - MIGRATE_DUMP = 1 - MIGRATE_RESTORE = 2 - MIGRATE_FEATURE_CHECK = 3 -) - -type CriuFeatures uint64 - -const ( - FEATURE_MEM_TRACK CriuFeatures = 1 << iota - FEATURE_LAZY_PAGES -) diff --git a/vendor/gopkg.in/lxc/go-lxc.v2/util.go b/vendor/gopkg.in/lxc/go-lxc.v2/util.go deleted file mode 100644 index fba2dab7d..000000000 --- a/vendor/gopkg.in/lxc/go-lxc.v2/util.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. -// Use of this source code is governed by a LGPLv2.1 -// license that can be found in the LICENSE file. - -// +build linux,cgo - -package lxc - -/* -#include -#include - -static char** makeCharArray(size_t size) { - // caller checks return value - return calloc(size, sizeof(char*)); -} - -static void setArrayString(char **array, char *string, size_t n) { - array[n] = string; -} - -static void freeCharArray(char **array, size_t size) { - size_t i; - for (i = 0; i < size; i++) { - free(array[i]); - } - free(array); -} - -static void freeSnapshotArray(struct lxc_snapshot *s, size_t size) { - size_t i; - for (i = 0; i < size; i++) { - s[i].free(&s[i]); - } - free(s); -} - -static size_t getArrayLength(char **array) { - char **p; - size_t size = 0; - for (p = (char **)array; *p; p++) { - size++; - } - return size; -} -*/ -import "C" - -import ( - "reflect" - "unsafe" -) - -func makeNullTerminatedArgs(args []string) **C.char { - cparams := C.makeCharArray(C.size_t(len(args) + 1)) - if cparams == nil { - return nil - } - - for i := 0; i < len(args); i++ { - C.setArrayString(cparams, C.CString(args[i]), C.size_t(i)) - } - C.setArrayString(cparams, nil, C.size_t(len(args))) - - return cparams -} - -func freeNullTerminatedArgs(cArgs **C.char, length int) { - C.freeCharArray(cArgs, C.size_t(length+1)) -} - -func convertArgs(cArgs **C.char) []string { - if cArgs == nil { - return nil - } - - return convertNArgs(cArgs, int(C.getArrayLength(cArgs))) -} - -func convertNArgs(cArgs **C.char, size int) []string { - if cArgs == nil || size <= 0 { - return nil - } - - var A []*C.char - - hdr := reflect.SliceHeader{ - Data: uintptr(unsafe.Pointer(cArgs)), - Len: size, - Cap: size, - } - cArgsInterface := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&hdr)).Elem().Interface() - - result := make([]string, size) - for i := 0; i < size; i++ { - result[i] = C.GoString(cArgsInterface.([]*C.char)[i]) - } - C.freeCharArray(cArgs, C.size_t(size)) - - return result -} - -func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) { - C.freeSnapshotArray(snapshots, C.size_t(size)) -} diff --git a/vendor/vendor.json b/vendor/vendor.json index 6099b67ad..e217677f8 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -438,7 +438,6 @@ {"path":"google.golang.org/grpc/transport","checksumSHA1":"oFGr0JoquaPGVnV86fVL8MVTc3A=","revision":"0c41876308d45bc82e587965971e28be659a1aca","revisionTime":"2017-07-21T17:58:12Z"}, {"path":"gopkg.in/fsnotify.v1","checksumSHA1":"eIhF+hmL/XZhzTiAwhLD0M65vlY=","revision":"629574ca2a5df945712d3079857300b5e4da0236","revisionTime":"2016-10-11T02:33:12Z"}, {"path":"gopkg.in/inf.v0","checksumSHA1":"6f8MEU31llHM1sLM/GGH4/Qxu0A=","revision":"3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4","revisionTime":"2015-09-11T12:57:57Z"}, - {"path":"gopkg.in/lxc/go-lxc.v2","checksumSHA1":"oAflbBrzWC7OMmZQixkp9bnPQW8=","revision":"0aadfc37157c2e3f0e63bedd10f8615e66e91cad","revisionTime":"2018-11-01T16:03:35Z"}, {"path":"gopkg.in/tomb.v1","checksumSHA1":"TO8baX+t1Qs7EmOYth80MkbKzFo=","revision":"dd632973f1e7218eb1089048e0798ec9ae7dceb8","revisionTime":"2014-10-24T13:56:13Z"}, {"path":"gopkg.in/tomb.v2","checksumSHA1":"WiyCOMvfzRdymImAJ3ME6aoYUdM=","revision":"14b3d72120e8d10ea6e6b7f87f7175734b1faab8","revisionTime":"2014-06-26T14:46:23Z"}, {"path":"gopkg.in/yaml.v2","checksumSHA1":"12GqsW8PiRPnezDDy0v4brZrndM=","revision":"a5b47d31c556af34a302ce5d659e6fea44d90de0","revisionTime":"2016-09-28T15:37:09Z"}