├── const.go ├── doc.go ├── .gitignore ├── examples ├── Makefile ├── destroy_snapshots.go ├── list_snapshots.go ├── list_keys.go ├── destroy.go ├── reboot.go ├── create_snapshot.go ├── freeze.go ├── unfreeze.go ├── execute.go ├── console.go ├── stop.go ├── shutdown.go ├── start.go ├── restore_snapshot.go ├── interfaces.go ├── rename.go ├── device_add_remove.go ├── list.go ├── concurrent_stop.go ├── concurrent_start.go ├── concurrent_destroy.go ├── concurrent_create.go ├── concurrent_shutdown.go ├── limit.go ├── create.go ├── attach.go ├── clone.go ├── ipaddress.go ├── attach_with_pipes.go ├── stats.go └── concurrent_stress.go ├── Makefile ├── README.md ├── util.go ├── lxc.h ├── error.go ├── lxc.go ├── type.go ├── lxc.c ├── LICENSE ├── lxc_test.go └── container.go /const.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | package lxc 11 | 12 | const ( 13 | // WaitForever timeout 14 | WaitForever int = iota - 1 15 | // DontWait timeout 16 | DontWait 17 | ) 18 | 19 | const ( 20 | isDefined = 1 << iota 21 | isNotDefined 22 | isRunning 23 | isNotRunning 24 | ) 25 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | LXC (LinuX Containers) is an operating system–level virtualization method for running multiple isolated Linux systems (containers) on a single control host. 4 | 5 | The Linux kernel comprises cgroups for resource isolation (CPU, memory, block I/O, network, etc.) that does not require starting any virtual machines. Cgroups also provides namespace isolation to completely isolate application's view of the operating environment, including process trees, network, user ids and mounted file systems. 6 | 7 | LXC combines cgroups and namespace support to provide an isolated environment for applications. 8 | */ 9 | package lxc 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | examples/attach 2 | examples/attach_with_pipes 3 | examples/clone 4 | examples/concurrent_create 5 | examples/concurrent_destroy 6 | examples/concurrent_shutdown 7 | examples/concurrent_start 8 | examples/concurrent_stop 9 | examples/concurrent_stress 10 | examples/console 11 | examples/create 12 | examples/create_snapshot 13 | examples/destroy 14 | examples/destroy_snapshots 15 | examples/device_add_remove 16 | examples/execute 17 | examples/freeze 18 | examples/interfaces 19 | examples/ipaddress 20 | examples/limit 21 | examples/list 22 | examples/list_keys 23 | examples/list_snapshots 24 | examples/reboot 25 | examples/rename 26 | examples/restore_snapshot 27 | examples/shutdown 28 | examples/start 29 | examples/stats 30 | examples/stop 31 | examples/unfreeze 32 | coverage.out 33 | tags 34 | -------------------------------------------------------------------------------- /examples/Makefile: -------------------------------------------------------------------------------- 1 | NO_COLOR=\033[0m 2 | OK_COLOR=\033[0;32m 3 | 4 | ALL_GO_FILES = $(wildcard *.go) 5 | ALL_FILES = $(patsubst %.go,%,$(ALL_GO_FILES)) 6 | 7 | all: $(ALL_FILES) 8 | 9 | define PROGRAM_template 10 | $(1): format vet lint 11 | @echo "$(OK_COLOR)==> Building $(1) $(NO_COLOR)" 12 | @go build $(1).go 13 | endef 14 | 15 | $(foreach prog,$(ALL_FILES),$(eval $(call PROGRAM_template,$(prog)))) 16 | 17 | clean: 18 | @$(foreach file,$(ALL_FILES),rm -f $(file);) 19 | 20 | format: 21 | @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" 22 | @gofmt -s -w *.go 23 | @goimports -w *.go 24 | 25 | vet: 26 | @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" 27 | @`which go` vet . 28 | 29 | lint: 30 | @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" 31 | @`which golint` . 32 | 33 | .PHONY: all clean format vet lint 34 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | NO_COLOR=\033[0m 2 | OK_COLOR=\033[0;32m 3 | 4 | all: format vet lint 5 | 6 | format: 7 | @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" 8 | @gofmt -s -w *.go 9 | @goimports -w *.go || true 10 | 11 | test: 12 | @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" 13 | @sudo `which go` test -v 14 | 15 | test-race: 16 | @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" 17 | @sudo `which go` test -race -v 18 | 19 | test-unprivileged: 20 | @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" 21 | @`which go` test -v 22 | 23 | test-unprivileged-race: 24 | @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" 25 | @`which go` test -race -v 26 | 27 | # requires https://codereview.appspot.com/34680044/ 28 | cover: 29 | @sudo `which go` test -v -coverprofile=coverage.out 30 | @`which go` tool cover -func=coverage.out 31 | 32 | doc: 33 | @`which godoc` github.com/lxc/go-lxc | less 34 | 35 | vet: 36 | @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" 37 | @`which go` vet . 38 | 39 | lint: 40 | @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" 41 | @`which golint` . || true 42 | 43 | ctags: 44 | @ctags -R --languages=c,go 45 | 46 | .PHONY: all format test doc vet lint ctags 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go Bindings for LXC (Linux Containers) 2 | 3 | This package implements [Go](http://golang.org) bindings for the [LXC](http://linuxcontainers.org/) C API (liblxc). 4 | 5 | ## Requirements 6 | 7 | This package requires [LXC 1.x](https://github.com/lxc/lxc/releases) and its development package to be installed. Works with [Go 1.x](https://code.google.com/p/go/downloads/list). 8 | 9 | ## Installing 10 | 11 | To install it, run: 12 | 13 | go get gopkg.in/lxc/go-lxc.v1 14 | 15 | ## Documentation 16 | 17 | Documentation can be found at [GoDoc](http://godoc.org/gopkg.in/lxc/go-lxc.v1). 18 | 19 | ## Stability 20 | 21 | The package API will remain stable as described in [gopkg.in](https://gopkg.in). 22 | 23 | ## Examples 24 | 25 | See the [examples](https://github.com/lxc/go-lxc/tree/master/examples) directory for some. 26 | 27 | ## Contributing 28 | 29 | We'd love to see go-lxc improve. To contribute to go-lxc; 30 | 31 | * **Fork** the repository 32 | * **Modify** your fork 33 | * Ensure your fork **passes all tests** 34 | * **Send** a pull request 35 | * Bonus points if the pull request includes *what* you changed, *why* you changed it, and *tests* attached. 36 | * For the love of all that is holy, please use `go fmt` *before* you send the pull request. 37 | 38 | We'll review it and merge it in if it's appropriate. 39 | -------------------------------------------------------------------------------- /examples/destroy_snapshots.go: -------------------------------------------------------------------------------- 1 | /* 2 | * destroy_snapshots.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "log" 27 | 28 | "gopkg.in/lxc/go-lxc.v1" 29 | ) 30 | 31 | func main() { 32 | c := lxc.Containers() 33 | for i := range c { 34 | log.Printf("%s\n", c[i].Name()) 35 | l, err := c[i].Snapshots() 36 | if err != nil { 37 | log.Fatalf("ERROR: %s\n", err.Error()) 38 | } 39 | 40 | for _, s := range l { 41 | log.Printf("Destroying Snaphot: %s\n", s.Name) 42 | if err := c[i].DestroySnapshot(s); err != nil { 43 | log.Fatalf("ERROR: %s\n", err.Error()) 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /examples/list_snapshots.go: -------------------------------------------------------------------------------- 1 | /* 2 | * list_snapshots.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "log" 27 | 28 | "gopkg.in/lxc/go-lxc.v1" 29 | ) 30 | 31 | func main() { 32 | c := lxc.Containers() 33 | for i := range c { 34 | log.Printf("%s\n", c[i].Name()) 35 | l, err := c[i].Snapshots() 36 | if err != nil { 37 | log.Printf("ERROR: %s\n", err.Error()) 38 | } 39 | 40 | for _, s := range l { 41 | log.Printf("Name: %s\n", s.Name) 42 | log.Printf("Comment path: %s\n", s.CommentPath) 43 | log.Printf("Timestamp: %s\n", s.Timestamp) 44 | log.Printf("LXC path: %s\n", s.Path) 45 | log.Println() 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /examples/list_keys.go: -------------------------------------------------------------------------------- 1 | /* 2 | * list_keys.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | for _, k := range c.ConfigKeys() { 51 | log.Printf("%s -> %s", k, c.ConfigItem(k)) 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /examples/destroy.go: -------------------------------------------------------------------------------- 1 | /* 2 | * destroy.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | log.Printf("Destroying container...\n") 51 | if err := c.Destroy(); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /examples/reboot.go: -------------------------------------------------------------------------------- 1 | /* 2 | * reboot.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | log.Printf("Rebooting the container...\n") 51 | if err := c.Reboot(); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /examples/create_snapshot.go: -------------------------------------------------------------------------------- 1 | /* 2 | * snapshot.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | log.Printf("Snapshoting the container...\n") 51 | if _, err := c.CreateSnapshot(); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /examples/freeze.go: -------------------------------------------------------------------------------- 1 | /* 2 | * freeze.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "time" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&name, "name", "rubik", "Name of the container") 41 | flag.Parse() 42 | } 43 | 44 | func main() { 45 | c, err := lxc.NewContainer(name, lxcpath) 46 | if err != nil { 47 | log.Fatalf("ERROR: %s\n", err.Error()) 48 | } 49 | defer lxc.PutContainer(c) 50 | 51 | log.Printf("Freezing the container...\n") 52 | if err := c.Freeze(); err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | c.Wait(lxc.FROZEN, 10*time.Second) 56 | } 57 | -------------------------------------------------------------------------------- /examples/unfreeze.go: -------------------------------------------------------------------------------- 1 | /* 2 | * unfreeze.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "time" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&name, "name", "rubik", "Name of the container") 41 | flag.Parse() 42 | } 43 | 44 | func main() { 45 | c, err := lxc.NewContainer(name, lxcpath) 46 | if err != nil { 47 | log.Fatalf("ERROR: %s\n", err.Error()) 48 | } 49 | defer lxc.PutContainer(c) 50 | 51 | log.Printf("Unfreezing the container...\n") 52 | if err := c.Unfreeze(); err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | c.Wait(lxc.RUNNING, 10*time.Second) 56 | } 57 | -------------------------------------------------------------------------------- /examples/execute.go: -------------------------------------------------------------------------------- 1 | /* 2 | * execute.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | c.LoadConfigFile(lxc.DefaultConfigPath()) 51 | if output, err := c.Execute("uname", "-a"); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } else { 54 | log.Printf("%s", output) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/console.go: -------------------------------------------------------------------------------- 1 | /* 2 | * console.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "os" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&name, "name", "rubik", "Name of the container") 41 | flag.Parse() 42 | } 43 | 44 | func main() { 45 | c, err := lxc.NewContainer(name, lxcpath) 46 | if err != nil { 47 | log.Fatalf("ERROR: %s\n", err.Error()) 48 | } 49 | defer lxc.PutContainer(c) 50 | 51 | log.Printf("Attaching to container's console...\n") 52 | if err := c.Console(-1, os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), 1); err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /examples/stop.go: -------------------------------------------------------------------------------- 1 | /* 2 | * stop.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | c.SetLogFile("/tmp/" + name + ".log") 51 | c.SetLogLevel(lxc.TRACE) 52 | 53 | log.Printf("Stopping the container...\n") 54 | if err := c.Stop(); err != nil { 55 | log.Fatalf("ERROR: %s\n", err.Error()) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /examples/shutdown.go: -------------------------------------------------------------------------------- 1 | /* 2 | * shutdown.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "time" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&name, "name", "rubik", "Name of the container") 41 | flag.Parse() 42 | } 43 | 44 | func main() { 45 | c, err := lxc.NewContainer(name, lxcpath) 46 | if err != nil { 47 | log.Fatalf("ERROR: %s\n", err.Error()) 48 | } 49 | defer lxc.PutContainer(c) 50 | 51 | log.Printf("Shutting down the container...\n") 52 | if err := c.Shutdown(30 * time.Second); err != nil { 53 | if err = c.Stop(); err != nil { 54 | log.Fatalf("ERROR: %s\n", err.Error()) 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /examples/start.go: -------------------------------------------------------------------------------- 1 | /* 2 | * start.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "time" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&name, "name", "rubik", "Name of the container") 41 | flag.Parse() 42 | } 43 | 44 | func main() { 45 | c, err := lxc.NewContainer(name, lxcpath) 46 | if err != nil { 47 | log.Fatalf("ERROR: %s\n", err.Error()) 48 | } 49 | defer lxc.PutContainer(c) 50 | 51 | c.SetLogFile("/tmp/" + name + ".log") 52 | c.SetLogLevel(lxc.TRACE) 53 | 54 | log.Printf("Starting the container...\n") 55 | if err := c.Start(); err != nil { 56 | log.Fatalf("ERROR: %s\n", err.Error()) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /examples/restore_snapshot.go: -------------------------------------------------------------------------------- 1 | /* 2 | * snapshot_restore.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | log.Printf("Restoring the container...\n") 51 | snapshot := lxc.Snapshot{Name: "snap0"} 52 | 53 | if err := c.RestoreSnapshot(snapshot, "rubik-restore"); err != nil { 54 | log.Fatalf("ERROR: %s\n", err.Error()) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/interfaces.go: -------------------------------------------------------------------------------- 1 | /* 2 | * interfaces.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the original container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | log.Printf("Interfaces\n") 51 | if interfaces, err := c.Interfaces(); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } else { 54 | for i, v := range interfaces { 55 | log.Printf("%d) %s\n", i, v) 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /examples/rename.go: -------------------------------------------------------------------------------- 1 | /* 2 | * rename.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | newname string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&newname, "newname", "kibur", "New name of the container") 41 | flag.StringVar(&name, "name", "rubik", "Name of the container") 42 | flag.Parse() 43 | } 44 | 45 | func main() { 46 | c, err := lxc.NewContainer(name, lxcpath) 47 | if err != nil { 48 | log.Fatalf("ERROR: %s\n", err.Error()) 49 | } 50 | defer lxc.PutContainer(c) 51 | 52 | log.Printf("Renaming container to %s...\n", newname) 53 | if err := c.Rename(newname); err != nil { 54 | log.Printf("ERROR: %s\n", err.Error()) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /examples/device_add_remove.go: -------------------------------------------------------------------------------- 1 | /* 2 | * device_add_remove.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "time" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | ) 37 | 38 | func init() { 39 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 40 | flag.StringVar(&name, "name", "rubik", "Name of the container") 41 | flag.Parse() 42 | } 43 | 44 | func main() { 45 | c, err := lxc.NewContainer(name, lxcpath) 46 | if err != nil { 47 | log.Fatalf("ERROR: %s\n", err.Error()) 48 | } 49 | defer lxc.PutContainer(c) 50 | 51 | if err := c.AddDeviceNode("/dev/network_latency"); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } 54 | 55 | time.Sleep(10000 * time.Millisecond) 56 | 57 | if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { 58 | log.Fatalf("ERROR: %s\n", err.Error()) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /examples/list.go: -------------------------------------------------------------------------------- 1 | /* 2 | * list.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | ) 35 | 36 | func init() { 37 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 38 | flag.Parse() 39 | } 40 | 41 | func main() { 42 | log.Printf("Defined containers:\n") 43 | c := lxc.DefinedContainers(lxcpath) 44 | for i := range c { 45 | log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) 46 | } 47 | 48 | log.Println() 49 | 50 | log.Printf("Active containers:\n") 51 | c = lxc.ActiveContainers(lxcpath) 52 | for i := range c { 53 | log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) 54 | } 55 | 56 | log.Println() 57 | 58 | log.Printf("Active and Defined containers:\n") 59 | c = lxc.ActiveContainers(lxcpath) 60 | for i := range c { 61 | log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /examples/concurrent_stop.go: -------------------------------------------------------------------------------- 1 | /* 2 | * concurrent_stop.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "runtime" 29 | "strconv" 30 | "sync" 31 | 32 | "gopkg.in/lxc/go-lxc.v1" 33 | ) 34 | 35 | var ( 36 | lxcpath string 37 | ) 38 | 39 | func init() { 40 | runtime.GOMAXPROCS(runtime.NumCPU()) 41 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 42 | flag.Parse() 43 | } 44 | 45 | func main() { 46 | var wg sync.WaitGroup 47 | 48 | for i := 0; i < 10; i++ { 49 | wg.Add(1) 50 | go func(i int) { 51 | c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) 52 | if err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | defer lxc.PutContainer(c) 56 | 57 | log.Printf("Stoping the container (%d)...\n", i) 58 | if err := c.Stop(); err != nil { 59 | log.Fatalf("ERROR: %s\n", err.Error()) 60 | } 61 | wg.Done() 62 | }(i) 63 | } 64 | wg.Wait() 65 | } 66 | -------------------------------------------------------------------------------- /examples/concurrent_start.go: -------------------------------------------------------------------------------- 1 | /* 2 | * concurrent_start.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "runtime" 29 | "strconv" 30 | "sync" 31 | 32 | "gopkg.in/lxc/go-lxc.v1" 33 | ) 34 | 35 | var ( 36 | lxcpath string 37 | ) 38 | 39 | func init() { 40 | runtime.GOMAXPROCS(runtime.NumCPU()) 41 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 42 | flag.Parse() 43 | } 44 | 45 | func main() { 46 | var wg sync.WaitGroup 47 | 48 | for i := 0; i < 10; i++ { 49 | wg.Add(1) 50 | go func(i int) { 51 | c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) 52 | if err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | defer lxc.PutContainer(c) 56 | 57 | log.Printf("Starting the container (%d)...\n", i) 58 | if err := c.Start(); err != nil { 59 | log.Fatalf("ERROR: %s\n", err.Error()) 60 | } 61 | wg.Done() 62 | }(i) 63 | } 64 | wg.Wait() 65 | } 66 | -------------------------------------------------------------------------------- /examples/concurrent_destroy.go: -------------------------------------------------------------------------------- 1 | /* 2 | * concurrent_destroy.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "runtime" 29 | "strconv" 30 | "sync" 31 | 32 | "gopkg.in/lxc/go-lxc.v1" 33 | ) 34 | 35 | var ( 36 | lxcpath string 37 | ) 38 | 39 | func init() { 40 | runtime.GOMAXPROCS(runtime.NumCPU()) 41 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 42 | flag.Parse() 43 | } 44 | 45 | func main() { 46 | var wg sync.WaitGroup 47 | 48 | for i := 0; i < 10; i++ { 49 | wg.Add(1) 50 | go func(i int) { 51 | c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) 52 | if err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | defer lxc.PutContainer(c) 56 | 57 | log.Printf("Destroying the container (%d)...\n", i) 58 | if err := c.Destroy(); err != nil { 59 | log.Fatalf("ERROR: %s\n", err.Error()) 60 | } 61 | wg.Done() 62 | }(i) 63 | } 64 | wg.Wait() 65 | } 66 | -------------------------------------------------------------------------------- /examples/concurrent_create.go: -------------------------------------------------------------------------------- 1 | /* 2 | * concurrent_create.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "runtime" 29 | "strconv" 30 | "sync" 31 | 32 | "gopkg.in/lxc/go-lxc.v1" 33 | ) 34 | 35 | var ( 36 | lxcpath string 37 | ) 38 | 39 | func init() { 40 | runtime.GOMAXPROCS(runtime.NumCPU()) 41 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 42 | flag.Parse() 43 | } 44 | 45 | func main() { 46 | var wg sync.WaitGroup 47 | 48 | for i := 0; i < 10; i++ { 49 | wg.Add(1) 50 | go func(i int) { 51 | c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) 52 | if err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | defer lxc.PutContainer(c) 56 | 57 | log.Printf("Creating the container (%d)...\n", i) 58 | if err := c.Create("busybox"); err != nil { 59 | log.Fatalf("ERROR: %s\n", err.Error()) 60 | } 61 | wg.Done() 62 | }(i) 63 | } 64 | wg.Wait() 65 | } 66 | -------------------------------------------------------------------------------- /examples/concurrent_shutdown.go: -------------------------------------------------------------------------------- 1 | /* 2 | * concurrent_stop.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "runtime" 29 | "strconv" 30 | "sync" 31 | "time" 32 | 33 | "gopkg.in/lxc/go-lxc.v1" 34 | ) 35 | 36 | var ( 37 | lxcpath string 38 | ) 39 | 40 | func init() { 41 | runtime.GOMAXPROCS(runtime.NumCPU()) 42 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 43 | flag.Parse() 44 | } 45 | 46 | func main() { 47 | var wg sync.WaitGroup 48 | 49 | for i := 0; i < 10; i++ { 50 | wg.Add(1) 51 | go func(i int) { 52 | c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) 53 | if err != nil { 54 | log.Fatalf("ERROR: %s\n", err.Error()) 55 | } 56 | defer lxc.PutContainer(c) 57 | 58 | log.Printf("Shutting down the container (%d)...\n", i) 59 | if err := c.Shutdown(30 * time.Second); err != nil { 60 | if err = c.Stop(); err != nil { 61 | log.Fatalf("ERROR: %s\n", err.Error()) 62 | } 63 | } 64 | wg.Done() 65 | }(i) 66 | } 67 | wg.Wait() 68 | } 69 | -------------------------------------------------------------------------------- /examples/limit.go: -------------------------------------------------------------------------------- 1 | /* 2 | * limit.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | memLimit, err := c.MemoryLimit() 51 | if err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } 54 | memorySwapLimit, err := c.MemorySwapLimit() 55 | if err != nil { 56 | log.Fatalf("ERROR: %s\n", err.Error()) 57 | } 58 | 59 | if err := c.SetMemoryLimit(memLimit / 4); err != nil { 60 | log.Fatalf("ERROR: %s\n", err.Error()) 61 | } 62 | if err := c.SetMemorySwapLimit(memorySwapLimit / 4); err != nil { 63 | log.Fatalf("ERROR: %s\n", err.Error()) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /examples/create.go: -------------------------------------------------------------------------------- 1 | /* 2 | * create.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "os" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | template string 36 | distro string 37 | release string 38 | arch string 39 | name string 40 | verbose bool 41 | ) 42 | 43 | func init() { 44 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 45 | flag.StringVar(&template, "template", "ubuntu", "Template to use") 46 | flag.StringVar(&distro, "distro", "ubuntu", "Template to use") 47 | flag.StringVar(&release, "release", "trusty", "Template to use") 48 | flag.StringVar(&arch, "arch", "amd64", "Template to use") 49 | flag.StringVar(&name, "name", "rubik", "Name of the container") 50 | flag.BoolVar(&verbose, "verbose", false, "Verbose output") 51 | flag.Parse() 52 | } 53 | 54 | func main() { 55 | c, err := lxc.NewContainer(name, lxcpath) 56 | if err != nil { 57 | log.Fatalf("ERROR: %s\n", err.Error()) 58 | } 59 | defer lxc.PutContainer(c) 60 | 61 | log.Printf("Creating container...\n") 62 | if verbose { 63 | c.SetVerbosity(lxc.Verbose) 64 | } 65 | 66 | if os.Geteuid() != 0 { 67 | if err := c.CreateAsUser(distro, release, arch); err != nil { 68 | log.Printf("ERROR: %s\n", err.Error()) 69 | } 70 | } else { 71 | if err := c.Create(template, "-a", arch, "-r", release); err != nil { 72 | log.Printf("ERROR: %s\n", err.Error()) 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /examples/attach.go: -------------------------------------------------------------------------------- 1 | /* 2 | * attach.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | "os" 29 | 30 | "gopkg.in/lxc/go-lxc.v1" 31 | ) 32 | 33 | var ( 34 | lxcpath string 35 | name string 36 | clear bool 37 | ) 38 | 39 | func init() { 40 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 41 | flag.StringVar(&name, "name", "rubik", "Name of the original container") 42 | flag.BoolVar(&clear, "clear", false, "Attach with clear environment") 43 | flag.Parse() 44 | } 45 | 46 | func main() { 47 | c, err := lxc.NewContainer(name, lxcpath) 48 | if err != nil { 49 | log.Fatalf("ERROR: %s\n", err.Error()) 50 | } 51 | defer lxc.PutContainer(c) 52 | 53 | if clear { 54 | log.Printf("AttachShellWithClearEnvironment\n") 55 | if err := c.AttachShellWithClearEnvironment(); err != nil { 56 | log.Fatalf("ERROR: %s\n", err.Error()) 57 | } 58 | 59 | log.Printf("RunCommandWithClearEnvironment\n") 60 | if _, err := c.RunCommandWithClearEnvironment(os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), "uname", "-a"); err != nil { 61 | log.Fatalf("ERROR: %s\n", err.Error()) 62 | } 63 | 64 | } else { 65 | log.Printf("AttachShell\n") 66 | if err := c.AttachShell(); err != nil { 67 | log.Fatalf("ERROR: %s\n", err.Error()) 68 | } 69 | 70 | log.Printf("RunCommand\n") 71 | if _, err := c.RunCommand(os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), "uname", "-a"); err != nil { 72 | log.Fatalf("ERROR: %s\n", err.Error()) 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /examples/clone.go: -------------------------------------------------------------------------------- 1 | /* 2 | * clone.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the original container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | directoryClone := name + "Directory" 51 | overlayClone := name + "Overlayfs" 52 | btrfsClone := name + "Btrfs" 53 | aufsClone := name + "Aufs" 54 | 55 | log.Printf("Cloning the container using Directory backend...\n") 56 | if err := c.Clone(directoryClone); err != nil { 57 | log.Fatalf("ERROR: %s\n", err.Error()) 58 | } 59 | 60 | log.Printf("Cloning the container using Overlayfs backend...\n") 61 | if err := c.CloneUsing(overlayClone, lxc.Overlayfs, lxc.CloneSnapshot); err != nil { 62 | log.Fatalf("ERROR: %s\n", err.Error()) 63 | } 64 | 65 | log.Printf("Cloning the container using Aufs backend...\n") 66 | if err := c.CloneUsing(aufsClone, lxc.Aufs, lxc.CloneSnapshot); err != nil { 67 | log.Fatalf("ERROR: %s\n", err.Error()) 68 | } 69 | 70 | log.Printf("Cloning the container using Btrfs backend...\n") 71 | if err := c.CloneUsing(btrfsClone, lxc.Btrfs, 0); err != nil { 72 | log.Fatalf("ERROR: %s\n", err.Error()) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /examples/ipaddress.go: -------------------------------------------------------------------------------- 1 | /* 2 | * ipaddress.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the original container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | log.Printf("IPAddress(\"lo\")\n") 51 | if addresses, err := c.IPAddress("lo"); err != nil { 52 | log.Fatalf("ERROR: %s\n", err.Error()) 53 | } else { 54 | for i, v := range addresses { 55 | log.Printf("%d) %s\n", i, v) 56 | } 57 | } 58 | 59 | log.Printf("IPAddresses()\n") 60 | if addresses, err := c.IPAddresses(); err != nil { 61 | log.Fatalf("ERROR: %s\n", err.Error()) 62 | } else { 63 | for i, v := range addresses { 64 | log.Printf("%d) %s\n", i, v) 65 | } 66 | } 67 | 68 | log.Printf("IPv4Addresses()\n") 69 | if addresses, err := c.IPv4Addresses(); err != nil { 70 | log.Fatalf("ERROR: %s\n", err.Error()) 71 | } else { 72 | for i, v := range addresses { 73 | log.Printf("%d) %s\n", i, v) 74 | } 75 | } 76 | 77 | log.Printf("IPv6Addresses()\n") 78 | if addresses, err := c.IPv6Addresses(); err != nil { 79 | log.Fatalf("ERROR: %s\n", err.Error()) 80 | } else { 81 | for i, v := range addresses { 82 | log.Printf("%d) %s\n", i, v) 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | package lxc 11 | 12 | /* 13 | #include 14 | #include 15 | 16 | static char** makeCharArray(size_t size) { 17 | // caller checks return value 18 | return calloc(sizeof(char*), size); 19 | } 20 | 21 | static void setArrayString(char **array, char *string, size_t n) { 22 | array[n] = string; 23 | } 24 | 25 | static void freeCharArray(char **array, size_t size) { 26 | size_t i; 27 | for (i = 0; i < size; i++) { 28 | free(array[i]); 29 | } 30 | free(array); 31 | } 32 | 33 | static void freeSnapshotArray(struct lxc_snapshot *s, size_t size) { 34 | size_t i; 35 | for (i = 0; i < size; i++) { 36 | s[i].free(&s[i]); 37 | } 38 | free(s); 39 | } 40 | 41 | static size_t getArrayLength(char **array) { 42 | char **p; 43 | size_t size = 0; 44 | for (p = (char **)array; *p; p++) { 45 | size++; 46 | } 47 | return size; 48 | } 49 | */ 50 | import "C" 51 | 52 | import ( 53 | "reflect" 54 | "unsafe" 55 | ) 56 | 57 | func makeNullTerminatedArgs(args []string) **C.char { 58 | cparams := C.makeCharArray(C.size_t(len(args) + 1)) 59 | if cparams == nil { 60 | return nil 61 | } 62 | 63 | for i := 0; i < len(args); i++ { 64 | C.setArrayString(cparams, C.CString(args[i]), C.size_t(i)) 65 | } 66 | C.setArrayString(cparams, nil, C.size_t(len(args))) 67 | 68 | return cparams 69 | } 70 | 71 | func freeNullTerminatedArgs(cArgs **C.char, length int) { 72 | C.freeCharArray(cArgs, C.size_t(length+1)) 73 | } 74 | 75 | func convertArgs(cArgs **C.char) []string { 76 | if cArgs == nil { 77 | return nil 78 | } 79 | 80 | return convertNArgs(cArgs, int(C.getArrayLength(cArgs))) 81 | } 82 | 83 | func convertNArgs(cArgs **C.char, size int) []string { 84 | if cArgs == nil || size <= 0 { 85 | return nil 86 | } 87 | 88 | var A []*C.char 89 | 90 | hdr := reflect.SliceHeader{ 91 | Data: uintptr(unsafe.Pointer(cArgs)), 92 | Len: size, 93 | Cap: size, 94 | } 95 | cArgsInterface := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&hdr)).Elem().Interface() 96 | 97 | result := make([]string, size) 98 | for i := 0; i < size; i++ { 99 | result[i] = C.GoString(cArgsInterface.([]*C.char)[i]) 100 | } 101 | C.freeCharArray(cArgs, C.size_t(size)) 102 | 103 | return result 104 | } 105 | 106 | func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) { 107 | C.freeSnapshotArray(snapshots, C.size_t(size)) 108 | } 109 | -------------------------------------------------------------------------------- /examples/attach_with_pipes.go: -------------------------------------------------------------------------------- 1 | /* 2 | * attach_with_pipes.go 3 | * 4 | * Copyright © 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * Kelsey Hightower 9 | * 10 | * This library is free software; you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License version 2, as 12 | * published by the Free Software Foundation. 13 | * 14 | * This program is distributed in the hope that it will be useful, 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | * GNU General Public License for more details. 18 | * 19 | * You should have received a copy of the GNU General Public License along 20 | * with this program; if not, write to the Free Software Foundation, Inc., 21 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 22 | */ 23 | 24 | package main 25 | 26 | import ( 27 | "flag" 28 | "io" 29 | "log" 30 | "os" 31 | "sync" 32 | 33 | "gopkg.in/lxc/go-lxc.v1" 34 | ) 35 | 36 | var ( 37 | lxcpath string 38 | name string 39 | clear bool 40 | wg sync.WaitGroup 41 | ) 42 | 43 | func init() { 44 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 45 | flag.StringVar(&name, "name", "rubik", "Name of the original container") 46 | flag.BoolVar(&clear, "clear", false, "Attach with clear environment") 47 | flag.Parse() 48 | } 49 | 50 | func main() { 51 | c, err := lxc.NewContainer(name, lxcpath) 52 | if err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } 55 | defer lxc.PutContainer(c) 56 | 57 | stdoutReader, stdoutWriter, err := os.Pipe() 58 | if err != nil { 59 | log.Fatalf("ERROR: %s\n", err.Error()) 60 | } 61 | stderrReader, stderrWriter, err := os.Pipe() 62 | if err != nil { 63 | log.Fatalf("ERROR: %s\n", err.Error()) 64 | } 65 | 66 | wg.Add(1) 67 | go func() { 68 | defer wg.Done() 69 | _, err := io.Copy(os.Stdout, stdoutReader) 70 | if err != nil { 71 | log.Fatalf("ERROR: %s\n", err.Error()) 72 | } 73 | }() 74 | wg.Add(1) 75 | go func() { 76 | defer wg.Done() 77 | _, err = io.Copy(os.Stderr, stderrReader) 78 | if err != nil { 79 | log.Fatalf("ERROR: %s\n", err.Error()) 80 | } 81 | }() 82 | 83 | if clear { 84 | log.Printf("AttachShellWithClearEnvironment\n") 85 | if err := c.AttachShellWithClearEnvironment(); err != nil { 86 | log.Fatalf("ERROR: %s\n", err.Error()) 87 | } 88 | 89 | log.Printf("RunCommandWithClearEnvironment\n") 90 | if _, err := c.RunCommandWithClearEnvironment(os.Stdin.Fd(), stdoutWriter.Fd(), stderrWriter.Fd(), "uname", "-a"); err != nil { 91 | log.Fatalf("ERROR: %s\n", err.Error()) 92 | } 93 | } else { 94 | log.Printf("AttachShell\n") 95 | if err := c.AttachShell(); err != nil { 96 | log.Fatalf("ERROR: %s\n", err.Error()) 97 | } 98 | 99 | log.Printf("RunCommand\n") 100 | if _, err := c.RunCommand(os.Stdin.Fd(), stdoutWriter.Fd(), stderrWriter.Fd(), "uname", "-a"); err != nil { 101 | log.Fatalf("ERROR: %s\n", err.Error()) 102 | } 103 | } 104 | 105 | if err := stdoutWriter.Close(); err != nil { 106 | log.Fatalf("ERROR: %s\n", err.Error()) 107 | } 108 | if err := stderrWriter.Close(); err != nil { 109 | log.Fatalf("ERROR: %s\n", err.Error()) 110 | } 111 | 112 | wg.Wait() 113 | } 114 | -------------------------------------------------------------------------------- /examples/stats.go: -------------------------------------------------------------------------------- 1 | /* 2 | * stats.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "log" 28 | 29 | "gopkg.in/lxc/go-lxc.v1" 30 | ) 31 | 32 | var ( 33 | lxcpath string 34 | name string 35 | ) 36 | 37 | func init() { 38 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 39 | flag.StringVar(&name, "name", "rubik", "Name of the container") 40 | flag.Parse() 41 | } 42 | 43 | func main() { 44 | c, err := lxc.NewContainer(name, lxcpath) 45 | if err != nil { 46 | log.Fatalf("ERROR: %s\n", err.Error()) 47 | } 48 | defer lxc.PutContainer(c) 49 | 50 | // mem 51 | memUsed, err := c.MemoryUsage() 52 | if err != nil { 53 | log.Fatalf("ERROR: %s\n", err.Error()) 54 | } else { 55 | log.Printf("MemoryUsage: %s\n", memUsed) 56 | } 57 | 58 | memLimit, err := c.MemoryLimit() 59 | if err != nil { 60 | log.Fatalf("ERROR: %s\n", err.Error()) 61 | } else { 62 | log.Printf("MemoryLimit: %s\n", memLimit) 63 | } 64 | 65 | // kmem 66 | kmemUsed, err := c.KernelMemoryUsage() 67 | if err != nil { 68 | log.Fatalf("ERROR: %s\n", err.Error()) 69 | } else { 70 | log.Printf("KernelMemoryUsage: %s\n", kmemUsed) 71 | } 72 | 73 | kmemLimit, err := c.KernelMemoryLimit() 74 | if err != nil { 75 | log.Fatalf("ERROR: %s\n", err.Error()) 76 | } else { 77 | log.Printf("KernelMemoryLimit: %s\n", kmemLimit) 78 | } 79 | 80 | // swap 81 | swapUsed, err := c.MemorySwapUsage() 82 | if err != nil { 83 | log.Fatalf("ERROR: %s\n", err.Error()) 84 | } else { 85 | log.Printf("MemorySwapUsage: %s\n", swapUsed) 86 | } 87 | 88 | swapLimit, err := c.MemorySwapLimit() 89 | if err != nil { 90 | log.Fatalf("ERROR: %s\n", err.Error()) 91 | } else { 92 | log.Printf("MemorySwapLimit: %s\n", swapLimit) 93 | } 94 | 95 | // blkio 96 | blkioUsage, err := c.BlkioUsage() 97 | if err != nil { 98 | log.Fatalf("ERROR: %s\n", err.Error()) 99 | } else { 100 | log.Printf("BlkioUsage: %s\n", blkioUsage) 101 | } 102 | 103 | cpuTime, err := c.CPUTime() 104 | if err != nil { 105 | log.Fatalf("ERROR: %s\n", err.Error()) 106 | } 107 | log.Printf("cpuacct.usage: %s\n", cpuTime) 108 | 109 | cpuTimePerCPU, err := c.CPUTimePerCPU() 110 | if err != nil { 111 | log.Fatalf("ERROR: %s\n", err.Error()) 112 | } 113 | log.Printf("cpuacct.usageerrpercpu: %v\n", cpuTimePerCPU) 114 | 115 | cpuStats, err := c.CPUStats() 116 | if err != nil { 117 | log.Fatalf("ERROR: %s\n", err.Error()) 118 | } 119 | log.Printf("cpuacct.stat: %v\n", cpuStats) 120 | 121 | interfaceStats, err := c.InterfaceStats() 122 | if err != nil { 123 | log.Fatalf("ERROR: %s\n", err.Error()) 124 | } 125 | log.Printf("InterfaceStats: %v\n", interfaceStats) 126 | } 127 | -------------------------------------------------------------------------------- /lxc.h: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 licence 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | extern bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); 9 | extern void go_lxc_clear_config(struct lxc_container *c); 10 | extern bool go_lxc_clear_config_item(struct lxc_container *c, const char *key); 11 | extern bool go_lxc_clone(struct lxc_container *c, const char *newname, int flags, const char *bdevtype); 12 | extern bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape); 13 | extern bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]); 14 | extern bool go_lxc_defined(struct lxc_container *c); 15 | extern bool go_lxc_destroy(struct lxc_container *c); 16 | extern bool go_lxc_freeze(struct lxc_container *c); 17 | extern bool go_lxc_load_config(struct lxc_container *c, const char *alt_file); 18 | extern bool go_lxc_may_control(struct lxc_container *c); 19 | extern bool go_lxc_reboot(struct lxc_container *c); 20 | extern bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); 21 | extern bool go_lxc_rename(struct lxc_container *c, const char *newname); 22 | extern bool go_lxc_running(struct lxc_container *c); 23 | extern bool go_lxc_save_config(struct lxc_container *c, const char *alt_file); 24 | extern bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value); 25 | extern bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value); 26 | extern bool go_lxc_set_config_path(struct lxc_container *c, const char *path); 27 | extern bool go_lxc_shutdown(struct lxc_container *c, int timeout); 28 | extern bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname); 29 | extern bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname); 30 | extern bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]); 31 | extern bool go_lxc_stop(struct lxc_container *c); 32 | extern bool go_lxc_unfreeze(struct lxc_container *c); 33 | extern bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout); 34 | extern bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state); 35 | extern bool go_lxc_want_daemonize(struct lxc_container *c, bool state); 36 | extern char* go_lxc_config_file_name(struct lxc_container *c); 37 | extern char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key); 38 | extern char* go_lxc_get_config_item(struct lxc_container *c, const char *key); 39 | extern char** go_lxc_get_interfaces(struct lxc_container *c); 40 | extern char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope); 41 | extern char* go_lxc_get_keys(struct lxc_container *c, const char *key); 42 | extern char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key); 43 | extern const char* go_lxc_get_config_path(struct lxc_container *c); 44 | extern const char* go_lxc_state(struct lxc_container *c); 45 | extern int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int stdinfd, int stdoutfd, int stderrfd, const char * const argv[]); 46 | extern int go_lxc_attach(struct lxc_container *c, bool clear_env); 47 | extern int go_lxc_console_getfd(struct lxc_container *c, int ttynum); 48 | extern int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret); 49 | extern int go_lxc_snapshot(struct lxc_container *c); 50 | extern pid_t go_lxc_init_pid(struct lxc_container *c); 51 | -------------------------------------------------------------------------------- /examples/concurrent_stress.go: -------------------------------------------------------------------------------- 1 | /* 2 | * concurrent_stress.go 3 | * 4 | * Copyright © 2013, 2014, S.Çağlar Onur 5 | * 6 | * Authors: 7 | * S.Çağlar Onur 8 | * 9 | * This library is free software; you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License version 2, as 11 | * published by the Free Software Foundation. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License along 19 | * with this program; if not, write to the Free Software Foundation, Inc., 20 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 21 | */ 22 | 23 | package main 24 | 25 | import ( 26 | "flag" 27 | "io/ioutil" 28 | "log" 29 | "runtime" 30 | "strconv" 31 | "sync" 32 | 33 | "gopkg.in/lxc/go-lxc.v1" 34 | ) 35 | 36 | var ( 37 | lxcpath string 38 | iteration int 39 | threads int 40 | template string 41 | quiet bool 42 | startstop bool 43 | createdestroy bool 44 | ) 45 | 46 | func init() { 47 | runtime.GOMAXPROCS(runtime.NumCPU()) 48 | 49 | flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") 50 | flag.StringVar(&template, "template", "busybox", "Template to use") 51 | flag.IntVar(&threads, "threads", 10, "Number of operations to run concurrently") 52 | flag.IntVar(&iteration, "iteration", 1, "Number times to run the test") 53 | flag.BoolVar(&quiet, "quiet", false, "Don't produce any output") 54 | flag.BoolVar(&startstop, "startstop", false, "Flag to execute Start and Stop") 55 | flag.BoolVar(&createdestroy, "createdestroy", false, "Flag to execute Create and Destroy") 56 | flag.Parse() 57 | } 58 | 59 | func main() { 60 | if quiet { 61 | log.SetOutput(ioutil.Discard) 62 | } 63 | log.Printf("Using %d GOMAXPROCS\n", runtime.NumCPU()) 64 | 65 | var wg sync.WaitGroup 66 | 67 | for i := 0; i < iteration; i++ { 68 | log.Printf("-- ITERATION %d --\n", i+1) 69 | for _, mode := range []string{"CREATE", "START", "STOP", "DESTROY"} { 70 | log.Printf("\t-- %s --\n", mode) 71 | for j := 0; j < threads; j++ { 72 | wg.Add(1) 73 | go func(i int, mode string) { 74 | c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) 75 | if err != nil { 76 | log.Fatalf("ERROR: %s\n", err.Error()) 77 | } 78 | defer lxc.PutContainer(c) 79 | 80 | if mode == "CREATE" && startstop == false { 81 | log.Printf("\t\tCreating the container (%d)...\n", i) 82 | if err := c.Create(template); err != nil { 83 | log.Fatalf("\t\t\tERROR: %s\n", err.Error()) 84 | } 85 | } else if mode == "START" && createdestroy == false { 86 | log.Printf("\t\tStarting the container (%d)...\n", i) 87 | if err := c.Start(); err != nil { 88 | log.Fatalf("\t\t\tERROR: %s\n", err.Error()) 89 | } 90 | } else if mode == "STOP" && createdestroy == false { 91 | log.Printf("\t\tStoping the container (%d)...\n", i) 92 | if err := c.Stop(); err != nil { 93 | log.Fatalf("\t\t\tERROR: %s\n", err.Error()) 94 | } 95 | } else if mode == "DESTROY" && startstop == false { 96 | log.Printf("\t\tDestroying the container (%d)...\n", i) 97 | if err := c.Destroy(); err != nil { 98 | log.Fatalf("\t\t\tERROR: %s\n", err.Error()) 99 | } 100 | } 101 | wg.Done() 102 | }(j, mode) 103 | } 104 | wg.Wait() 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | // Fatih Arslan 8 | 9 | // +build linux 10 | 11 | package lxc 12 | 13 | var ( 14 | ErrAllocationFailed = NewError("allocating memory failed") 15 | ErrAddDeviceNodeFailed = NewError("adding device to container failed") 16 | ErrAlreadyDefined = NewError("container already defined") 17 | ErrAlreadyFrozen = NewError("container is already frozen") 18 | ErrAlreadyRunning = NewError("container is already running") 19 | ErrAttachFailed = NewError("attaching to the container failed") 20 | ErrBlkioUsage = NewError("BlkioUsage for the container failed") 21 | ErrClearingCgroupItemFailed = NewError("clearing cgroup item for the container failed") 22 | ErrCloneFailed = NewError("cloning the container failed") 23 | ErrCloseAllFdsFailed = NewError("setting close_all_fds flag for container failed") 24 | ErrCreateFailed = NewError("creating the container failed") 25 | ErrCreateSnapshotFailed = NewError("snapshotting the container failed") 26 | ErrDaemonizeFailed = NewError("setting daemonize flag for container failed") 27 | ErrDestroyFailed = NewError("destroying the container failed") 28 | ErrDestroySnapshotFailed = NewError("destroying the snapshot failed") 29 | ErrExecuteFailed = NewError("executing the command in a temporary container failed") 30 | ErrFreezeFailed = NewError("freezing the container failed") 31 | ErrInsufficientNumberOfArguments = NewError("insufficient number of arguments were supplied") 32 | ErrInterfaces = NewError("getting interface names for the container failed") 33 | ErrIPAddresses = NewError("getting IP addresses of the container failed") 34 | ErrIPAddress = NewError("getting IP address on the interface of the container failed") 35 | ErrIPv4Addresses = NewError("getting IPv4 addresses of the container failed") 36 | ErrIPv6Addresses = NewError("getting IPv6 addresses of the container failed") 37 | ErrKMemLimit = NewError("your kernel does not support cgroup kernel memory controller") 38 | ErrLoadConfigFailed = NewError("loading config file for the container failed") 39 | ErrMemLimit = NewError("your kernel does not support cgroup memory controller") 40 | ErrSoftMemLimit = NewError("your kernel does not support cgroup memory controller") 41 | ErrMemorySwapLimit = NewError("your kernel does not support cgroup swap controller") 42 | ErrNewFailed = NewError("allocating the container failed") 43 | ErrNoSnapshot = NewError("container has no snapshot") 44 | ErrNotDefined = NewError("container is not defined") 45 | ErrNotFrozen = NewError("container is not frozen") 46 | ErrNotRunning = NewError("container is not running") 47 | ErrRebootFailed = NewError("rebooting the container failed") 48 | ErrRemoveDeviceNodeFailed = NewError("removing device from container failed") 49 | ErrRenameFailed = NewError("renaming the container failed") 50 | ErrRestoreSnapshotFailed = NewError("restoring the container failed") 51 | ErrSaveConfigFailed = NewError("saving config file for the container failed") 52 | ErrSettingCgroupItemFailed = NewError("setting cgroup item for the container failed") 53 | ErrSettingConfigItemFailed = NewError("setting config item for the container failed") 54 | ErrSettingConfigPathFailed = NewError("setting config file for the container failed") 55 | ErrSettingKMemoryLimitFailed = NewError("setting kernel memory limit for the container failed") 56 | ErrSettingMemoryLimitFailed = NewError("setting memory limit for the container failed") 57 | ErrSettingSoftMemoryLimitFailed = NewError("setting soft memory limit for the container failed") 58 | ErrSettingMemorySwapLimitFailed = NewError("setting memroy+swap limit for the container failed") 59 | ErrShutdownFailed = NewError("shutting down the container failed") 60 | ErrStartFailed = NewError("starting the container failed") 61 | ErrStopFailed = NewError("stopping the container failed") 62 | ErrUnfreezeFailed = NewError("unfreezing the container failed") 63 | ) 64 | 65 | // Error represents a basic error that implies the error interface. 66 | type Error struct { 67 | Message string 68 | } 69 | 70 | // NewError creates a new error with the given msg argument. 71 | func NewError(msg string) error { 72 | return &Error{ 73 | Message: msg, 74 | } 75 | } 76 | 77 | func (e *Error) Error() string { 78 | return e.Message 79 | } 80 | -------------------------------------------------------------------------------- /lxc.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | // Package lxc provides Go Bindings for LXC (Linux Containers) C API. 11 | package lxc 12 | 13 | // #cgo pkg-config: lxc 14 | // #include 15 | // #include "lxc.h" 16 | import "C" 17 | 18 | import "unsafe" 19 | 20 | // NewContainer returns a new container struct. 21 | func NewContainer(name string, lxcpath ...string) (*Container, error) { 22 | var container *C.struct_lxc_container 23 | 24 | cname := C.CString(name) 25 | defer C.free(unsafe.Pointer(cname)) 26 | 27 | if lxcpath != nil && len(lxcpath) == 1 { 28 | clxcpath := C.CString(lxcpath[0]) 29 | defer C.free(unsafe.Pointer(clxcpath)) 30 | 31 | container = C.lxc_container_new(cname, clxcpath) 32 | } else { 33 | container = C.lxc_container_new(cname, nil) 34 | } 35 | 36 | if container == nil { 37 | return nil, ErrNewFailed 38 | } 39 | return &Container{container: container, verbosity: Quiet}, nil 40 | } 41 | 42 | // GetContainer increments the reference counter of the container object. 43 | func GetContainer(c *Container) bool { 44 | return C.lxc_container_get(c.container) == 1 45 | } 46 | 47 | // PutContainer decrements the reference counter of the container object. 48 | func PutContainer(c *Container) bool { 49 | return C.lxc_container_put(c.container) == 1 50 | } 51 | 52 | // Version returns the LXC version. 53 | func Version() string { 54 | return C.GoString(C.lxc_get_version()) 55 | } 56 | 57 | // GlobalConfigItem returns the value of the given global config key. 58 | func GlobalConfigItem(name string) string { 59 | cname := C.CString(name) 60 | defer C.free(unsafe.Pointer(cname)) 61 | 62 | return C.GoString(C.lxc_get_global_config_item(cname)) 63 | } 64 | 65 | // DefaultConfigPath returns default config path. 66 | func DefaultConfigPath() string { 67 | return GlobalConfigItem("lxc.lxcpath") 68 | } 69 | 70 | // DefaultLvmVg returns the name of the default LVM volume group. 71 | func DefaultLvmVg() string { 72 | return GlobalConfigItem("lxc.bdev.lvm.vg") 73 | } 74 | 75 | // DefaultZfsRoot returns the name of the default ZFS root. 76 | func DefaultZfsRoot() string { 77 | return GlobalConfigItem("lxc.bdec.zfs.root") 78 | } 79 | 80 | // ContainerNames returns the names of defined and active containers on the system. 81 | func ContainerNames(lxcpath ...string) []string { 82 | var size int 83 | var cnames **C.char 84 | 85 | if lxcpath != nil && len(lxcpath) == 1 { 86 | clxcpath := C.CString(lxcpath[0]) 87 | defer C.free(unsafe.Pointer(clxcpath)) 88 | 89 | size = int(C.list_all_containers(clxcpath, &cnames, nil)) 90 | } else { 91 | 92 | size = int(C.list_all_containers(nil, &cnames, nil)) 93 | } 94 | 95 | if size < 1 { 96 | return nil 97 | } 98 | return convertNArgs(cnames, size) 99 | } 100 | 101 | // Containers returns the defined and active containers on the system. Only 102 | // containers that could retrieved successfully are returned. 103 | func Containers(lxcpath ...string) []Container { 104 | var containers []Container 105 | 106 | for _, v := range ContainerNames(lxcpath...) { 107 | if container, err := NewContainer(v, lxcpath...); err == nil { 108 | containers = append(containers, *container) 109 | } 110 | } 111 | 112 | return containers 113 | } 114 | 115 | // DefinedContainerNames returns the names of the defined containers on the system. 116 | func DefinedContainerNames(lxcpath ...string) []string { 117 | var size int 118 | var cnames **C.char 119 | 120 | if lxcpath != nil && len(lxcpath) == 1 { 121 | clxcpath := C.CString(lxcpath[0]) 122 | defer C.free(unsafe.Pointer(clxcpath)) 123 | 124 | size = int(C.list_defined_containers(clxcpath, &cnames, nil)) 125 | } else { 126 | 127 | size = int(C.list_defined_containers(nil, &cnames, nil)) 128 | } 129 | 130 | if size < 1 { 131 | return nil 132 | } 133 | return convertNArgs(cnames, size) 134 | } 135 | 136 | // DefinedContainers returns the defined containers on the system. Only 137 | // containers that could retrieved successfully are returned. 138 | func DefinedContainers(lxcpath ...string) []Container { 139 | var containers []Container 140 | 141 | for _, v := range DefinedContainerNames(lxcpath...) { 142 | if container, err := NewContainer(v, lxcpath...); err == nil { 143 | containers = append(containers, *container) 144 | } 145 | } 146 | 147 | return containers 148 | } 149 | 150 | // ActiveContainerNames returns the names of the active containers on the system. 151 | func ActiveContainerNames(lxcpath ...string) []string { 152 | var size int 153 | var cnames **C.char 154 | 155 | if lxcpath != nil && len(lxcpath) == 1 { 156 | clxcpath := C.CString(lxcpath[0]) 157 | defer C.free(unsafe.Pointer(clxcpath)) 158 | 159 | size = int(C.list_active_containers(clxcpath, &cnames, nil)) 160 | } else { 161 | 162 | size = int(C.list_active_containers(nil, &cnames, nil)) 163 | } 164 | 165 | if size < 1 { 166 | return nil 167 | } 168 | return convertNArgs(cnames, size) 169 | } 170 | 171 | // ActiveContainers returns the active containers on the system. Only 172 | // containers that could retrieved successfully are returned. 173 | func ActiveContainers(lxcpath ...string) []Container { 174 | var containers []Container 175 | 176 | for _, v := range ActiveContainerNames(lxcpath...) { 177 | if container, err := NewContainer(v, lxcpath...); err == nil { 178 | containers = append(containers, *container) 179 | } 180 | } 181 | 182 | return containers 183 | } 184 | -------------------------------------------------------------------------------- /type.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | package lxc 11 | 12 | // #include 13 | import "C" 14 | 15 | import ( 16 | "fmt" 17 | ) 18 | 19 | // Verbosity type 20 | type Verbosity int 21 | 22 | const ( 23 | // Quiet makes some API calls not to write anything to stdout 24 | Quiet Verbosity = 1 << iota 25 | // Verbose makes some API calls write to stdout 26 | Verbose 27 | ) 28 | 29 | // BackendStore type specifies possible backend types. 30 | type BackendStore int 31 | 32 | const ( 33 | // Btrfs backendstore type 34 | Btrfs BackendStore = iota + 1 35 | // Directory backendstore type 36 | Directory 37 | // LVM backendstore type 38 | LVM 39 | // ZFS backendstore type 40 | ZFS 41 | // Aufs backendstore type 42 | Aufs 43 | // Overlayfs backendstore type 44 | Overlayfs 45 | // Loopback backendstore type 46 | Loopback 47 | // Best backendstore type 48 | Best 49 | ) 50 | 51 | // BackendStore as string 52 | func (t BackendStore) String() string { 53 | switch t { 54 | case Directory: 55 | return "dir" 56 | case ZFS: 57 | return "zfs" 58 | case Btrfs: 59 | return "btrfs" 60 | case LVM: 61 | return "lvm" 62 | case Aufs: 63 | return "aufs" 64 | case Overlayfs: 65 | return "overlayfs" 66 | case Loopback: 67 | return "loopback" 68 | case Best: 69 | return "best" 70 | } 71 | return "" 72 | } 73 | 74 | // State type specifies possible container states. 75 | type State int 76 | 77 | const ( 78 | // STOPPED means container is not running 79 | STOPPED State = iota + 1 80 | // STARTING means container is starting 81 | STARTING 82 | // RUNNING means container is running 83 | RUNNING 84 | // STOPPING means container is stopping 85 | STOPPING 86 | // ABORTING means container is aborting 87 | ABORTING 88 | // FREEZING means container is freezing 89 | FREEZING 90 | // FROZEN means containe is frozen 91 | FROZEN 92 | // THAWED means container is thawed 93 | THAWED 94 | ) 95 | 96 | var stateMap = map[string]State{ 97 | "STOPPED": STOPPED, 98 | "STARTING": STARTING, 99 | "RUNNING": RUNNING, 100 | "STOPPING": STOPPING, 101 | "ABORTING": ABORTING, 102 | "FREEZING": FREEZING, 103 | "FROZEN": FROZEN, 104 | "THAWED": THAWED, 105 | } 106 | 107 | // State as string 108 | func (t State) String() string { 109 | switch t { 110 | case STOPPED: 111 | return "STOPPED" 112 | case STARTING: 113 | return "STARTING" 114 | case RUNNING: 115 | return "RUNNING" 116 | case STOPPING: 117 | return "STOPPING" 118 | case ABORTING: 119 | return "ABORTING" 120 | case FREEZING: 121 | return "FREEZING" 122 | case FROZEN: 123 | return "FROZEN" 124 | case THAWED: 125 | return "THAWED" 126 | } 127 | return "" 128 | } 129 | 130 | // Taken from http://golang.org/doc/effective_go.html#constants 131 | 132 | // ByteSize type 133 | type ByteSize float64 134 | 135 | const ( 136 | _ = iota 137 | // KB - kilobyte 138 | KB ByteSize = 1 << (10 * iota) 139 | // MB - megabyte 140 | MB 141 | // GB - gigabyte 142 | GB 143 | // TB - terabyte 144 | TB 145 | // PB - petabyte 146 | PB 147 | // EB - exabyte 148 | EB 149 | // ZB - zettabyte 150 | ZB 151 | // YB - yottabyte 152 | YB 153 | ) 154 | 155 | func (b ByteSize) String() string { 156 | switch { 157 | case b >= YB: 158 | return fmt.Sprintf("%.2fYB", b/YB) 159 | case b >= ZB: 160 | return fmt.Sprintf("%.2fZB", b/ZB) 161 | case b >= EB: 162 | return fmt.Sprintf("%.2fEB", b/EB) 163 | case b >= PB: 164 | return fmt.Sprintf("%.2fPB", b/PB) 165 | case b >= TB: 166 | return fmt.Sprintf("%.2fTB", b/TB) 167 | case b >= GB: 168 | return fmt.Sprintf("%.2fGB", b/GB) 169 | case b >= MB: 170 | return fmt.Sprintf("%.2fMB", b/MB) 171 | case b >= KB: 172 | return fmt.Sprintf("%.2fKB", b/KB) 173 | } 174 | return fmt.Sprintf("%.2fB", b) 175 | } 176 | 177 | // LogLevel type specifies possible log levels. 178 | type LogLevel int 179 | 180 | const ( 181 | // TRACE priority 182 | TRACE LogLevel = iota 183 | // DEBUG priority 184 | DEBUG 185 | // INFO priority 186 | INFO 187 | // NOTICE priority 188 | NOTICE 189 | // WARN priority 190 | WARN 191 | // ERROR priority 192 | ERROR 193 | // CRIT priority 194 | CRIT 195 | // ALERT priority 196 | ALERT 197 | // FATAL priority 198 | FATAL 199 | ) 200 | 201 | var logLevelMap = map[string]LogLevel{ 202 | "TRACE": TRACE, 203 | "DEBUG": DEBUG, 204 | "INFO": INFO, 205 | "NOTICE": NOTICE, 206 | "WARN": WARN, 207 | "ERROR": ERROR, 208 | "CRIT": CRIT, 209 | "ALERT": ALERT, 210 | "FATAL": FATAL, 211 | } 212 | 213 | func (l LogLevel) String() string { 214 | switch l { 215 | case TRACE: 216 | return "TRACE" 217 | case DEBUG: 218 | return "DEBUG" 219 | case INFO: 220 | return "INFO" 221 | case NOTICE: 222 | return "NOTICE" 223 | case WARN: 224 | return "WARN" 225 | case ERROR: 226 | return "ERROR" 227 | case CRIT: 228 | return "CRIT" 229 | case ALERT: 230 | return "ALERT" 231 | case FATAL: 232 | return "FATAL" 233 | } 234 | return "NOTSET" 235 | } 236 | 237 | // CloneFlags type 238 | type CloneFlags int 239 | 240 | const ( 241 | // CloneKeepName means do not edit the rootfs to change the hostname 242 | CloneKeepName CloneFlags = 1 << iota 243 | // CloneKeepMACAddr means do not change the mac address on network interfaces 244 | CloneKeepMACAddr 245 | // CloneSnapshot means snapshot the original filesystem(s) 246 | CloneSnapshot 247 | // CloneKeepBdevType means use the same bdev type 248 | CloneKeepBdevType 249 | // CloneMaybeSnapshot means snapshot only if bdev supports it, else copy 250 | CloneMaybeSnapshot 251 | ) 252 | -------------------------------------------------------------------------------- /lxc.c: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | #include 11 | 12 | #include 13 | #include 14 | 15 | bool go_lxc_defined(struct lxc_container *c) { 16 | return c->is_defined(c); 17 | } 18 | 19 | const char* go_lxc_state(struct lxc_container *c) { 20 | return c->state(c); 21 | } 22 | 23 | bool go_lxc_running(struct lxc_container *c) { 24 | return c->is_running(c); 25 | } 26 | 27 | bool go_lxc_freeze(struct lxc_container *c) { 28 | return c->freeze(c); 29 | } 30 | 31 | bool go_lxc_unfreeze(struct lxc_container *c) { 32 | return c->unfreeze(c); 33 | } 34 | 35 | pid_t go_lxc_init_pid(struct lxc_container *c) { 36 | return c->init_pid(c); 37 | } 38 | 39 | bool go_lxc_want_daemonize(struct lxc_container *c, bool state) { 40 | return c->want_daemonize(c, state); 41 | } 42 | 43 | bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state) { 44 | return c->want_close_all_fds(c, state); 45 | } 46 | 47 | bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]) { 48 | return c->create(c, t, bdevtype, NULL, !!(flags & LXC_CREATE_QUIET), argv); 49 | } 50 | 51 | bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]) { 52 | return c->start(c, useinit, argv); 53 | } 54 | 55 | bool go_lxc_stop(struct lxc_container *c) { 56 | return c->stop(c); 57 | } 58 | 59 | bool go_lxc_reboot(struct lxc_container *c) { 60 | return c->reboot(c); 61 | } 62 | 63 | bool go_lxc_shutdown(struct lxc_container *c, int timeout) { 64 | return c->shutdown(c, timeout); 65 | } 66 | 67 | char* go_lxc_config_file_name(struct lxc_container *c) { 68 | return c->config_file_name(c); 69 | } 70 | 71 | bool go_lxc_destroy(struct lxc_container *c) { 72 | return c->destroy(c); 73 | } 74 | 75 | bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout) { 76 | return c->wait(c, state, timeout); 77 | } 78 | 79 | char* go_lxc_get_config_item(struct lxc_container *c, const char *key) { 80 | int len = c->get_config_item(c, key, NULL, 0); 81 | if (len <= 0) { 82 | return NULL; 83 | } 84 | 85 | char* value = (char*)malloc(sizeof(char)*len + 1); 86 | if (c->get_config_item(c, key, value, len + 1) != len) { 87 | return NULL; 88 | } 89 | return value; 90 | } 91 | 92 | bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value) { 93 | return c->set_config_item(c, key, value); 94 | } 95 | 96 | void go_lxc_clear_config(struct lxc_container *c) { 97 | c->clear_config(c); 98 | } 99 | 100 | bool go_lxc_clear_config_item(struct lxc_container *c, const char *key) { 101 | return c->clear_config_item(c, key); 102 | } 103 | 104 | char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key) { 105 | return c->get_running_config_item(c, key); 106 | } 107 | 108 | char* go_lxc_get_keys(struct lxc_container *c, const char *key) { 109 | int len = c->get_keys(c, key, NULL, 0); 110 | if (len <= 0) { 111 | return NULL; 112 | } 113 | 114 | char* value = (char*)malloc(sizeof(char)*len + 1); 115 | if (c->get_keys(c, key, value, len + 1) != len) { 116 | return NULL; 117 | } 118 | return value; 119 | } 120 | 121 | char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key) { 122 | int len = c->get_cgroup_item(c, key, NULL, 0); 123 | if (len <= 0) { 124 | return NULL; 125 | } 126 | 127 | char* value = (char*)malloc(sizeof(char)*len + 1); 128 | if (c->get_cgroup_item(c, key, value, len + 1) != len) { 129 | return NULL; 130 | } 131 | return value; 132 | } 133 | 134 | bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value) { 135 | return c->set_cgroup_item(c, key, value); 136 | } 137 | 138 | const char* go_lxc_get_config_path(struct lxc_container *c) { 139 | return c->get_config_path(c); 140 | } 141 | 142 | bool go_lxc_set_config_path(struct lxc_container *c, const char *path) { 143 | return c->set_config_path(c, path); 144 | } 145 | 146 | bool go_lxc_load_config(struct lxc_container *c, const char *alt_file) { 147 | return c->load_config(c, alt_file); 148 | } 149 | 150 | bool go_lxc_save_config(struct lxc_container *c, const char *alt_file) { 151 | return c->save_config(c, alt_file); 152 | } 153 | 154 | bool go_lxc_clone(struct lxc_container *c, const char *newname, int flags, const char *bdevtype) { 155 | return c->clone(c, newname, NULL, flags, bdevtype, NULL, 0, NULL) != NULL; 156 | } 157 | 158 | int go_lxc_console_getfd(struct lxc_container *c, int ttynum) { 159 | int masterfd; 160 | 161 | if (c->console_getfd(c, &ttynum, &masterfd) < 0) { 162 | return -1; 163 | } 164 | return masterfd; 165 | } 166 | 167 | bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape) { 168 | 169 | if (c->console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape) == 0) { 170 | return true; 171 | } 172 | return false; 173 | } 174 | 175 | char** go_lxc_get_interfaces(struct lxc_container *c) { 176 | return c->get_interfaces(c); 177 | } 178 | 179 | char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope) { 180 | return c->get_ips(c, interface, family, scope); 181 | } 182 | 183 | int go_lxc_attach(struct lxc_container *c, bool clear_env) { 184 | int ret; 185 | pid_t pid; 186 | lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; 187 | 188 | attach_options.env_policy = LXC_ATTACH_KEEP_ENV; 189 | if (clear_env) { 190 | attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; 191 | } 192 | 193 | /* 194 | remount_sys_proc 195 | 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. 196 | default_options.attach_flags |= LXC_ATTACH_REMOUNT_PROC_SYS; 197 | 198 | elevated_privileges 199 | 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. 200 | default_options.attach_flags &= ~(LXC_ATTACH_MOVE_TO_CGROUP | LXC_ATTACH_DROP_CAPABILITIES | LXC_ATTACH_APPARMOR); 201 | 202 | Specify the namespaces to attach to, as a pipe-separated list, e.g. NETWORK|IPC. Allowed values are MOUNT, PID, UTSNAME, IPC, USER and NETWORK. 203 | default_options.namespaces = namespace_flags; // lxc_fill_namespace_flags(arg, &namespace_flags); 204 | 205 | Specify the architecture which the kernel should appear to be running as to the command executed. 206 | default_options.personality = new_personality; // lxc_config_parse_arch(arg); 207 | 208 | Keep the current environment for attached programs. 209 | Clear the environment before attaching, so no undesired environment variables leak into the container. 210 | 211 | default_options.env_policy = env_policy; // LXC_ATTACH_KEEP_ENV or LXC_ATTACH_CLEAR_ENV 212 | 213 | default_options.extra_env_vars = extra_env; 214 | default_options.extra_keep_env = extra_keep; 215 | */ 216 | 217 | ret = c->attach(c, lxc_attach_run_shell, NULL, &attach_options, &pid); 218 | if (ret < 0) 219 | return -1; 220 | 221 | ret = lxc_wait_for_pid_status(pid); 222 | if (ret < 0) 223 | return -1; 224 | 225 | if (WIFEXITED(ret)) 226 | return WEXITSTATUS(ret); 227 | 228 | return -1; 229 | } 230 | 231 | int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int stdinfd, int stdoutfd, int stderrfd, const char * const argv[]) { 232 | int ret; 233 | lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; 234 | 235 | attach_options.env_policy = LXC_ATTACH_KEEP_ENV; 236 | if (clear_env) { 237 | attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; 238 | } 239 | attach_options.stdin_fd = stdinfd; 240 | attach_options.stdout_fd = stdoutfd; 241 | attach_options.stderr_fd = stderrfd; 242 | 243 | ret = c->attach_run_wait(c, &attach_options, argv[0], argv); 244 | if (WIFEXITED(ret) && WEXITSTATUS(ret) == 255) 245 | return -1; 246 | return ret; 247 | } 248 | 249 | bool go_lxc_may_control(struct lxc_container *c) { 250 | return c->may_control(c); 251 | } 252 | 253 | int go_lxc_snapshot(struct lxc_container *c) { 254 | return c->snapshot(c, NULL); 255 | } 256 | 257 | int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret) { 258 | return c->snapshot_list(c, ret); 259 | } 260 | 261 | bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname) { 262 | return c->snapshot_restore(c, snapname, newname); 263 | } 264 | 265 | bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname) { 266 | return c->snapshot_destroy(c, snapname); 267 | } 268 | 269 | bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { 270 | return c->add_device_node(c, src_path, dest_path); 271 | } 272 | 273 | bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { 274 | return c->remove_device_node(c, src_path, dest_path); 275 | } 276 | 277 | bool go_lxc_rename(struct lxc_container *c, const char *newname) { 278 | return c->rename(c, newname); 279 | } 280 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /lxc_test.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | package lxc 11 | 12 | import ( 13 | "math/rand" 14 | "os" 15 | "runtime" 16 | "strconv" 17 | "strings" 18 | "sync" 19 | "testing" 20 | "time" 21 | ) 22 | 23 | const ( 24 | ContainerType = "busybox" 25 | ContainerName = "lorem" 26 | SnapshotName = "snap0" 27 | ContainerRestoreName = "ipsum" 28 | ContainerCloneName = "consectetur" 29 | ContainerCloneOverlayName = "adipiscing" 30 | ContainerCloneAufsName = "pellentesque" 31 | // used by unprivileged test cases 32 | UnprivilegedContainerType = "ubuntu" 33 | UnprivilegedRelease = "trusty" 34 | UnprivilegedArch = "amd64" 35 | ) 36 | 37 | func unprivileged() bool { 38 | if os.Geteuid() != 0 { 39 | return true 40 | } 41 | return false 42 | } 43 | 44 | func supported(moduleName string) bool { 45 | if _, err := os.Stat("/sys/module/" + moduleName); err != nil { 46 | return false 47 | } 48 | return true 49 | } 50 | 51 | func TestVersion(t *testing.T) { 52 | t.Logf("LXC version: %s", Version()) 53 | } 54 | 55 | func TestDefaultConfigPath(t *testing.T) { 56 | if DefaultConfigPath() == "" { 57 | t.Errorf("DefaultConfigPath failed...") 58 | } 59 | } 60 | 61 | func TestSetConfigPath(t *testing.T) { 62 | c, err := NewContainer(ContainerName) 63 | if err != nil { 64 | t.Errorf(err.Error()) 65 | } 66 | defer PutContainer(c) 67 | 68 | currentPath := c.ConfigPath() 69 | if err := c.SetConfigPath("/tmp"); err != nil { 70 | t.Errorf(err.Error()) 71 | } 72 | newPath := c.ConfigPath() 73 | 74 | if currentPath == newPath { 75 | t.Errorf("SetConfigPath failed...") 76 | } 77 | } 78 | 79 | func TestGetContainer(t *testing.T) { 80 | c, err := NewContainer(ContainerName) 81 | if err != nil { 82 | t.Errorf(err.Error()) 83 | } 84 | defer PutContainer(c) 85 | 86 | GetContainer(c) 87 | PutContainer(c) 88 | } 89 | 90 | func TestConcurrentDefined_Negative(t *testing.T) { 91 | defer runtime.GOMAXPROCS(runtime.NumCPU()) 92 | 93 | var wg sync.WaitGroup 94 | 95 | for i := 0; i <= 100; i++ { 96 | wg.Add(1) 97 | go func() { 98 | c, err := NewContainer(strconv.Itoa(rand.Intn(10))) 99 | if err != nil { 100 | t.Errorf(err.Error()) 101 | } 102 | defer PutContainer(c) 103 | 104 | // sleep for a while to simulate some dummy work 105 | time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) 106 | 107 | if c.Defined() { 108 | t.Errorf("Defined_Negative failed...") 109 | } 110 | wg.Done() 111 | }() 112 | } 113 | wg.Wait() 114 | } 115 | 116 | func TestDefined_Negative(t *testing.T) { 117 | c, err := NewContainer(ContainerName) 118 | if err != nil { 119 | t.Errorf(err.Error()) 120 | } 121 | defer PutContainer(c) 122 | 123 | if c.Defined() { 124 | t.Errorf("Defined_Negative failed...") 125 | } 126 | } 127 | 128 | func TestExecute(t *testing.T) { 129 | if unprivileged() { 130 | t.Skip("skipping test in unprivileged mode.") 131 | } 132 | 133 | c, err := NewContainer(ContainerName) 134 | if err != nil { 135 | t.Errorf(err.Error()) 136 | } 137 | defer PutContainer(c) 138 | 139 | if _, err := c.Execute("/bin/true"); err != nil { 140 | t.Errorf(err.Error()) 141 | } 142 | } 143 | 144 | func TestSetVerbosity(t *testing.T) { 145 | c, err := NewContainer(ContainerName) 146 | if err != nil { 147 | t.Errorf(err.Error()) 148 | } 149 | defer PutContainer(c) 150 | 151 | c.SetVerbosity(Quiet) 152 | } 153 | 154 | func TestCreate(t *testing.T) { 155 | c, err := NewContainer(ContainerName) 156 | if err != nil { 157 | t.Errorf(err.Error()) 158 | } 159 | defer PutContainer(c) 160 | 161 | if unprivileged() { 162 | if err := c.CreateAsUser(UnprivilegedContainerType, UnprivilegedRelease, UnprivilegedArch); err != nil { 163 | t.Errorf("ERROR: %s\n", err.Error()) 164 | } 165 | } else { 166 | if err := c.Create(ContainerType); err != nil { 167 | t.Errorf(err.Error()) 168 | } 169 | } 170 | } 171 | 172 | func TestClone(t *testing.T) { 173 | c, err := NewContainer(ContainerName) 174 | if err != nil { 175 | t.Errorf(err.Error()) 176 | } 177 | defer PutContainer(c) 178 | 179 | if err := c.Clone(ContainerCloneName); err != nil { 180 | t.Errorf(err.Error()) 181 | } 182 | } 183 | 184 | func TestCloneUsingOverlayfs(t *testing.T) { 185 | if !supported("overlayfs") { 186 | t.Skip("skipping test as overlayfs support is missing.") 187 | } 188 | 189 | c, err := NewContainer(ContainerName) 190 | if err != nil { 191 | t.Errorf(err.Error()) 192 | } 193 | defer PutContainer(c) 194 | 195 | if err := c.CloneUsing(ContainerCloneOverlayName, Overlayfs, CloneSnapshot|CloneKeepName|CloneKeepMACAddr); err != nil { 196 | t.Errorf(err.Error()) 197 | } 198 | } 199 | 200 | func TestCloneUsingAufs(t *testing.T) { 201 | if unprivileged() { 202 | t.Skip("skipping test in unprivileged mode.") 203 | } 204 | 205 | if !supported("aufs") { 206 | t.Skip("skipping test as aufs support is missing.") 207 | } 208 | 209 | c, err := NewContainer(ContainerName) 210 | if err != nil { 211 | t.Errorf(err.Error()) 212 | } 213 | defer PutContainer(c) 214 | 215 | if err := c.CloneUsing(ContainerCloneAufsName, Aufs, CloneSnapshot|CloneKeepName|CloneKeepMACAddr); err != nil { 216 | t.Errorf(err.Error()) 217 | } 218 | } 219 | 220 | func TestCreateSnapshot(t *testing.T) { 221 | c, err := NewContainer(ContainerName) 222 | if err != nil { 223 | t.Errorf(err.Error()) 224 | } 225 | defer PutContainer(c) 226 | 227 | if _, err := c.CreateSnapshot(); err != nil { 228 | t.Errorf(err.Error()) 229 | } 230 | } 231 | 232 | func TestRestoreSnapshot(t *testing.T) { 233 | c, err := NewContainer(ContainerName) 234 | if err != nil { 235 | t.Errorf(err.Error()) 236 | } 237 | defer PutContainer(c) 238 | 239 | snapshot := Snapshot{Name: SnapshotName} 240 | if err := c.RestoreSnapshot(snapshot, ContainerRestoreName); err != nil { 241 | t.Errorf(err.Error()) 242 | } 243 | } 244 | 245 | func TestConcurrentCreate(t *testing.T) { 246 | defer runtime.GOMAXPROCS(runtime.NumCPU()) 247 | 248 | if unprivileged() { 249 | t.Skip("skipping test in unprivileged mode.") 250 | } 251 | 252 | var wg sync.WaitGroup 253 | 254 | for i := 0; i < 10; i++ { 255 | wg.Add(1) 256 | go func(i int) { 257 | c, err := NewContainer(strconv.Itoa(i)) 258 | if err != nil { 259 | t.Errorf(err.Error()) 260 | } 261 | defer PutContainer(c) 262 | 263 | // sleep for a while to simulate some dummy work 264 | time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) 265 | 266 | if err := c.Create(ContainerType); err != nil { 267 | t.Errorf(err.Error()) 268 | } 269 | wg.Done() 270 | }(i) 271 | } 272 | wg.Wait() 273 | } 274 | 275 | func TestSnapshots(t *testing.T) { 276 | c, err := NewContainer(ContainerName) 277 | if err != nil { 278 | t.Errorf(err.Error()) 279 | } 280 | defer PutContainer(c) 281 | 282 | if _, err := c.Snapshots(); err != nil { 283 | t.Errorf(err.Error()) 284 | } 285 | } 286 | 287 | func TestConcurrentStart(t *testing.T) { 288 | defer runtime.GOMAXPROCS(runtime.NumCPU()) 289 | 290 | if unprivileged() { 291 | t.Skip("skipping test in unprivileged mode.") 292 | } 293 | 294 | var wg sync.WaitGroup 295 | 296 | for i := 0; i < 10; i++ { 297 | wg.Add(1) 298 | go func(i int) { 299 | c, err := NewContainer(strconv.Itoa(i)) 300 | if err != nil { 301 | t.Errorf(err.Error()) 302 | } 303 | defer PutContainer(c) 304 | 305 | if err := c.Start(); err != nil { 306 | t.Errorf(err.Error()) 307 | } 308 | 309 | c.Wait(RUNNING, 30*time.Second) 310 | if !c.Running() { 311 | t.Errorf("Starting the container failed...") 312 | } 313 | 314 | wg.Done() 315 | }(i) 316 | } 317 | wg.Wait() 318 | } 319 | 320 | func TestConfigFileName(t *testing.T) { 321 | c, err := NewContainer(ContainerName) 322 | if err != nil { 323 | t.Errorf(err.Error()) 324 | } 325 | defer PutContainer(c) 326 | 327 | if c.ConfigFileName() == "" { 328 | t.Errorf("ConfigFileName failed...") 329 | } 330 | } 331 | 332 | func TestDefined_Positive(t *testing.T) { 333 | c, err := NewContainer(ContainerName) 334 | if err != nil { 335 | t.Errorf(err.Error()) 336 | } 337 | defer PutContainer(c) 338 | 339 | if !c.Defined() { 340 | t.Errorf("Defined_Positive failed...") 341 | } 342 | } 343 | 344 | func TestConcurrentDefined_Positive(t *testing.T) { 345 | defer runtime.GOMAXPROCS(runtime.NumCPU()) 346 | 347 | if unprivileged() { 348 | t.Skip("skipping test in unprivileged mode.") 349 | } 350 | 351 | var wg sync.WaitGroup 352 | 353 | for i := 0; i <= 100; i++ { 354 | wg.Add(1) 355 | go func() { 356 | c, err := NewContainer(strconv.Itoa(rand.Intn(10))) 357 | if err != nil { 358 | t.Errorf(err.Error()) 359 | } 360 | defer PutContainer(c) 361 | 362 | // sleep for a while to simulate some dummy work 363 | time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) 364 | 365 | if !c.Defined() { 366 | t.Errorf("Defined_Positive failed...") 367 | } 368 | wg.Done() 369 | }() 370 | } 371 | wg.Wait() 372 | } 373 | 374 | func TestInitPid_Negative(t *testing.T) { 375 | c, err := NewContainer(ContainerName) 376 | if err != nil { 377 | t.Errorf(err.Error()) 378 | } 379 | defer PutContainer(c) 380 | 381 | if c.InitPid() != -1 { 382 | t.Errorf("InitPid failed...") 383 | } 384 | } 385 | 386 | func TestStart(t *testing.T) { 387 | c, err := NewContainer(ContainerName) 388 | if err != nil { 389 | t.Errorf(err.Error()) 390 | } 391 | defer PutContainer(c) 392 | 393 | if err := c.Start(); err != nil { 394 | t.Errorf(err.Error()) 395 | } 396 | 397 | c.Wait(RUNNING, 30*time.Second) 398 | if !c.Running() { 399 | t.Errorf("Starting the container failed...") 400 | } 401 | } 402 | 403 | func TestControllable(t *testing.T) { 404 | c, err := NewContainer(ContainerName) 405 | if err != nil { 406 | t.Errorf(err.Error()) 407 | } 408 | defer PutContainer(c) 409 | 410 | if !c.Controllable() { 411 | t.Errorf("Controling the container failed...") 412 | } 413 | } 414 | 415 | func TestContainerNames(t *testing.T) { 416 | if ContainerNames() == nil { 417 | t.Errorf("ContainerNames failed...") 418 | } 419 | } 420 | 421 | func TestDefinedContainerNames(t *testing.T) { 422 | if DefinedContainerNames() == nil { 423 | t.Errorf("DefinedContainerNames failed...") 424 | } 425 | } 426 | 427 | func TestActiveContainerNames(t *testing.T) { 428 | if ActiveContainerNames() == nil { 429 | t.Errorf("ActiveContainerNames failed...") 430 | } 431 | } 432 | 433 | func TestContainers(t *testing.T) { 434 | if Containers() == nil { 435 | t.Errorf("Containers failed...") 436 | } 437 | } 438 | 439 | func TestDefinedContainers(t *testing.T) { 440 | if DefinedContainers() == nil { 441 | t.Errorf("DefinedContainers failed...") 442 | } 443 | } 444 | 445 | func TestActiveContainers(t *testing.T) { 446 | if ActiveContainers() == nil { 447 | t.Errorf("ActiveContainers failed...") 448 | } 449 | } 450 | 451 | func TestRunning(t *testing.T) { 452 | c, err := NewContainer(ContainerName) 453 | if err != nil { 454 | t.Errorf(err.Error()) 455 | } 456 | defer PutContainer(c) 457 | 458 | if !c.Running() { 459 | t.Errorf("Checking the container failed...") 460 | } 461 | } 462 | 463 | func TestWantDaemonize(t *testing.T) { 464 | c, err := NewContainer(ContainerName) 465 | if err != nil { 466 | t.Errorf(err.Error()) 467 | } 468 | defer PutContainer(c) 469 | 470 | if err := c.WantDaemonize(false); err != nil || c.Daemonize() { 471 | t.Errorf("WantDaemonize failed...") 472 | } 473 | } 474 | 475 | func TestWantCloseAllFds(t *testing.T) { 476 | c, err := NewContainer(ContainerName) 477 | if err != nil { 478 | t.Errorf(err.Error()) 479 | } 480 | defer PutContainer(c) 481 | 482 | if err := c.WantCloseAllFds(true); err != nil { 483 | t.Errorf("WantCloseAllFds failed...") 484 | } 485 | } 486 | 487 | func TestSetLogLevel(t *testing.T) { 488 | c, err := NewContainer(ContainerName) 489 | if err != nil { 490 | t.Errorf(err.Error()) 491 | } 492 | defer PutContainer(c) 493 | 494 | if err := c.SetLogLevel(WARN); err != nil || c.LogLevel() != WARN { 495 | t.Errorf("SetLogLevel( failed...") 496 | } 497 | } 498 | 499 | func TestSetLogFile(t *testing.T) { 500 | c, err := NewContainer(ContainerName) 501 | if err != nil { 502 | t.Errorf(err.Error()) 503 | } 504 | defer PutContainer(c) 505 | 506 | if err := c.SetLogFile("/tmp/" + ContainerName); err != nil || c.LogFile() != "/tmp/"+ContainerName { 507 | t.Errorf("SetLogFile failed...") 508 | } 509 | } 510 | 511 | func TestInitPid_Positive(t *testing.T) { 512 | c, err := NewContainer(ContainerName) 513 | if err != nil { 514 | t.Errorf(err.Error()) 515 | } 516 | defer PutContainer(c) 517 | 518 | if c.InitPid() == -1 { 519 | t.Errorf("InitPid failed...") 520 | } 521 | } 522 | 523 | func TestName(t *testing.T) { 524 | c, err := NewContainer(ContainerName) 525 | if err != nil { 526 | t.Errorf(err.Error()) 527 | } 528 | defer PutContainer(c) 529 | 530 | if c.Name() != ContainerName { 531 | t.Errorf("Name failed...") 532 | } 533 | } 534 | 535 | func TestFreeze(t *testing.T) { 536 | c, err := NewContainer(ContainerName) 537 | if err != nil { 538 | t.Errorf(err.Error()) 539 | } 540 | defer PutContainer(c) 541 | 542 | if err := c.Freeze(); err != nil { 543 | t.Errorf(err.Error()) 544 | } 545 | 546 | c.Wait(FROZEN, 30*time.Second) 547 | if c.State() != FROZEN { 548 | t.Errorf("Freezing the container failed...") 549 | } 550 | } 551 | 552 | func TestUnfreeze(t *testing.T) { 553 | c, err := NewContainer(ContainerName) 554 | if err != nil { 555 | t.Errorf(err.Error()) 556 | } 557 | defer PutContainer(c) 558 | 559 | if err := c.Unfreeze(); err != nil { 560 | t.Errorf(err.Error()) 561 | } 562 | 563 | c.Wait(RUNNING, 30*time.Second) 564 | if !c.Running() { 565 | t.Errorf("Unfreezing the container failed...") 566 | } 567 | } 568 | 569 | func TestLoadConfigFile(t *testing.T) { 570 | c, err := NewContainer(ContainerName) 571 | if err != nil { 572 | t.Errorf(err.Error()) 573 | } 574 | defer PutContainer(c) 575 | 576 | if err := c.LoadConfigFile(c.ConfigFileName()); err != nil { 577 | t.Errorf(err.Error()) 578 | } 579 | } 580 | 581 | func TestSaveConfigFile(t *testing.T) { 582 | c, err := NewContainer(ContainerName) 583 | if err != nil { 584 | t.Errorf(err.Error()) 585 | } 586 | defer PutContainer(c) 587 | 588 | if err := c.SaveConfigFile(c.ConfigFileName()); err != nil { 589 | t.Errorf(err.Error()) 590 | } 591 | } 592 | 593 | func TestConfigItem(t *testing.T) { 594 | c, err := NewContainer(ContainerName) 595 | if err != nil { 596 | t.Errorf(err.Error()) 597 | } 598 | defer PutContainer(c) 599 | 600 | if c.ConfigItem("lxc.utsname")[0] != ContainerName { 601 | t.Errorf("ConfigItem failed...") 602 | } 603 | } 604 | 605 | func TestSetConfigItem(t *testing.T) { 606 | c, err := NewContainer(ContainerName) 607 | if err != nil { 608 | t.Errorf(err.Error()) 609 | } 610 | defer PutContainer(c) 611 | 612 | if err := c.SetConfigItem("lxc.utsname", ContainerName); err != nil { 613 | t.Errorf(err.Error()) 614 | } 615 | 616 | if c.ConfigItem("lxc.utsname")[0] != ContainerName { 617 | t.Errorf("ConfigItem failed...") 618 | } 619 | } 620 | 621 | func TestRunningConfigItem(t *testing.T) { 622 | c, err := NewContainer(ContainerName) 623 | if err != nil { 624 | t.Errorf(err.Error()) 625 | } 626 | defer PutContainer(c) 627 | 628 | if c.RunningConfigItem("lxc.network.0.type") == nil { 629 | t.Errorf("RunningConfigItem failed...") 630 | } 631 | } 632 | 633 | func TestSetCgroupItem(t *testing.T) { 634 | c, err := NewContainer(ContainerName) 635 | if err != nil { 636 | t.Errorf(err.Error()) 637 | } 638 | defer PutContainer(c) 639 | 640 | maxMem := c.CgroupItem("memory.max_usage_in_bytes")[0] 641 | currentMem := c.CgroupItem("memory.limit_in_bytes")[0] 642 | if err := c.SetCgroupItem("memory.limit_in_bytes", maxMem); err != nil { 643 | t.Errorf(err.Error()) 644 | } 645 | newMem := c.CgroupItem("memory.limit_in_bytes")[0] 646 | 647 | if newMem == currentMem { 648 | t.Errorf("SetCgroupItem failed...") 649 | } 650 | } 651 | 652 | func TestClearConfigItem(t *testing.T) { 653 | c, err := NewContainer(ContainerName) 654 | if err != nil { 655 | t.Errorf(err.Error()) 656 | } 657 | defer PutContainer(c) 658 | 659 | if err := c.ClearConfigItem("lxc.cap.drop"); err != nil { 660 | t.Errorf(err.Error()) 661 | } 662 | if c.ConfigItem("lxc.cap.drop")[0] != "" { 663 | t.Errorf("ClearConfigItem failed...") 664 | } 665 | } 666 | 667 | func TestConfigKeys(t *testing.T) { 668 | c, err := NewContainer(ContainerName) 669 | if err != nil { 670 | t.Errorf(err.Error()) 671 | } 672 | defer PutContainer(c) 673 | 674 | keys := strings.Join(c.ConfigKeys("lxc.network.0"), " ") 675 | if !strings.Contains(keys, "mtu") { 676 | t.Errorf("Keys failed...") 677 | } 678 | } 679 | 680 | func TestInterfaces(t *testing.T) { 681 | c, err := NewContainer(ContainerName) 682 | if err != nil { 683 | t.Errorf(err.Error()) 684 | } 685 | defer PutContainer(c) 686 | 687 | if _, err := c.Interfaces(); err != nil { 688 | t.Errorf(err.Error()) 689 | } 690 | } 691 | 692 | func TestMemoryUsage(t *testing.T) { 693 | c, err := NewContainer(ContainerName) 694 | if err != nil { 695 | t.Errorf(err.Error()) 696 | } 697 | defer PutContainer(c) 698 | 699 | if _, err := c.MemoryUsage(); err != nil { 700 | t.Errorf(err.Error()) 701 | } 702 | } 703 | 704 | func TestKernelMemoryUsage(t *testing.T) { 705 | c, err := NewContainer(ContainerName) 706 | if err != nil { 707 | t.Errorf(err.Error()) 708 | } 709 | defer PutContainer(c) 710 | 711 | if _, err := c.KernelMemoryUsage(); err != nil { 712 | t.Errorf(err.Error()) 713 | } 714 | } 715 | 716 | func TestMemorySwapUsage(t *testing.T) { 717 | c, err := NewContainer(ContainerName) 718 | if err != nil { 719 | t.Errorf(err.Error()) 720 | } 721 | defer PutContainer(c) 722 | 723 | if _, err := c.MemorySwapUsage(); err != nil { 724 | t.Errorf(err.Error()) 725 | } 726 | } 727 | 728 | func TestBlkioUsage(t *testing.T) { 729 | c, err := NewContainer(ContainerName) 730 | if err != nil { 731 | t.Errorf(err.Error()) 732 | } 733 | defer PutContainer(c) 734 | 735 | if _, err := c.BlkioUsage(); err != nil { 736 | t.Errorf(err.Error()) 737 | } 738 | } 739 | 740 | func TestMemoryLimit(t *testing.T) { 741 | c, err := NewContainer(ContainerName) 742 | if err != nil { 743 | t.Errorf(err.Error()) 744 | } 745 | defer PutContainer(c) 746 | 747 | if _, err := c.MemoryLimit(); err != nil { 748 | t.Errorf(err.Error()) 749 | } 750 | } 751 | 752 | func TestSoftMemoryLimit(t *testing.T) { 753 | c, err := NewContainer(ContainerName) 754 | if err != nil { 755 | t.Errorf(err.Error()) 756 | } 757 | defer PutContainer(c) 758 | 759 | if _, err := c.SoftMemoryLimit(); err != nil { 760 | t.Errorf(err.Error()) 761 | } 762 | } 763 | 764 | func TestKernelMemoryLimit(t *testing.T) { 765 | c, err := NewContainer(ContainerName) 766 | if err != nil { 767 | t.Errorf(err.Error()) 768 | } 769 | defer PutContainer(c) 770 | 771 | if _, err := c.KernelMemoryLimit(); err != nil { 772 | t.Errorf(err.Error()) 773 | } 774 | } 775 | 776 | func TestMemorySwapLimit(t *testing.T) { 777 | c, err := NewContainer(ContainerName) 778 | if err != nil { 779 | t.Errorf(err.Error()) 780 | } 781 | defer PutContainer(c) 782 | 783 | if _, err := c.MemorySwapLimit(); err != nil { 784 | t.Errorf(err.Error()) 785 | } 786 | } 787 | 788 | func TestSetMemoryLimit(t *testing.T) { 789 | c, err := NewContainer(ContainerName) 790 | if err != nil { 791 | t.Errorf(err.Error()) 792 | } 793 | defer PutContainer(c) 794 | 795 | oldMemLimit, err := c.MemoryLimit() 796 | if err != nil { 797 | t.Errorf(err.Error()) 798 | } 799 | 800 | if err := c.SetMemoryLimit(oldMemLimit * 4); err != nil { 801 | t.Errorf(err.Error()) 802 | } 803 | 804 | newMemLimit, err := c.MemoryLimit() 805 | if err != nil { 806 | t.Errorf(err.Error()) 807 | } 808 | 809 | if newMemLimit != oldMemLimit*4 { 810 | t.Errorf("SetMemoryLimit failed") 811 | } 812 | } 813 | 814 | func TestSetSoftMemoryLimit(t *testing.T) { 815 | c, err := NewContainer(ContainerName) 816 | if err != nil { 817 | t.Errorf(err.Error()) 818 | } 819 | defer PutContainer(c) 820 | 821 | oldMemLimit, err := c.MemoryLimit() 822 | if err != nil { 823 | t.Errorf(err.Error()) 824 | } 825 | 826 | if err := c.SetSoftMemoryLimit(oldMemLimit * 4); err != nil { 827 | t.Errorf(err.Error()) 828 | } 829 | 830 | newMemLimit, err := c.SoftMemoryLimit() 831 | if err != nil { 832 | t.Errorf(err.Error()) 833 | } 834 | 835 | if newMemLimit != oldMemLimit*4 { 836 | t.Errorf("SetSoftMemoryLimit failed") 837 | } 838 | } 839 | 840 | func TestSetKernelMemoryLimit(t *testing.T) { 841 | t.Skip("skipping the test as it requires memory.kmem.limit_in_bytes to be set") 842 | 843 | c, err := NewContainer(ContainerName) 844 | if err != nil { 845 | t.Errorf(err.Error()) 846 | } 847 | defer PutContainer(c) 848 | 849 | oldMemLimit, err := c.KernelMemoryLimit() 850 | if err != nil { 851 | t.Errorf(err.Error()) 852 | } 853 | 854 | if err := c.SetKernelMemoryLimit(oldMemLimit * 4); err != nil { 855 | t.Errorf(err.Error()) 856 | } 857 | 858 | newMemLimit, err := c.KernelMemoryLimit() 859 | if err != nil { 860 | t.Errorf(err.Error()) 861 | } 862 | if newMemLimit != oldMemLimit*4 { 863 | t.Errorf("SetKernelMemoryLimit failed") 864 | } 865 | } 866 | 867 | func TestSetMemorySwapLimit(t *testing.T) { 868 | c, err := NewContainer(ContainerName) 869 | if err != nil { 870 | t.Errorf(err.Error()) 871 | } 872 | defer PutContainer(c) 873 | 874 | oldMemorySwapLimit, err := c.MemorySwapLimit() 875 | if err != nil { 876 | t.Errorf(err.Error()) 877 | } 878 | if err := c.SetMemorySwapLimit(oldMemorySwapLimit / 4); err != nil { 879 | t.Errorf(err.Error()) 880 | } 881 | 882 | newMemorySwapLimit, err := c.MemorySwapLimit() 883 | if err != nil { 884 | t.Errorf(err.Error()) 885 | } 886 | 887 | if newMemorySwapLimit != oldMemorySwapLimit/4 { 888 | t.Errorf("SetSwapLimit failed") 889 | } 890 | } 891 | 892 | func TestCPUTime(t *testing.T) { 893 | c, err := NewContainer(ContainerName) 894 | if err != nil { 895 | t.Errorf(err.Error()) 896 | } 897 | defer PutContainer(c) 898 | 899 | if _, err := c.CPUTime(); err != nil { 900 | t.Errorf(err.Error()) 901 | } 902 | } 903 | 904 | func TestCPUTimePerCPU(t *testing.T) { 905 | c, err := NewContainer(ContainerName) 906 | if err != nil { 907 | t.Errorf(err.Error()) 908 | } 909 | defer PutContainer(c) 910 | 911 | if _, err := c.CPUTimePerCPU(); err != nil { 912 | t.Errorf(err.Error()) 913 | } 914 | } 915 | 916 | func TestCPUStats(t *testing.T) { 917 | c, err := NewContainer(ContainerName) 918 | if err != nil { 919 | t.Errorf(err.Error()) 920 | } 921 | defer PutContainer(c) 922 | 923 | if _, err := c.CPUStats(); err != nil { 924 | t.Errorf(err.Error()) 925 | } 926 | } 927 | 928 | func TestRunCommand(t *testing.T) { 929 | c, err := NewContainer(ContainerName) 930 | if err != nil { 931 | t.Errorf(err.Error()) 932 | } 933 | defer PutContainer(c) 934 | 935 | argsThree := []string{"/bin/sh", "-c", "/bin/ls -al > /dev/null"} 936 | ok, err := c.RunCommand(os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), argsThree...) 937 | if err != nil { 938 | t.Errorf(err.Error()) 939 | } 940 | if ok != true { 941 | t.Errorf("Expected success") 942 | } 943 | 944 | argsThree = []string{"/bin/sh", "-c", "exit 1"} 945 | ok, err = c.RunCommand(os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), argsThree...) 946 | if err != nil { 947 | t.Errorf(err.Error()) 948 | } 949 | if ok != false { 950 | t.Errorf("Expected failure") 951 | } 952 | } 953 | 954 | func TestRunCommandWithClearEnvironment(t *testing.T) { 955 | c, err := NewContainer(ContainerName) 956 | if err != nil { 957 | t.Errorf(err.Error()) 958 | } 959 | defer PutContainer(c) 960 | 961 | argsThree := []string{"/bin/sh", "-c", "/bin/ls -al > /dev/null"} 962 | ok, err := c.RunCommandWithClearEnvironment(os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), argsThree...) 963 | if err != nil { 964 | t.Errorf(err.Error()) 965 | } 966 | if ok != true { 967 | t.Errorf("Expected success") 968 | } 969 | 970 | argsThree = []string{"/bin/sh", "-c", "exit 1"} 971 | ok, err = c.RunCommandWithClearEnvironment(os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(), argsThree...) 972 | if err != nil { 973 | t.Errorf(err.Error()) 974 | } 975 | if ok != false { 976 | t.Errorf("Expected failure") 977 | } 978 | } 979 | 980 | func TestConsoleFd(t *testing.T) { 981 | c, err := NewContainer(ContainerName) 982 | if err != nil { 983 | t.Errorf(err.Error()) 984 | } 985 | defer PutContainer(c) 986 | 987 | if _, err := c.ConsoleFd(0); err != nil { 988 | t.Errorf(err.Error()) 989 | } 990 | } 991 | 992 | func TestIPAddress(t *testing.T) { 993 | c, err := NewContainer(ContainerName) 994 | if err != nil { 995 | t.Errorf(err.Error()) 996 | } 997 | defer PutContainer(c) 998 | 999 | if unprivileged() { 1000 | time.Sleep(3 * time.Second) 1001 | } 1002 | 1003 | if _, err := c.IPAddress("lo"); err != nil { 1004 | t.Errorf(err.Error()) 1005 | } 1006 | } 1007 | 1008 | func TestAddDeviceNode(t *testing.T) { 1009 | if unprivileged() { 1010 | t.Skip("skipping test in unprivileged mode.") 1011 | } 1012 | 1013 | c, err := NewContainer(ContainerName) 1014 | if err != nil { 1015 | t.Errorf(err.Error()) 1016 | } 1017 | defer PutContainer(c) 1018 | 1019 | if err := c.AddDeviceNode("/dev/network_latency"); err != nil { 1020 | t.Errorf(err.Error()) 1021 | } 1022 | } 1023 | 1024 | func TestRemoveDeviceNode(t *testing.T) { 1025 | if unprivileged() { 1026 | t.Skip("skipping test in unprivileged mode.") 1027 | } 1028 | 1029 | c, err := NewContainer(ContainerName) 1030 | if err != nil { 1031 | t.Errorf(err.Error()) 1032 | } 1033 | defer PutContainer(c) 1034 | 1035 | if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { 1036 | t.Errorf(err.Error()) 1037 | } 1038 | } 1039 | 1040 | func TestIPv4Addresses(t *testing.T) { 1041 | t.Skip("skipping test") 1042 | 1043 | c, err := NewContainer(ContainerName) 1044 | if err != nil { 1045 | t.Errorf(err.Error()) 1046 | } 1047 | defer PutContainer(c) 1048 | 1049 | if _, err := c.IPv4Addresses(); err != nil { 1050 | t.Errorf(err.Error()) 1051 | } 1052 | } 1053 | 1054 | func TestIPv6Addresses(t *testing.T) { 1055 | t.Skip("skipping test") 1056 | 1057 | c, err := NewContainer(ContainerName) 1058 | if err != nil { 1059 | t.Errorf(err.Error()) 1060 | } 1061 | defer PutContainer(c) 1062 | 1063 | if _, err := c.IPv6Addresses(); err != nil { 1064 | t.Errorf(err.Error()) 1065 | } 1066 | } 1067 | 1068 | func TestReboot(t *testing.T) { 1069 | c, err := NewContainer(ContainerName) 1070 | if err != nil { 1071 | t.Errorf(err.Error()) 1072 | } 1073 | defer PutContainer(c) 1074 | 1075 | if err := c.Reboot(); err != nil { 1076 | t.Errorf("Rebooting the container failed...") 1077 | } 1078 | c.Wait(RUNNING, 30*time.Second) 1079 | } 1080 | 1081 | func TestConcurrentShutdown(t *testing.T) { 1082 | defer runtime.GOMAXPROCS(runtime.NumCPU()) 1083 | 1084 | if unprivileged() { 1085 | t.Skip("skipping test in unprivileged mode.") 1086 | } 1087 | 1088 | var wg sync.WaitGroup 1089 | 1090 | for i := 0; i < 10; i++ { 1091 | wg.Add(1) 1092 | go func(i int) { 1093 | c, err := NewContainer(strconv.Itoa(i)) 1094 | if err != nil { 1095 | t.Errorf(err.Error()) 1096 | } 1097 | defer PutContainer(c) 1098 | 1099 | if err := c.Shutdown(30 * time.Second); err != nil { 1100 | t.Errorf(err.Error()) 1101 | } 1102 | 1103 | c.Wait(STOPPED, 30*time.Second) 1104 | if c.Running() { 1105 | t.Errorf("Shutting down the container failed...") 1106 | } 1107 | 1108 | wg.Done() 1109 | }(i) 1110 | } 1111 | wg.Wait() 1112 | } 1113 | 1114 | func TestShutdown(t *testing.T) { 1115 | c, err := NewContainer(ContainerName) 1116 | if err != nil { 1117 | t.Errorf(err.Error()) 1118 | } 1119 | defer PutContainer(c) 1120 | 1121 | if err := c.Shutdown(30 * time.Second); err != nil { 1122 | t.Errorf(err.Error()) 1123 | } 1124 | 1125 | c.Wait(STOPPED, 30*time.Second) 1126 | if c.Running() { 1127 | t.Errorf("Shutting down the container failed...") 1128 | } 1129 | } 1130 | 1131 | func TestStop(t *testing.T) { 1132 | c, err := NewContainer(ContainerName) 1133 | if err != nil { 1134 | t.Errorf(err.Error()) 1135 | } 1136 | defer PutContainer(c) 1137 | 1138 | if err := c.Start(); err != nil { 1139 | t.Errorf(err.Error()) 1140 | } 1141 | 1142 | if err := c.Stop(); err != nil { 1143 | t.Errorf(err.Error()) 1144 | } 1145 | 1146 | c.Wait(STOPPED, 30*time.Second) 1147 | if c.Running() { 1148 | t.Errorf("Stopping the container failed...") 1149 | } 1150 | } 1151 | 1152 | func TestDestroySnapshot(t *testing.T) { 1153 | c, err := NewContainer(ContainerName) 1154 | if err != nil { 1155 | t.Errorf(err.Error()) 1156 | } 1157 | defer PutContainer(c) 1158 | 1159 | snapshot := Snapshot{Name: SnapshotName} 1160 | if err := c.DestroySnapshot(snapshot); err != nil { 1161 | t.Errorf(err.Error()) 1162 | } 1163 | } 1164 | 1165 | func TestDestroy(t *testing.T) { 1166 | if supported("overlayfs") { 1167 | c, err := NewContainer(ContainerCloneOverlayName) 1168 | if err != nil { 1169 | t.Errorf(err.Error()) 1170 | } 1171 | defer PutContainer(c) 1172 | 1173 | if err := c.Destroy(); err != nil { 1174 | t.Errorf(err.Error()) 1175 | } 1176 | } 1177 | 1178 | if !unprivileged() && supported("aufs") { 1179 | c, err := NewContainer(ContainerCloneAufsName) 1180 | if err != nil { 1181 | t.Errorf(err.Error()) 1182 | } 1183 | defer PutContainer(c) 1184 | 1185 | if err := c.Destroy(); err != nil { 1186 | t.Errorf(err.Error()) 1187 | } 1188 | } 1189 | c, err := NewContainer(ContainerCloneName) 1190 | if err != nil { 1191 | t.Errorf(err.Error()) 1192 | } 1193 | defer PutContainer(c) 1194 | 1195 | if err := c.Destroy(); err != nil { 1196 | t.Errorf(err.Error()) 1197 | } 1198 | 1199 | c, err = NewContainer(ContainerRestoreName) 1200 | if err != nil { 1201 | t.Errorf(err.Error()) 1202 | } 1203 | defer PutContainer(c) 1204 | 1205 | if err := c.Destroy(); err != nil { 1206 | t.Errorf(err.Error()) 1207 | } 1208 | 1209 | c, err = NewContainer(ContainerName) 1210 | if err != nil { 1211 | t.Errorf(err.Error()) 1212 | } 1213 | defer PutContainer(c) 1214 | 1215 | if err := c.Destroy(); err != nil { 1216 | t.Errorf(err.Error()) 1217 | } 1218 | } 1219 | 1220 | func TestConcurrentDestroy(t *testing.T) { 1221 | defer runtime.GOMAXPROCS(runtime.NumCPU()) 1222 | 1223 | if unprivileged() { 1224 | t.Skip("skipping test in unprivileged mode.") 1225 | } 1226 | 1227 | var wg sync.WaitGroup 1228 | 1229 | for i := 0; i < 10; i++ { 1230 | wg.Add(1) 1231 | go func(i int) { 1232 | c, err := NewContainer(strconv.Itoa(i)) 1233 | if err != nil { 1234 | t.Errorf(err.Error()) 1235 | } 1236 | defer PutContainer(c) 1237 | 1238 | // sleep for a while to simulate some dummy work 1239 | time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) 1240 | 1241 | if err := c.Destroy(); err != nil { 1242 | t.Errorf(err.Error()) 1243 | } 1244 | wg.Done() 1245 | }(i) 1246 | } 1247 | wg.Wait() 1248 | } 1249 | 1250 | func TestBackendStore(t *testing.T) { 1251 | var X struct { 1252 | store BackendStore 1253 | } 1254 | 1255 | if X.store.String() != "" { 1256 | t.Error("zero value of BackendStore should be invalid") 1257 | } 1258 | } 1259 | 1260 | func TestState(t *testing.T) { 1261 | var X struct { 1262 | state State 1263 | } 1264 | 1265 | if X.state.String() != "" { 1266 | t.Error("zero value of State should be invalid") 1267 | } 1268 | } 1269 | -------------------------------------------------------------------------------- /container.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2013, 2014, S.Çağlar Onur 2 | // Use of this source code is governed by a LGPLv2.1 3 | // license that can be found in the LICENSE file. 4 | // 5 | // Authors: 6 | // S.Çağlar Onur 7 | 8 | // +build linux 9 | 10 | package lxc 11 | 12 | // #include 13 | // #include "lxc.h" 14 | import "C" 15 | 16 | import ( 17 | "fmt" 18 | "io/ioutil" 19 | "os/exec" 20 | "reflect" 21 | "strconv" 22 | "strings" 23 | "sync" 24 | "time" 25 | "unsafe" 26 | ) 27 | 28 | // Container struct 29 | type Container struct { 30 | container *C.struct_lxc_container 31 | mu sync.RWMutex 32 | 33 | verbosity Verbosity 34 | } 35 | 36 | // Snapshot struct 37 | type Snapshot struct { 38 | Name string 39 | CommentPath string 40 | Timestamp string 41 | Path string 42 | } 43 | 44 | func (c *Container) makeSure(flags int) error { 45 | if flags&isDefined != 0 && !c.Defined() { 46 | return ErrNotDefined 47 | } 48 | 49 | if flags&isNotDefined != 0 && c.Defined() { 50 | return ErrAlreadyDefined 51 | } 52 | 53 | if flags&isRunning != 0 && !c.Running() { 54 | return ErrNotRunning 55 | } 56 | 57 | if flags&isNotRunning != 0 && c.Running() { 58 | return ErrAlreadyRunning 59 | } 60 | return nil 61 | } 62 | 63 | func (c *Container) cgroupItemAsByteSize(filename string, missing error) (ByteSize, error) { 64 | size, err := strconv.ParseFloat(c.CgroupItem(filename)[0], 64) 65 | if err != nil { 66 | return -1, missing 67 | } 68 | return ByteSize(size), nil 69 | } 70 | 71 | func (c *Container) setCgroupItemWithByteSize(filename string, limit ByteSize, missing error) error { 72 | if err := c.SetCgroupItem(filename, fmt.Sprintf("%.f", limit)); err != nil { 73 | return missing 74 | } 75 | return nil 76 | } 77 | 78 | // Name returns the name of the container. 79 | func (c *Container) Name() string { 80 | c.mu.RLock() 81 | defer c.mu.RUnlock() 82 | 83 | return C.GoString(c.container.name) 84 | } 85 | 86 | // Defined returns true if the container is already defined. 87 | func (c *Container) Defined() bool { 88 | c.mu.RLock() 89 | defer c.mu.RUnlock() 90 | 91 | return bool(C.go_lxc_defined(c.container)) 92 | } 93 | 94 | // Running returns true if the container is already running. 95 | func (c *Container) Running() bool { 96 | c.mu.RLock() 97 | defer c.mu.RUnlock() 98 | 99 | return bool(C.go_lxc_running(c.container)) 100 | } 101 | 102 | // Controllable returns true if the caller can control the container. 103 | func (c *Container) Controllable() bool { 104 | c.mu.RLock() 105 | defer c.mu.RUnlock() 106 | 107 | return bool(C.go_lxc_may_control(c.container)) 108 | } 109 | 110 | // CreateSnapshot creates a new snapshot. 111 | func (c *Container) CreateSnapshot() (*Snapshot, error) { 112 | if err := c.makeSure(isDefined | isNotRunning); err != nil { 113 | return nil, err 114 | } 115 | 116 | c.mu.Lock() 117 | defer c.mu.Unlock() 118 | 119 | ret := int(C.go_lxc_snapshot(c.container)) 120 | if ret < 0 { 121 | return nil, ErrCreateSnapshotFailed 122 | } 123 | return &Snapshot{Name: fmt.Sprintf("snap%d", ret)}, nil 124 | } 125 | 126 | // RestoreSnapshot creates a new container based on a snapshot. 127 | func (c *Container) RestoreSnapshot(snapshot Snapshot, name string) error { 128 | if err := c.makeSure(isDefined); err != nil { 129 | return err 130 | } 131 | 132 | c.mu.Lock() 133 | defer c.mu.Unlock() 134 | 135 | cname := C.CString(name) 136 | defer C.free(unsafe.Pointer(cname)) 137 | 138 | csnapname := C.CString(snapshot.Name) 139 | defer C.free(unsafe.Pointer(csnapname)) 140 | 141 | if !bool(C.go_lxc_snapshot_restore(c.container, csnapname, cname)) { 142 | return ErrRestoreSnapshotFailed 143 | } 144 | return nil 145 | } 146 | 147 | // DestroySnapshot destroys the specified snapshot. 148 | func (c *Container) DestroySnapshot(snapshot Snapshot) error { 149 | if err := c.makeSure(isDefined); err != nil { 150 | return err 151 | } 152 | 153 | c.mu.Lock() 154 | defer c.mu.Unlock() 155 | 156 | csnapname := C.CString(snapshot.Name) 157 | defer C.free(unsafe.Pointer(csnapname)) 158 | 159 | if !bool(C.go_lxc_snapshot_destroy(c.container, csnapname)) { 160 | return ErrDestroySnapshotFailed 161 | } 162 | return nil 163 | } 164 | 165 | // Snapshots returns the list of container snapshots. 166 | func (c *Container) Snapshots() ([]Snapshot, error) { 167 | if err := c.makeSure(isDefined); err != nil { 168 | return nil, err 169 | } 170 | 171 | c.mu.Lock() 172 | defer c.mu.Unlock() 173 | 174 | var csnapshots *C.struct_lxc_snapshot 175 | 176 | size := int(C.go_lxc_snapshot_list(c.container, &csnapshots)) 177 | defer freeSnapshots(csnapshots, size) 178 | 179 | if size < 1 { 180 | return nil, ErrNoSnapshot 181 | } 182 | 183 | hdr := reflect.SliceHeader{ 184 | Data: uintptr(unsafe.Pointer(csnapshots)), 185 | Len: size, 186 | Cap: size, 187 | } 188 | gosnapshots := *(*[]C.struct_lxc_snapshot)(unsafe.Pointer(&hdr)) 189 | 190 | snapshots := make([]Snapshot, size, size) 191 | for i := 0; i < size; i++ { 192 | snapshots[i] = Snapshot{ 193 | Name: C.GoString(gosnapshots[i].name), 194 | Timestamp: C.GoString(gosnapshots[i].timestamp), 195 | CommentPath: C.GoString(gosnapshots[i].comment_pathname), 196 | Path: C.GoString(gosnapshots[i].lxcpath), 197 | } 198 | } 199 | 200 | return snapshots, nil 201 | } 202 | 203 | // State returns the state of the container. 204 | func (c *Container) State() State { 205 | c.mu.RLock() 206 | defer c.mu.RUnlock() 207 | 208 | return stateMap[C.GoString(C.go_lxc_state(c.container))] 209 | } 210 | 211 | // InitPid returns the process ID of the container's init process 212 | // seen from outside the container. 213 | func (c *Container) InitPid() int { 214 | c.mu.RLock() 215 | defer c.mu.RUnlock() 216 | 217 | return int(C.go_lxc_init_pid(c.container)) 218 | } 219 | 220 | // Daemonize returns true if the container wished to be daemonized. 221 | func (c *Container) Daemonize() bool { 222 | c.mu.RLock() 223 | defer c.mu.RUnlock() 224 | 225 | return bool(c.container.daemonize) 226 | } 227 | 228 | // WantDaemonize determines if the container wants to run daemonized. 229 | func (c *Container) WantDaemonize(state bool) error { 230 | c.mu.Lock() 231 | defer c.mu.Unlock() 232 | 233 | if !bool(C.go_lxc_want_daemonize(c.container, C.bool(state))) { 234 | return ErrDaemonizeFailed 235 | } 236 | return nil 237 | } 238 | 239 | // WantCloseAllFds determines whether container wishes all file descriptors 240 | // to be closed on startup. 241 | func (c *Container) WantCloseAllFds(state bool) error { 242 | c.mu.Lock() 243 | defer c.mu.Unlock() 244 | 245 | if !bool(C.go_lxc_want_close_all_fds(c.container, C.bool(state))) { 246 | return ErrCloseAllFdsFailed 247 | } 248 | return nil 249 | } 250 | 251 | // SetVerbosity sets the verbosity level of some API calls 252 | func (c *Container) SetVerbosity(verbosity Verbosity) { 253 | c.mu.Lock() 254 | defer c.mu.Unlock() 255 | 256 | c.verbosity = verbosity 257 | } 258 | 259 | // Freeze freezes the running container. 260 | func (c *Container) Freeze() error { 261 | if err := c.makeSure(isDefined | isRunning); err != nil { 262 | return err 263 | } 264 | 265 | if c.State() == FROZEN { 266 | return ErrAlreadyFrozen 267 | } 268 | 269 | c.mu.Lock() 270 | defer c.mu.Unlock() 271 | 272 | if !bool(C.go_lxc_freeze(c.container)) { 273 | return ErrFreezeFailed 274 | } 275 | 276 | return nil 277 | } 278 | 279 | // Unfreeze thaws the frozen container. 280 | func (c *Container) Unfreeze() error { 281 | if err := c.makeSure(isDefined | isRunning); err != nil { 282 | return err 283 | } 284 | 285 | if c.State() != FROZEN { 286 | return ErrNotFrozen 287 | } 288 | 289 | c.mu.Lock() 290 | defer c.mu.Unlock() 291 | 292 | if !bool(C.go_lxc_unfreeze(c.container)) { 293 | return ErrUnfreezeFailed 294 | } 295 | 296 | return nil 297 | } 298 | 299 | // CreateUsing creates the container using given arguments with specified backend. 300 | func (c *Container) CreateUsing(template string, backend BackendStore, args ...string) error { 301 | // FIXME: Support bdevtype and bdev_specs 302 | // bdevtypes: 303 | // "btrfs", "zfs", "lvm", "dir" 304 | // 305 | // best tries to find the best backing store type 306 | // 307 | // bdev_specs: 308 | // zfs requires zfsroot 309 | // lvm requires lvname/vgname/thinpool as well as fstype and fssize 310 | // btrfs requires nothing 311 | // dir requires nothing 312 | if err := c.makeSure(isNotDefined); err != nil { 313 | return err 314 | } 315 | 316 | c.mu.Lock() 317 | defer c.mu.Unlock() 318 | 319 | ctemplate := C.CString(template) 320 | defer C.free(unsafe.Pointer(ctemplate)) 321 | 322 | cbackend := C.CString(backend.String()) 323 | defer C.free(unsafe.Pointer(cbackend)) 324 | 325 | ret := false 326 | if args != nil { 327 | cargs := makeNullTerminatedArgs(args) 328 | if cargs == nil { 329 | return ErrAllocationFailed 330 | } 331 | defer freeNullTerminatedArgs(cargs, len(args)) 332 | 333 | ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), cargs)) 334 | } else { 335 | ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), nil)) 336 | } 337 | 338 | if !ret { 339 | return ErrCreateFailed 340 | } 341 | return nil 342 | } 343 | 344 | // Create creates the container using the Directory backendstore. 345 | func (c *Container) Create(template string, args ...string) error { 346 | return c.CreateUsing(template, Directory, args...) 347 | } 348 | 349 | // CreateAsUser creates the container as "unprivileged user" using the Directory backendstore. 350 | func (c *Container) CreateAsUser(distro string, release string, arch string, args ...string) error { 351 | // required parameters 352 | nargs := []string{"-d", distro, "-r", release, "-a", arch} 353 | // optional arguments 354 | nargs = append(nargs, args...) 355 | 356 | return c.CreateUsing("download", Directory, nargs...) 357 | } 358 | 359 | // Start starts the container. 360 | func (c *Container) Start() error { 361 | if err := c.makeSure(isDefined | isNotRunning); err != nil { 362 | return err 363 | } 364 | 365 | c.mu.Lock() 366 | defer c.mu.Unlock() 367 | 368 | if !bool(C.go_lxc_start(c.container, 0, nil)) { 369 | return ErrStartFailed 370 | } 371 | return nil 372 | } 373 | 374 | // Execute executes the given command in a temporary container. 375 | func (c *Container) Execute(args ...string) ([]byte, error) { 376 | if err := c.makeSure(isNotDefined); err != nil { 377 | return nil, err 378 | } 379 | 380 | cargs := []string{"lxc-execute", "-n", c.Name(), "-P", c.ConfigPath(), "--"} 381 | cargs = append(cargs, args...) 382 | 383 | c.mu.Lock() 384 | defer c.mu.Unlock() 385 | 386 | /* 387 | * FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now 388 | * go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ 389 | */ 390 | output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput() 391 | if err != nil { 392 | return nil, ErrExecuteFailed 393 | } 394 | 395 | return output, nil 396 | /* 397 | cargs := makeNullTerminatedArgs(args) 398 | if cargs == nil { 399 | return ErrAllocationFailed 400 | } 401 | defer freeNullTerminatedArgs(cargs, len(args)) 402 | 403 | if !bool(C.go_lxc_start(c.container, 1, cargs)) { 404 | return ErrExecuteFailed 405 | } 406 | return nil 407 | */ 408 | } 409 | 410 | // Stop stops the container. 411 | func (c *Container) Stop() error { 412 | if err := c.makeSure(isDefined | isRunning); err != nil { 413 | return err 414 | } 415 | 416 | c.mu.Lock() 417 | defer c.mu.Unlock() 418 | 419 | if !bool(C.go_lxc_stop(c.container)) { 420 | return ErrStopFailed 421 | } 422 | return nil 423 | } 424 | 425 | // Reboot reboots the container. 426 | func (c *Container) Reboot() error { 427 | if err := c.makeSure(isDefined | isRunning); err != nil { 428 | return err 429 | } 430 | 431 | c.mu.Lock() 432 | defer c.mu.Unlock() 433 | 434 | if !bool(C.go_lxc_reboot(c.container)) { 435 | return ErrRebootFailed 436 | } 437 | return nil 438 | } 439 | 440 | // Shutdown shuts down the container. 441 | func (c *Container) Shutdown(timeout time.Duration) error { 442 | if err := c.makeSure(isDefined | isRunning); err != nil { 443 | return err 444 | } 445 | c.mu.Lock() 446 | defer c.mu.Unlock() 447 | 448 | if !bool(C.go_lxc_shutdown(c.container, C.int(timeout.Seconds()))) { 449 | return ErrShutdownFailed 450 | } 451 | return nil 452 | } 453 | 454 | // Destroy destroys the container. 455 | func (c *Container) Destroy() error { 456 | if err := c.makeSure(isDefined | isNotRunning); err != nil { 457 | return err 458 | } 459 | 460 | c.mu.Lock() 461 | defer c.mu.Unlock() 462 | 463 | if !bool(C.go_lxc_destroy(c.container)) { 464 | return ErrDestroyFailed 465 | } 466 | return nil 467 | } 468 | 469 | // CloneUsing clones the container using given arguments with specified backend. 470 | // 471 | // Additional flags to change the cloning behaviour: 472 | // CloneKeepName, CloneKeepMACAddr, CloneSnapshot and CloneMaybeSnapshot 473 | func (c *Container) CloneUsing(name string, backend BackendStore, flags CloneFlags) error { 474 | // FIXME: support lxcpath, bdevtype, bdevdata, newsize and hookargs 475 | // 476 | // bdevtypes: 477 | // "btrfs", "zfs", "lvm", "dir" "overlayfs" 478 | // 479 | // bdevdata: 480 | // zfs requires zfsroot 481 | // lvm requires lvname/vgname/thinpool as well as fstype and fssize 482 | // btrfs requires nothing 483 | // dir requires nothing 484 | // 485 | // newsize: for blockdev-backed backingstores 486 | // 487 | // hookargs: additional arguments to pass to the clone hook script 488 | if err := c.makeSure(isDefined | isNotRunning); err != nil { 489 | return err 490 | } 491 | 492 | c.mu.Lock() 493 | defer c.mu.Unlock() 494 | 495 | cname := C.CString(name) 496 | defer C.free(unsafe.Pointer(cname)) 497 | 498 | cbackend := C.CString(backend.String()) 499 | defer C.free(unsafe.Pointer(cbackend)) 500 | 501 | if !bool(C.go_lxc_clone(c.container, cname, C.int(flags), cbackend)) { 502 | return ErrCloneFailed 503 | } 504 | return nil 505 | } 506 | 507 | // Clone clones the container using the Directory backendstore. 508 | func (c *Container) Clone(name string) error { 509 | return c.CloneUsing(name, Directory, 0) 510 | } 511 | 512 | // Rename renames the container. 513 | func (c *Container) Rename(name string) error { 514 | if err := c.makeSure(isDefined | isNotRunning); err != nil { 515 | return err 516 | } 517 | 518 | c.mu.Lock() 519 | defer c.mu.Unlock() 520 | 521 | cname := C.CString(name) 522 | defer C.free(unsafe.Pointer(cname)) 523 | 524 | if !bool(C.go_lxc_rename(c.container, cname)) { 525 | return ErrRenameFailed 526 | } 527 | return nil 528 | } 529 | 530 | // Wait waits for container to reach a particular state. 531 | func (c *Container) Wait(state State, timeout time.Duration) bool { 532 | c.mu.Lock() 533 | defer c.mu.Unlock() 534 | 535 | cstate := C.CString(state.String()) 536 | defer C.free(unsafe.Pointer(cstate)) 537 | 538 | return bool(C.go_lxc_wait(c.container, cstate, C.int(timeout.Seconds()))) 539 | } 540 | 541 | // ConfigFileName returns the container's configuration file's name. 542 | func (c *Container) ConfigFileName() string { 543 | c.mu.RLock() 544 | defer c.mu.RUnlock() 545 | 546 | // allocated in lxc.c 547 | configFileName := C.go_lxc_config_file_name(c.container) 548 | defer C.free(unsafe.Pointer(configFileName)) 549 | 550 | return C.GoString(configFileName) 551 | } 552 | 553 | // ConfigItem returns the value of the given config item. 554 | func (c *Container) ConfigItem(key string) []string { 555 | c.mu.RLock() 556 | defer c.mu.RUnlock() 557 | 558 | ckey := C.CString(key) 559 | defer C.free(unsafe.Pointer(ckey)) 560 | 561 | // allocated in lxc.c 562 | configItem := C.go_lxc_get_config_item(c.container, ckey) 563 | defer C.free(unsafe.Pointer(configItem)) 564 | 565 | ret := strings.TrimSpace(C.GoString(configItem)) 566 | return strings.Split(ret, "\n") 567 | } 568 | 569 | // SetConfigItem sets the value of the given config item. 570 | func (c *Container) SetConfigItem(key string, value string) error { 571 | c.mu.Lock() 572 | defer c.mu.Unlock() 573 | 574 | ckey := C.CString(key) 575 | defer C.free(unsafe.Pointer(ckey)) 576 | 577 | cvalue := C.CString(value) 578 | defer C.free(unsafe.Pointer(cvalue)) 579 | 580 | if !bool(C.go_lxc_set_config_item(c.container, ckey, cvalue)) { 581 | return ErrSettingConfigItemFailed 582 | } 583 | return nil 584 | } 585 | 586 | // RunningConfigItem returns the value of the given config item. 587 | func (c *Container) RunningConfigItem(key string) []string { 588 | c.mu.RLock() 589 | defer c.mu.RUnlock() 590 | 591 | ckey := C.CString(key) 592 | defer C.free(unsafe.Pointer(ckey)) 593 | 594 | // allocated in lxc.c 595 | configItem := C.go_lxc_get_running_config_item(c.container, ckey) 596 | defer C.free(unsafe.Pointer(configItem)) 597 | 598 | ret := strings.TrimSpace(C.GoString(configItem)) 599 | return strings.Split(ret, "\n") 600 | } 601 | 602 | // CgroupItem returns the value of the given cgroup subsystem value. 603 | func (c *Container) CgroupItem(key string) []string { 604 | c.mu.RLock() 605 | defer c.mu.RUnlock() 606 | 607 | ckey := C.CString(key) 608 | defer C.free(unsafe.Pointer(ckey)) 609 | 610 | // allocated in lxc.c 611 | cgroupItem := C.go_lxc_get_cgroup_item(c.container, ckey) 612 | defer C.free(unsafe.Pointer(cgroupItem)) 613 | 614 | ret := strings.TrimSpace(C.GoString(cgroupItem)) 615 | return strings.Split(ret, "\n") 616 | } 617 | 618 | // SetCgroupItem sets the value of given cgroup subsystem value. 619 | func (c *Container) SetCgroupItem(key string, value string) error { 620 | c.mu.Lock() 621 | defer c.mu.Unlock() 622 | 623 | ckey := C.CString(key) 624 | defer C.free(unsafe.Pointer(ckey)) 625 | 626 | cvalue := C.CString(value) 627 | defer C.free(unsafe.Pointer(cvalue)) 628 | 629 | if !bool(C.go_lxc_set_cgroup_item(c.container, ckey, cvalue)) { 630 | return ErrSettingCgroupItemFailed 631 | } 632 | return nil 633 | } 634 | 635 | // ClearConfig completely clears the containers in-memory configuration. 636 | func (c *Container) ClearConfig() { 637 | c.mu.Lock() 638 | defer c.mu.Unlock() 639 | 640 | C.go_lxc_clear_config(c.container) 641 | } 642 | 643 | // ClearConfigItem clears the value of given config item. 644 | func (c *Container) ClearConfigItem(key string) error { 645 | c.mu.Lock() 646 | defer c.mu.Unlock() 647 | 648 | ckey := C.CString(key) 649 | defer C.free(unsafe.Pointer(ckey)) 650 | 651 | if !bool(C.go_lxc_clear_config_item(c.container, ckey)) { 652 | return ErrClearingCgroupItemFailed 653 | } 654 | return nil 655 | } 656 | 657 | // ConfigKeys returns the names of the config items. 658 | func (c *Container) ConfigKeys(key ...string) []string { 659 | c.mu.RLock() 660 | defer c.mu.RUnlock() 661 | 662 | var keys *_Ctype_char 663 | 664 | if key != nil && len(key) == 1 { 665 | ckey := C.CString(key[0]) 666 | defer C.free(unsafe.Pointer(ckey)) 667 | 668 | // allocated in lxc.c 669 | keys = C.go_lxc_get_keys(c.container, ckey) 670 | defer C.free(unsafe.Pointer(keys)) 671 | } else { 672 | // allocated in lxc.c 673 | keys = C.go_lxc_get_keys(c.container, nil) 674 | defer C.free(unsafe.Pointer(keys)) 675 | } 676 | ret := strings.TrimSpace(C.GoString(keys)) 677 | return strings.Split(ret, "\n") 678 | } 679 | 680 | // LoadConfigFile loads the configuration file from given path. 681 | func (c *Container) LoadConfigFile(path string) error { 682 | c.mu.Lock() 683 | defer c.mu.Unlock() 684 | 685 | cpath := C.CString(path) 686 | defer C.free(unsafe.Pointer(cpath)) 687 | 688 | if !bool(C.go_lxc_load_config(c.container, cpath)) { 689 | return ErrLoadConfigFailed 690 | } 691 | return nil 692 | } 693 | 694 | // SaveConfigFile saves the configuration file to given path. 695 | func (c *Container) SaveConfigFile(path string) error { 696 | c.mu.Lock() 697 | defer c.mu.Unlock() 698 | 699 | cpath := C.CString(path) 700 | defer C.free(unsafe.Pointer(cpath)) 701 | 702 | if !bool(C.go_lxc_save_config(c.container, cpath)) { 703 | return ErrSaveConfigFailed 704 | } 705 | return nil 706 | } 707 | 708 | // ConfigPath returns the configuration file's path. 709 | func (c *Container) ConfigPath() string { 710 | c.mu.RLock() 711 | defer c.mu.RUnlock() 712 | 713 | return C.GoString(C.go_lxc_get_config_path(c.container)) 714 | } 715 | 716 | // SetConfigPath sets the configuration file's path. 717 | func (c *Container) SetConfigPath(path string) error { 718 | c.mu.Lock() 719 | defer c.mu.Unlock() 720 | 721 | cpath := C.CString(path) 722 | defer C.free(unsafe.Pointer(cpath)) 723 | 724 | if !bool(C.go_lxc_set_config_path(c.container, cpath)) { 725 | return ErrSettingConfigPathFailed 726 | } 727 | return nil 728 | } 729 | 730 | // MemoryUsage returns memory usage of the container in bytes. 731 | func (c *Container) MemoryUsage() (ByteSize, error) { 732 | if err := c.makeSure(isDefined | isRunning); err != nil { 733 | return -1, err 734 | } 735 | 736 | return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit) 737 | } 738 | 739 | // MemoryLimit returns memory limit of the container in bytes. 740 | func (c *Container) MemoryLimit() (ByteSize, error) { 741 | if err := c.makeSure(isDefined | isRunning); err != nil { 742 | return -1, err 743 | } 744 | 745 | return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit) 746 | } 747 | 748 | // SetMemoryLimit sets memory limit of the container in bytes. 749 | func (c *Container) SetMemoryLimit(limit ByteSize) error { 750 | if err := c.makeSure(isDefined | isRunning); err != nil { 751 | return err 752 | } 753 | 754 | return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed) 755 | } 756 | 757 | // SoftMemoryLimit returns soft memory limit of the container in bytes. 758 | func (c *Container) SoftMemoryLimit() (ByteSize, error) { 759 | if err := c.makeSure(isDefined | isRunning); err != nil { 760 | return -1, err 761 | } 762 | 763 | return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit) 764 | } 765 | 766 | // SetSoftMemoryLimit sets soft memory limit of the container in bytes. 767 | func (c *Container) SetSoftMemoryLimit(limit ByteSize) error { 768 | if err := c.makeSure(isDefined | isRunning); err != nil { 769 | return err 770 | } 771 | 772 | return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed) 773 | } 774 | 775 | // KernelMemoryUsage returns current kernel memory allocation of the container in bytes. 776 | func (c *Container) KernelMemoryUsage() (ByteSize, error) { 777 | if err := c.makeSure(isDefined | isRunning); err != nil { 778 | return -1, err 779 | } 780 | 781 | return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) 782 | } 783 | 784 | // KernelMemoryLimit returns kernel memory limit of the container in bytes. 785 | func (c *Container) KernelMemoryLimit() (ByteSize, error) { 786 | if err := c.makeSure(isDefined | isRunning); err != nil { 787 | return -1, err 788 | } 789 | 790 | return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) 791 | } 792 | 793 | // SetKernelMemoryLimit sets kernel memory limit of the container in bytes. 794 | func (c *Container) SetKernelMemoryLimit(limit ByteSize) error { 795 | if err := c.makeSure(isDefined | isRunning); err != nil { 796 | return err 797 | } 798 | 799 | return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed) 800 | } 801 | 802 | // MemorySwapUsage returns memory+swap usage of the container in bytes. 803 | func (c *Container) MemorySwapUsage() (ByteSize, error) { 804 | if err := c.makeSure(isDefined | isRunning); err != nil { 805 | return -1, err 806 | } 807 | 808 | return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit) 809 | } 810 | 811 | // MemorySwapLimit returns the memory+swap limit of the container in bytes. 812 | func (c *Container) MemorySwapLimit() (ByteSize, error) { 813 | if err := c.makeSure(isDefined | isRunning); err != nil { 814 | return -1, err 815 | } 816 | 817 | return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit) 818 | } 819 | 820 | // SetMemorySwapLimit sets memory+swap limit of the container in bytes. 821 | func (c *Container) SetMemorySwapLimit(limit ByteSize) error { 822 | if err := c.makeSure(isDefined | isRunning); err != nil { 823 | return err 824 | } 825 | 826 | return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed) 827 | } 828 | 829 | // BlkioUsage returns number of bytes transferred to/from the disk by the container. 830 | func (c *Container) BlkioUsage() (ByteSize, error) { 831 | if err := c.makeSure(isDefined | isRunning); err != nil { 832 | return -1, err 833 | } 834 | 835 | c.mu.RLock() 836 | defer c.mu.RUnlock() 837 | 838 | for _, v := range c.CgroupItem("blkio.throttle.io_service_bytes") { 839 | b := strings.Split(v, " ") 840 | if b[0] == "Total" { 841 | blkioUsed, err := strconv.ParseFloat(b[1], 64) 842 | if err != nil { 843 | return -1, err 844 | } 845 | return ByteSize(blkioUsed), nil 846 | } 847 | } 848 | return -1, ErrBlkioUsage 849 | } 850 | 851 | // CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks 852 | // in this cgroup (including tasks lower in the hierarchy). 853 | func (c *Container) CPUTime() (time.Duration, error) { 854 | if err := c.makeSure(isDefined | isRunning); err != nil { 855 | return -1, err 856 | } 857 | 858 | c.mu.RLock() 859 | defer c.mu.RUnlock() 860 | 861 | cpuUsage, err := strconv.ParseInt(c.CgroupItem("cpuacct.usage")[0], 10, 64) 862 | if err != nil { 863 | return -1, err 864 | } 865 | return time.Duration(cpuUsage), nil 866 | } 867 | 868 | // CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by 869 | // all tasks in this cgroup (including tasks lower in the hierarchy). 870 | func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) { 871 | if err := c.makeSure(isDefined | isRunning); err != nil { 872 | return nil, err 873 | } 874 | 875 | c.mu.RLock() 876 | defer c.mu.RUnlock() 877 | 878 | cpuTimes := make(map[int]time.Duration) 879 | for i, v := range strings.Split(c.CgroupItem("cpuacct.usage_percpu")[0], " ") { 880 | cpuUsage, err := strconv.ParseInt(v, 10, 64) 881 | if err != nil { 882 | return nil, err 883 | } 884 | cpuTimes[i] = time.Duration(cpuUsage) 885 | } 886 | return cpuTimes, nil 887 | } 888 | 889 | // CPUStats returns the number of CPU cycles (in the units defined by USER_HZ on the system) 890 | // consumed by tasks in this cgroup and its children in both user mode and system (kernel) mode. 891 | func (c *Container) CPUStats() (map[string]int64, error) { 892 | if err := c.makeSure(isDefined | isRunning); err != nil { 893 | return nil, err 894 | } 895 | 896 | c.mu.RLock() 897 | defer c.mu.RUnlock() 898 | 899 | cpuStat := c.CgroupItem("cpuacct.stat") 900 | user, err := strconv.ParseInt(strings.Split(cpuStat[0], "user ")[1], 10, 64) 901 | if err != nil { 902 | return nil, err 903 | } 904 | system, err := strconv.ParseInt(strings.Split(cpuStat[1], "system ")[1], 10, 64) 905 | if err != nil { 906 | return nil, err 907 | } 908 | 909 | return map[string]int64{"user": user, "system": system}, nil 910 | } 911 | 912 | // ConsoleFd allocates a console tty from container 913 | // ttynum: tty number to attempt to allocate or -1 to allocate the first available tty 914 | // 915 | // Returns "ttyfd" on success, -1 on failure. The returned "ttyfd" is 916 | // used to keep the tty allocated. The caller should close "ttyfd" to 917 | // indicate that it is done with the allocated console so that it can 918 | // be allocated by another caller. 919 | func (c *Container) ConsoleFd(ttynum int) (int, error) { 920 | // FIXME: Make idiomatic 921 | if err := c.makeSure(isDefined | isRunning); err != nil { 922 | return -1, err 923 | } 924 | 925 | c.mu.Lock() 926 | defer c.mu.Unlock() 927 | 928 | ret := int(C.go_lxc_console_getfd(c.container, C.int(ttynum))) 929 | if ret < 0 { 930 | return -1, ErrAttachFailed 931 | } 932 | return ret, nil 933 | } 934 | 935 | // Console allocates and runs a console tty from container 936 | // ttynum: tty number to attempt to allocate, -1 to allocate the first available tty, or 0 to allocate the console 937 | // stdinfd: fd to read input from 938 | // stdoutfd: fd to write output to 939 | // stderrfd: fd to write error output to 940 | // escape: the escape character (1 == 'a', 2 == 'b', ...) 941 | // 942 | // This function will not return until the console has been exited by the user. 943 | func (c *Container) Console(ttynum int, stdinfd, stdoutfd, stderrfd uintptr, escape int) error { 944 | // FIXME: Make idiomatic 945 | if err := c.makeSure(isDefined | isRunning); err != nil { 946 | return err 947 | } 948 | 949 | c.mu.Lock() 950 | defer c.mu.Unlock() 951 | 952 | if !bool(C.go_lxc_console(c.container, C.int(ttynum), C.int(stdinfd), 953 | C.int(stdoutfd), C.int(stderrfd), C.int(escape))) { 954 | return ErrAttachFailed 955 | } 956 | return nil 957 | } 958 | 959 | // AttachShell attaches a shell to the container. 960 | func (c *Container) AttachShell() error { 961 | if err := c.makeSure(isDefined | isRunning); err != nil { 962 | return err 963 | } 964 | 965 | c.mu.Lock() 966 | defer c.mu.Unlock() 967 | 968 | if int(C.go_lxc_attach(c.container, false)) < 0 { 969 | return ErrAttachFailed 970 | } 971 | return nil 972 | } 973 | 974 | // AttachShellWithClearEnvironment attaches a shell to the container. 975 | // It clears all environment variables before attaching. 976 | func (c *Container) AttachShellWithClearEnvironment() error { 977 | if err := c.makeSure(isDefined | isRunning); err != nil { 978 | return err 979 | } 980 | 981 | c.mu.Lock() 982 | defer c.mu.Unlock() 983 | 984 | if int(C.go_lxc_attach(c.container, true)) < 0 { 985 | return ErrAttachFailed 986 | } 987 | return nil 988 | } 989 | 990 | // RunCommand runs the user specified command inside the container and waits for it to exit. 991 | // stdinfd: fd to read input from 992 | // stdoutfd: fd to write output to 993 | // stderrfd: fd to write error output to 994 | func (c *Container) RunCommand(stdinfd, stdoutfd, stderrfd uintptr, args ...string) (bool, error) { 995 | return c.runCommand(stdinfd, stdoutfd, stderrfd, false, args...) 996 | } 997 | 998 | // RunCommandWithClearEnvironment runs the user specified command inside the container 999 | // and waits for it to exit. It clears all environment variables before running. 1000 | // stdinfd: fd to read input from 1001 | // stdoutfd: fd to write output to 1002 | // stderrfd: fd to write error output to 1003 | func (c *Container) RunCommandWithClearEnvironment(stdinfd, stdoutfd, stderrfd uintptr, args ...string) (bool, error) { 1004 | return c.runCommand(stdinfd, stdoutfd, stderrfd, true, args...) 1005 | } 1006 | 1007 | func (c *Container) runCommand(stdinfd, stdoutfd, stderrfd uintptr, clearenv bool, args ...string) (bool, error) { 1008 | if args == nil { 1009 | return false, ErrInsufficientNumberOfArguments 1010 | } 1011 | 1012 | if err := c.makeSure(isDefined | isRunning); err != nil { 1013 | return false, err 1014 | } 1015 | 1016 | c.mu.Lock() 1017 | defer c.mu.Unlock() 1018 | 1019 | cargs := makeNullTerminatedArgs(args) 1020 | if cargs == nil { 1021 | return false, ErrAllocationFailed 1022 | } 1023 | defer freeNullTerminatedArgs(cargs, len(args)) 1024 | 1025 | ret := int(C.go_lxc_attach_run_wait(c.container, C.bool(clearenv), C.int(stdinfd), C.int(stdoutfd), C.int(stderrfd), cargs)) 1026 | 1027 | if ret < 0 { 1028 | return false, ErrAttachFailed 1029 | } 1030 | return ret == 0, nil 1031 | } 1032 | 1033 | // Interfaces returns the names of the network interfaces. 1034 | func (c *Container) Interfaces() ([]string, error) { 1035 | if err := c.makeSure(isDefined | isRunning); err != nil { 1036 | return nil, err 1037 | } 1038 | 1039 | c.mu.RLock() 1040 | defer c.mu.RUnlock() 1041 | 1042 | result := C.go_lxc_get_interfaces(c.container) 1043 | if result == nil { 1044 | return nil, ErrInterfaces 1045 | } 1046 | return convertArgs(result), nil 1047 | } 1048 | 1049 | // InterfaceStats returns the stats about container's network interfaces 1050 | func (c *Container) InterfaceStats() (map[string]map[string]ByteSize, error) { 1051 | if err := c.makeSure(isDefined | isRunning); err != nil { 1052 | return nil, err 1053 | } 1054 | 1055 | c.mu.RLock() 1056 | defer c.mu.RUnlock() 1057 | 1058 | var interfaceName string 1059 | 1060 | statistics := make(map[string]map[string]ByteSize) 1061 | 1062 | for i := 0; i < len(c.ConfigItem("lxc.network")); i++ { 1063 | interfaceType := c.RunningConfigItem(fmt.Sprintf("lxc.network.%d.type", i)) 1064 | if interfaceType == nil { 1065 | continue 1066 | } 1067 | 1068 | if interfaceType[0] == "veth" { 1069 | interfaceName = c.RunningConfigItem(fmt.Sprintf("lxc.network.%d.veth.pair", i))[0] 1070 | } else { 1071 | interfaceName = c.RunningConfigItem(fmt.Sprintf("lxc.network.%d.link", i))[0] 1072 | } 1073 | 1074 | for _, v := range []string{"rx", "tx"} { 1075 | /* tx and rx are reversed from the host vs container */ 1076 | content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/statistics/%s_bytes", interfaceName, v)) 1077 | if err != nil { 1078 | return nil, err 1079 | } 1080 | 1081 | bytes, err := strconv.ParseInt(strings.Split(string(content), "\n")[0], 10, 64) 1082 | if err != nil { 1083 | return nil, err 1084 | } 1085 | 1086 | if statistics[interfaceName] == nil { 1087 | statistics[interfaceName] = make(map[string]ByteSize) 1088 | } 1089 | statistics[interfaceName][v] = ByteSize(bytes) 1090 | } 1091 | } 1092 | 1093 | return statistics, nil 1094 | } 1095 | 1096 | // IPAddress returns the IP address of the given network interface. 1097 | func (c *Container) IPAddress(interfaceName string) ([]string, error) { 1098 | if err := c.makeSure(isDefined | isRunning); err != nil { 1099 | return nil, err 1100 | } 1101 | 1102 | c.mu.RLock() 1103 | defer c.mu.RUnlock() 1104 | 1105 | cinterface := C.CString(interfaceName) 1106 | defer C.free(unsafe.Pointer(cinterface)) 1107 | 1108 | result := C.go_lxc_get_ips(c.container, cinterface, nil, 0) 1109 | if result == nil { 1110 | return nil, ErrIPAddress 1111 | } 1112 | return convertArgs(result), nil 1113 | } 1114 | 1115 | // IPAddresses returns all IP addresses. 1116 | func (c *Container) IPAddresses() ([]string, error) { 1117 | if err := c.makeSure(isDefined | isRunning); err != nil { 1118 | return nil, err 1119 | } 1120 | 1121 | c.mu.RLock() 1122 | defer c.mu.RUnlock() 1123 | 1124 | result := C.go_lxc_get_ips(c.container, nil, nil, 0) 1125 | if result == nil { 1126 | return nil, ErrIPAddresses 1127 | } 1128 | return convertArgs(result), nil 1129 | 1130 | } 1131 | 1132 | // IPv4Addresses returns all IPv4 addresses. 1133 | func (c *Container) IPv4Addresses() ([]string, error) { 1134 | if err := c.makeSure(isDefined | isRunning); err != nil { 1135 | return nil, err 1136 | } 1137 | 1138 | c.mu.RLock() 1139 | defer c.mu.RUnlock() 1140 | 1141 | cfamily := C.CString("inet") 1142 | defer C.free(unsafe.Pointer(cfamily)) 1143 | 1144 | result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) 1145 | if result == nil { 1146 | return nil, ErrIPv4Addresses 1147 | } 1148 | return convertArgs(result), nil 1149 | } 1150 | 1151 | // IPv6Addresses returns all IPv6 addresses. 1152 | func (c *Container) IPv6Addresses() ([]string, error) { 1153 | if err := c.makeSure(isDefined | isRunning); err != nil { 1154 | return nil, err 1155 | } 1156 | 1157 | c.mu.RLock() 1158 | defer c.mu.RUnlock() 1159 | 1160 | cfamily := C.CString("inet6") 1161 | defer C.free(unsafe.Pointer(cfamily)) 1162 | 1163 | result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) 1164 | if result == nil { 1165 | return nil, ErrIPv6Addresses 1166 | } 1167 | return convertArgs(result), nil 1168 | } 1169 | 1170 | // LogFile returns the name of the logfile. 1171 | func (c *Container) LogFile() string { 1172 | return c.ConfigItem("lxc.logfile")[0] 1173 | } 1174 | 1175 | // SetLogFile sets the name of the logfile. 1176 | func (c *Container) SetLogFile(filename string) error { 1177 | if err := c.SetConfigItem("lxc.logfile", filename); err != nil { 1178 | return err 1179 | } 1180 | return nil 1181 | } 1182 | 1183 | // LogLevel returns the level of the logfile. 1184 | func (c *Container) LogLevel() LogLevel { 1185 | return logLevelMap[c.ConfigItem("lxc.loglevel")[0]] 1186 | } 1187 | 1188 | // SetLogLevel sets the level of the logfile. 1189 | func (c *Container) SetLogLevel(level LogLevel) error { 1190 | if err := c.SetConfigItem("lxc.loglevel", level.String()); err != nil { 1191 | return err 1192 | } 1193 | return nil 1194 | } 1195 | 1196 | // AddDeviceNode adds specified device to the container. 1197 | func (c *Container) AddDeviceNode(source string, destination ...string) error { 1198 | if err := c.makeSure(isDefined | isRunning); err != nil { 1199 | return err 1200 | } 1201 | 1202 | c.mu.Lock() 1203 | defer c.mu.Unlock() 1204 | 1205 | csource := C.CString(source) 1206 | defer C.free(unsafe.Pointer(csource)) 1207 | 1208 | if destination != nil && len(destination) == 1 { 1209 | cdestination := C.CString(destination[0]) 1210 | defer C.free(unsafe.Pointer(cdestination)) 1211 | 1212 | if !bool(C.go_lxc_add_device_node(c.container, csource, cdestination)) { 1213 | return ErrAddDeviceNodeFailed 1214 | } 1215 | return nil 1216 | } 1217 | 1218 | if !bool(C.go_lxc_add_device_node(c.container, csource, nil)) { 1219 | return ErrAddDeviceNodeFailed 1220 | } 1221 | return nil 1222 | 1223 | } 1224 | 1225 | // RemoveDeviceNode removes the specified device from the container. 1226 | func (c *Container) RemoveDeviceNode(source string, destination ...string) error { 1227 | if err := c.makeSure(isDefined | isRunning); err != nil { 1228 | return err 1229 | } 1230 | 1231 | c.mu.Lock() 1232 | defer c.mu.Unlock() 1233 | 1234 | csource := C.CString(source) 1235 | defer C.free(unsafe.Pointer(csource)) 1236 | 1237 | if destination != nil && len(destination) == 1 { 1238 | cdestination := C.CString(destination[0]) 1239 | defer C.free(unsafe.Pointer(cdestination)) 1240 | 1241 | if !bool(C.go_lxc_remove_device_node(c.container, csource, cdestination)) { 1242 | return ErrRemoveDeviceNodeFailed 1243 | } 1244 | return nil 1245 | } 1246 | 1247 | if !bool(C.go_lxc_remove_device_node(c.container, csource, nil)) { 1248 | return ErrRemoveDeviceNodeFailed 1249 | } 1250 | return nil 1251 | } 1252 | --------------------------------------------------------------------------------