pax_global_header00006660000000000000000000000064132304123120014501gustar00rootroot0000000000000052 comment=b964baab402d04122567df45c56559f64512f143 golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/000077500000000000000000000000001323041231200210745ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/.gitignore000066400000000000000000000012631323041231200230660ustar00rootroot00000000000000examples/attach examples/attach_with_pipes examples/checkpoint examples/clone examples/concurrent_create examples/concurrent_destroy examples/concurrent_shutdown examples/concurrent_start examples/concurrent_stop examples/concurrent_stress examples/config examples/console examples/create examples/create_snapshot examples/destroy examples/destroy_snapshots examples/device_add_remove examples/execute examples/freeze examples/interfaces examples/ipaddress examples/limit examples/list examples/list_keys examples/list_snapshots examples/reboot examples/rename examples/restore_snapshot examples/shutdown examples/start examples/stats examples/stop examples/unfreeze coverage.out tags *.swp golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/.travis.yml000066400000000000000000000020571323041231200232110ustar00rootroot00000000000000language: go os: - linux go: - 1.6 - 1.7 - 1.8 - 1.9 - tip matrix: fast_finish: true allow_failures: - go: tip before_install: - sudo add-apt-repository ppa:ubuntu-lxc/daily -y - sudo apt-get update - sudo apt-get install -qq lxc lxc-dev uidmap - echo "${USER}:100000:65536" | sudo tee /etc/subuid - echo "${USER}:100000:65536" | sudo tee /etc/subgid - echo "${USER} veth lxcbr0 10" | sudo tee -a /etc/lxc/lxc-usernet - mkdir -p ~/.config/lxc/ - cp /etc/lxc/default.conf ~/.config/lxc/default.conf - echo "lxc.idmap = u 0 100000 65536" | sudo tee -a ~/.config/lxc/default.conf - echo "lxc.idmap = g 0 100000 65536" | sudo tee -a ~/.config/lxc/default.conf - "make setup-test-cgroup" - mkdir -p ~/.local/share - chmod +x ~/.local/share - chmod +x ~/.local/ - chmod +x ${HOME} install: - go get gopkg.in/lxc/go-lxc.v2 script: - "make all" - "make test" - "make test-race" - "make test-unprivileged" - "make test-unprivileged-race" - "make cover" notifications: webhooks: https://linuxcontainers.org/webhook-lxcbot/ golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/AUTHORS000066400000000000000000000010321323041231200221400ustar00rootroot00000000000000# This is the official list of Go-LXC authors for copyright purposes. # Names should be added to this file as #Name or Organization # The email address is not required for organizations. # Please keep the list sorted. David Cramer Fatih Arslan Kelsey Hightower S.Çağlar Onur Serge Hallyn Stéphane Graber Syed Tycho Andersen golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/LICENSE000066400000000000000000000657151323041231200221170ustar00rootroot00000000000000This software is licensed under the LGPLv2.1, included below. As a special exception to the GNU Lesser General Public License version 2.1 ("LGPL2.1"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code or providing the installation information, provided that you comply with the other provisions of LGPL2.1 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL2.1 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/Makefile000066400000000000000000000026761323041231200225470ustar00rootroot00000000000000NO_COLOR=\033[0m OK_COLOR=\033[0;32m all: format vet lint format: @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" @gofmt -s -w *.go @goimports -w *.go || true test: @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" @sudo `which go` test -v test-race: @echo "$(OK_COLOR)==> Running go test $(NO_COLOR)" @sudo `which go` test -race -v test-unprivileged: @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" @`which go` test -v test-unprivileged-race: @echo "$(OK_COLOR)==> Running go test for unprivileged user$(NO_COLOR)" @`which go` test -race -v cover: @sudo `which go` test -v -coverprofile=coverage.out @`which go` tool cover -func=coverage.out doc: @`which godoc` gopkg.in/lxc/go-lxc.v2 | less vet: @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" @`which go` vet . lint: @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" @`which golint` . || true escape-analysis: @go build -gcflags -m ctags: @ctags -R --languages=c,go scope: @echo "$(OK_COLOR)==> Exported container calls in container.go $(NO_COLOR)" @/bin/grep -E "\bc+\.([A-Z])\w+" container.go || true setup-test-cgroup: for d in /sys/fs/cgroup/*; do \ [ -f $$d/cgroup.clone_children ] && echo 1 | sudo tee $$d/cgroup.clone_children; \ [ -f $$d/cgroup.use_hierarchy ] && echo 1 | sudo tee $$d/cgroup.use_hierarchy; \ sudo mkdir -p $$d/lxc; \ sudo chown -R $$USER: $$d/lxc; \ done .PHONY: all format test doc vet lint ctags golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/README.md000066400000000000000000000023461323041231200223600ustar00rootroot00000000000000# Go Bindings for LXC (Linux Containers) This package implements [Go](http://golang.org) bindings for the [LXC](http://linuxcontainers.org/) C API (liblxc). ## Requirements This package requires [LXC 1.x](https://github.com/lxc/lxc/releases) and its development package to be installed. Works with [Go 1.x](http://golang.org/dl). Following command should install required dependencies on Ubuntu: apt-get install -y pkg-config lxc-dev ## Installing To install it, run: go get gopkg.in/lxc/go-lxc.v2 ## Documentation Documentation can be found at [GoDoc](http://godoc.org/gopkg.in/lxc/go-lxc.v2). ## Stability The package API will remain stable as described in [gopkg.in](https://gopkg.in). ## Examples See the [examples](https://github.com/lxc/go-lxc/tree/v2/examples) directory for some. ## Contributing We'd love to see go-lxc improve. To contribute to go-lxc; * **Fork** the repository * **Modify** your fork * Ensure your fork **passes all tests** * **Send** a pull request * Bonus points if the pull request includes *what* you changed, *why* you changed it, and *tests* attached. * For the love of all that is holy, please use `go fmt` *before* you send the pull request. We'll review it and merge it in if it's appropriate. golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/container.go000066400000000000000000001313001323041231200234030ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc // #include // #include // #include "lxc-binding.h" import "C" import ( "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "reflect" "strconv" "strings" "sync" "syscall" "time" "unsafe" ) // Container struct type Container struct { mu sync.RWMutex container *C.struct_lxc_container verbosity Verbosity } // Snapshot struct type Snapshot struct { Name string CommentPath string Timestamp string Path string } const ( isDefined = 1 << iota isNotDefined isRunning isNotRunning isPrivileged isUnprivileged isGreaterEqualThanLXC11 isGreaterEqualThanLXC20 ) func (c *Container) makeSure(flags int) error { if flags&isDefined != 0 && !c.defined() { return fmt.Errorf("%s: %q", ErrNotDefined, c.name()) } if flags&isNotDefined != 0 && c.defined() { return fmt.Errorf("%s: %q", ErrAlreadyDefined, c.name()) } if flags&isRunning != 0 && !c.running() { return fmt.Errorf("%s: %q", ErrNotRunning, c.name()) } if flags&isNotRunning != 0 && c.running() { return fmt.Errorf("%s: %q", ErrAlreadyRunning, c.name()) } if flags&isPrivileged != 0 && os.Geteuid() != 0 { return ErrMethodNotAllowed } if flags&isGreaterEqualThanLXC11 != 0 && !VersionAtLeast(1, 1, 0) { return ErrNotSupported } if flags&isGreaterEqualThanLXC20 != 0 && !VersionAtLeast(2, 0, 0) { return ErrNotSupported } return nil } func (c *Container) cgroupItemAsByteSize(filename string, missing error) (ByteSize, error) { size, err := strconv.ParseFloat(c.cgroupItem(filename)[0], 64) if err != nil { return -1, missing } return ByteSize(size), nil } func (c *Container) setCgroupItemWithByteSize(filename string, limit ByteSize, missing error) error { if err := c.setCgroupItem(filename, fmt.Sprintf("%.f", limit)); err != nil { return missing } return nil } func (c *Container) name() string { return C.GoString(c.container.name) } // Name returns the name of the container. func (c *Container) Name() string { c.mu.RLock() defer c.mu.RUnlock() return c.name() } // String returns the string represantation of container. func (c *Container) String() string { c.mu.RLock() defer c.mu.RUnlock() return path.Join(c.configPath(), c.name()) } // Caller needs to hold the lock func (c *Container) defined() bool { return bool(C.go_lxc_defined(c.container)) } // Defined returns true if the container is already defined. func (c *Container) Defined() bool { c.mu.RLock() defer c.mu.RUnlock() return c.defined() } // Caller needs to hold the lock func (c *Container) running() bool { return bool(C.go_lxc_running(c.container)) } // Running returns true if the container is already running. func (c *Container) Running() bool { c.mu.RLock() defer c.mu.RUnlock() return c.running() } // Controllable returns true if the caller can control the container. func (c *Container) Controllable() bool { c.mu.RLock() defer c.mu.RUnlock() return bool(C.go_lxc_may_control(c.container)) } // CreateSnapshot creates a new snapshot. func (c *Container) CreateSnapshot() (*Snapshot, error) { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined | isNotRunning); err != nil { return nil, err } ret := int(C.go_lxc_snapshot(c.container)) if ret < 0 { return nil, ErrCreateSnapshotFailed } return &Snapshot{Name: fmt.Sprintf("snap%d", ret)}, nil } // RestoreSnapshot creates a new container based on a snapshot. func (c *Container) RestoreSnapshot(snapshot Snapshot, name string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined); err != nil { return err } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) csnapname := C.CString(snapshot.Name) defer C.free(unsafe.Pointer(csnapname)) if !bool(C.go_lxc_snapshot_restore(c.container, csnapname, cname)) { return ErrRestoreSnapshotFailed } return nil } // DestroySnapshot destroys the specified snapshot. func (c *Container) DestroySnapshot(snapshot Snapshot) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined); err != nil { return err } csnapname := C.CString(snapshot.Name) defer C.free(unsafe.Pointer(csnapname)) if !bool(C.go_lxc_snapshot_destroy(c.container, csnapname)) { return ErrDestroySnapshotFailed } return nil } // DestroyAllSnapshots destroys all the snapshot. func (c *Container) DestroyAllSnapshots() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined | isGreaterEqualThanLXC11); err != nil { return err } if !bool(C.go_lxc_snapshot_destroy_all(c.container)) { return ErrDestroyAllSnapshotsFailed } return nil } // Snapshots returns the list of container snapshots. func (c *Container) Snapshots() ([]Snapshot, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isDefined); err != nil { return nil, err } var csnapshots *C.struct_lxc_snapshot size := int(C.go_lxc_snapshot_list(c.container, &csnapshots)) defer freeSnapshots(csnapshots, size) if size < 1 { return nil, ErrNoSnapshot } hdr := reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(csnapshots)), Len: size, Cap: size, } gosnapshots := *(*[]C.struct_lxc_snapshot)(unsafe.Pointer(&hdr)) snapshots := make([]Snapshot, size, size) for i := 0; i < size; i++ { snapshots[i] = Snapshot{ Name: C.GoString(gosnapshots[i].name), Timestamp: C.GoString(gosnapshots[i].timestamp), CommentPath: C.GoString(gosnapshots[i].comment_pathname), Path: C.GoString(gosnapshots[i].lxcpath), } } return snapshots, nil } // Caller needs to hold the lock func (c *Container) state() State { return StateMap[C.GoString(C.go_lxc_state(c.container))] } // State returns the state of the container. func (c *Container) State() State { c.mu.RLock() defer c.mu.RUnlock() return c.state() } // InitPid returns the process ID of the container's init process // seen from outside the container. func (c *Container) InitPid() int { c.mu.RLock() defer c.mu.RUnlock() return int(C.go_lxc_init_pid(c.container)) } // Daemonize returns true if the container wished to be daemonized. func (c *Container) Daemonize() bool { c.mu.RLock() defer c.mu.RUnlock() return bool(c.container.daemonize) } // WantDaemonize determines if the container wants to run daemonized. func (c *Container) WantDaemonize(state bool) error { c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_want_daemonize(c.container, C.bool(state))) { return ErrDaemonizeFailed } return nil } // WantCloseAllFds determines whether container wishes all file descriptors // to be closed on startup. func (c *Container) WantCloseAllFds(state bool) error { c.mu.Lock() defer c.mu.Unlock() if !bool(C.go_lxc_want_close_all_fds(c.container, C.bool(state))) { return ErrCloseAllFdsFailed } return nil } // SetVerbosity sets the verbosity level of some API calls func (c *Container) SetVerbosity(verbosity Verbosity) { c.mu.Lock() defer c.mu.Unlock() c.verbosity = verbosity } // Freeze freezes the running container. func (c *Container) Freeze() error { c.mu.Lock() defer c.mu.Unlock() // check the state using lockless version if c.state() == FROZEN { return ErrAlreadyFrozen } if !bool(C.go_lxc_freeze(c.container)) { return ErrFreezeFailed } return nil } // Unfreeze thaws the frozen container. func (c *Container) Unfreeze() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } // check the state using lockless version if c.state() != FROZEN { return ErrNotFrozen } if !bool(C.go_lxc_unfreeze(c.container)) { return ErrUnfreezeFailed } return nil } // Create creates the container using given TemplateOptions func (c *Container) Create(options TemplateOptions) error { c.mu.Lock() defer c.mu.Unlock() // FIXME: Support bdev_specs // // bdev_specs: // zfs requires zfsroot // lvm requires lvname/vgname/thinpool as well as fstype and fssize // btrfs requires nothing // dir requires nothing if err := c.makeSure(isNotDefined); err != nil { return err } // use download template if not set if options.Template == "" { options.Template = "download" } // use Directory backend if not set if options.Backend == 0 { options.Backend = Directory } var args []string if options.Template == "download" { // required parameters if options.Distro == "" || options.Release == "" || options.Arch == "" { return ErrInsufficientNumberOfArguments } args = append(args, "--dist", options.Distro, "--release", options.Release, "--arch", options.Arch) // optional arguments if options.Variant != "" { args = append(args, "--variant", options.Variant) } if options.Server != "" { args = append(args, "--server", options.Server) } if options.KeyID != "" { args = append(args, "--keyid", options.KeyID) } if options.KeyServer != "" { args = append(args, "--keyserver", options.KeyServer) } if options.DisableGPGValidation { args = append(args, "--no-validate") } if options.FlushCache { args = append(args, "--flush-cache") } if options.ForceCache { args = append(args, "--force-cache") } } else { // optional arguments if options.Release != "" { args = append(args, "--release", options.Release) } if options.Arch != "" { args = append(args, "--arch", options.Arch) } if options.FlushCache { args = append(args, "--flush-cache") } } if options.ExtraArgs != nil { args = append(args, options.ExtraArgs...) } ctemplate := C.CString(options.Template) defer C.free(unsafe.Pointer(ctemplate)) cbackend := C.CString(options.Backend.String()) defer C.free(unsafe.Pointer(cbackend)) ret := false if args != nil { cargs := makeNullTerminatedArgs(args) if cargs == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), cargs)) } else { ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, C.int(c.verbosity), nil)) } if !ret { return ErrCreateFailed } return nil } // Start starts the container. func (c *Container) Start() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isNotRunning); err != nil { return err } if !bool(C.go_lxc_start(c.container, 0, nil)) { return ErrStartFailed } return nil } // StartWithArgs starts the container using given arguments. func (c *Container) StartWithArgs(args []string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isNotRunning); err != nil { return err } if !bool(C.go_lxc_start(c.container, 0, makeNullTerminatedArgs(args))) { return ErrStartFailed } return nil } // StartExecute starts a container. It runs a minimal init as PID 1 and the // requested program as the second process. func (c *Container) StartExecute(args []string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isNotRunning); err != nil { return err } if !bool(C.go_lxc_start(c.container, 1, makeNullTerminatedArgs(args))) { return ErrStartFailed } return nil } // Execute executes the given command in a temporary container. func (c *Container) Execute(args ...string) ([]byte, error) { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isNotDefined); err != nil { return nil, err } os.MkdirAll(filepath.Join(c.configPath(), c.name()), 0700) c.saveConfigFile(filepath.Join(c.configPath(), c.name(), "config")) defer os.RemoveAll(filepath.Join(c.configPath(), c.name())) cargs := []string{"lxc-execute", "-n", c.name(), "-P", c.configPath(), "--"} cargs = append(cargs, args...) // FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now // go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput() if err != nil { return nil, ErrExecuteFailed } return output, nil } // Stop stops the container. func (c *Container) Stop() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } if !bool(C.go_lxc_stop(c.container)) { return ErrStopFailed } return nil } // Reboot reboots the container. func (c *Container) Reboot() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } if !bool(C.go_lxc_reboot(c.container)) { return ErrRebootFailed } return nil } // Shutdown shuts down the container. func (c *Container) Shutdown(timeout time.Duration) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } if !bool(C.go_lxc_shutdown(c.container, C.int(timeout.Seconds()))) { return ErrShutdownFailed } return nil } // Destroy destroys the container. func (c *Container) Destroy() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined | isNotRunning); err != nil { return err } if !bool(C.go_lxc_destroy(c.container)) { return ErrDestroyFailed } return nil } // DestroyWithAllSnapshots destroys the container and its snapshots func (c *Container) DestroyWithAllSnapshots() error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined | isNotRunning | isGreaterEqualThanLXC11); err != nil { return err } if !bool(C.go_lxc_destroy_with_snapshots(c.container)) { return ErrDestroyWithAllSnapshotsFailed } return nil } // Clone clones the container using given arguments with specified backend. func (c *Container) Clone(name string, options CloneOptions) error { c.mu.Lock() defer c.mu.Unlock() // FIXME: bdevdata, newsize and hookargs // // bdevdata: // zfs requires zfsroot // lvm requires lvname/vgname/thinpool as well as fstype and fssize // btrfs requires nothing // dir requires nothing // // newsize: for blockdev-backed backingstores // // hookargs: additional arguments to pass to the clone hook script if err := c.makeSure(isDefined | isNotRunning); err != nil { return err } // use Directory backend if not set if options.Backend == 0 { options.Backend = Directory } var flags int if options.KeepName { flags |= C.LXC_CLONE_KEEPNAME } if options.KeepMAC { flags |= C.LXC_CLONE_KEEPMACADDR } if options.Snapshot { flags |= C.LXC_CLONE_SNAPSHOT } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) cbackend := C.CString(options.Backend.String()) defer C.free(unsafe.Pointer(cbackend)) if options.ConfigPath != "" { clxcpath := C.CString(options.ConfigPath) defer C.free(unsafe.Pointer(clxcpath)) if !bool(C.go_lxc_clone(c.container, cname, clxcpath, C.int(flags), cbackend)) { return ErrCloneFailed } } else { if !bool(C.go_lxc_clone(c.container, cname, nil, C.int(flags), cbackend)) { return ErrCloneFailed } } return nil } // Rename renames the container. func (c *Container) Rename(name string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isDefined | isNotRunning); err != nil { return err } cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) if !bool(C.go_lxc_rename(c.container, cname)) { return ErrRenameFailed } return nil } // Wait waits for container to reach a particular state. func (c *Container) Wait(state State, timeout time.Duration) bool { c.mu.Lock() defer c.mu.Unlock() cstate := C.CString(state.String()) defer C.free(unsafe.Pointer(cstate)) return bool(C.go_lxc_wait(c.container, cstate, C.int(timeout.Seconds()))) } // ConfigFileName returns the container's configuration file's name. func (c *Container) ConfigFileName() string { c.mu.RLock() defer c.mu.RUnlock() // allocated in lxc.c configFileName := C.go_lxc_config_file_name(c.container) defer C.free(unsafe.Pointer(configFileName)) return C.GoString(configFileName) } func (c *Container) configItem(key string) []string { ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c configItem := C.go_lxc_get_config_item(c.container, ckey) defer C.free(unsafe.Pointer(configItem)) ret := strings.TrimSpace(C.GoString(configItem)) return strings.Split(ret, "\n") } // ConfigItem returns the value of the given config item. func (c *Container) ConfigItem(key string) []string { c.mu.RLock() defer c.mu.RUnlock() return c.configItem(key) } func (c *Container) setConfigItem(key string, value string) error { ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) cvalue := C.CString(value) defer C.free(unsafe.Pointer(cvalue)) if !bool(C.go_lxc_set_config_item(c.container, ckey, cvalue)) { return ErrSettingConfigItemFailed } return nil } // SetConfigItem sets the value of the given config item. func (c *Container) SetConfigItem(key string, value string) error { c.mu.Lock() defer c.mu.Unlock() return c.setConfigItem(key, value) } func (c *Container) runningConfigItem(key string) []string { ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c configItem := C.go_lxc_get_running_config_item(c.container, ckey) defer C.free(unsafe.Pointer(configItem)) ret := strings.TrimSpace(C.GoString(configItem)) return strings.Split(ret, "\n") } // RunningConfigItem returns the value of the given config item. func (c *Container) RunningConfigItem(key string) []string { c.mu.RLock() defer c.mu.RUnlock() return c.runningConfigItem(key) } func (c *Container) cgroupItem(key string) []string { ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c cgroupItem := C.go_lxc_get_cgroup_item(c.container, ckey) defer C.free(unsafe.Pointer(cgroupItem)) ret := strings.TrimSpace(C.GoString(cgroupItem)) return strings.Split(ret, "\n") } func (c *Container) setCgroupItem(key string, value string) error { ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) cvalue := C.CString(value) defer C.free(unsafe.Pointer(cvalue)) if !bool(C.go_lxc_set_cgroup_item(c.container, ckey, cvalue)) { return ErrSettingCgroupItemFailed } return nil } // CgroupItem returns the value of the given cgroup subsystem value. func (c *Container) CgroupItem(key string) []string { c.mu.RLock() defer c.mu.RUnlock() return c.cgroupItem(key) } // SetCgroupItem sets the value of given cgroup subsystem value. func (c *Container) SetCgroupItem(key string, value string) error { c.mu.Lock() defer c.mu.Unlock() return c.setCgroupItem(key, value) } // ClearConfig completely clears the containers in-memory configuration. func (c *Container) ClearConfig() { c.mu.Lock() defer c.mu.Unlock() C.go_lxc_clear_config(c.container) } // ClearConfigItem clears the value of given config item. func (c *Container) ClearConfigItem(key string) error { c.mu.Lock() defer c.mu.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) if !bool(C.go_lxc_clear_config_item(c.container, ckey)) { return ErrClearingConfigItemFailed } return nil } // ConfigKeys returns the names of the config items. func (c *Container) ConfigKeys(key ...string) []string { c.mu.RLock() defer c.mu.RUnlock() var keys *_Ctype_char if key != nil && len(key) == 1 { ckey := C.CString(key[0]) defer C.free(unsafe.Pointer(ckey)) // allocated in lxc.c keys = C.go_lxc_get_keys(c.container, ckey) defer C.free(unsafe.Pointer(keys)) } else { // allocated in lxc.c keys = C.go_lxc_get_keys(c.container, nil) defer C.free(unsafe.Pointer(keys)) } ret := strings.TrimSpace(C.GoString(keys)) return strings.Split(ret, "\n") } // LoadConfigFile loads the configuration file from given path. func (c *Container) LoadConfigFile(path string) error { c.mu.Lock() defer c.mu.Unlock() cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_load_config(c.container, cpath)) { return ErrLoadConfigFailed } return nil } func (c *Container) saveConfigFile(path string) error { cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_save_config(c.container, cpath)) { return ErrSaveConfigFailed } return nil } // SaveConfigFile saves the configuration file to given path. func (c *Container) SaveConfigFile(path string) error { c.mu.Lock() defer c.mu.Unlock() return c.saveConfigFile(path) } func (c *Container) configPath() string { return C.GoString(C.go_lxc_get_config_path(c.container)) } // ConfigPath returns the configuration file's path. func (c *Container) ConfigPath() string { c.mu.RLock() defer c.mu.RUnlock() return c.configPath() } // SetConfigPath sets the configuration file's path. func (c *Container) SetConfigPath(path string) error { c.mu.Lock() defer c.mu.Unlock() cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_set_config_path(c.container, cpath)) { return ErrSettingConfigPathFailed } return nil } // MemoryUsage returns memory usage of the container in bytes. func (c *Container) MemoryUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit) } // MemoryLimit returns memory limit of the container in bytes. func (c *Container) MemoryLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit) } // SetMemoryLimit sets memory limit of the container in bytes. func (c *Container) SetMemoryLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed) } // SoftMemoryLimit returns soft memory limit of the container in bytes. func (c *Container) SoftMemoryLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit) } // SetSoftMemoryLimit sets soft memory limit of the container in bytes. func (c *Container) SetSoftMemoryLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed) } // KernelMemoryUsage returns current kernel memory allocation of the container in bytes. func (c *Container) KernelMemoryUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) } // KernelMemoryLimit returns kernel memory limit of the container in bytes. func (c *Container) KernelMemoryLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) } // SetKernelMemoryLimit sets kernel memory limit of the container in bytes. func (c *Container) SetKernelMemoryLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed) } // MemorySwapUsage returns memory+swap usage of the container in bytes. func (c *Container) MemorySwapUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit) } // MemorySwapLimit returns the memory+swap limit of the container in bytes. func (c *Container) MemorySwapLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit) } // SetMemorySwapLimit sets memory+swap limit of the container in bytes. func (c *Container) SetMemorySwapLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed) } // BlkioUsage returns number of bytes transferred to/from the disk by the container. func (c *Container) BlkioUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } ioServiceBytes := c.cgroupItem("blkio.throttle.io_service_bytes") if ioServiceBytes[0] == "" { return 0, nil } for _, v := range ioServiceBytes { b := strings.Split(v, " ") if b[0] == "Total" { blkioUsed, err := strconv.ParseFloat(b[1], 64) if err != nil { return -1, err } return ByteSize(blkioUsed), nil } } return -1, ErrBlkioUsage } // CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks // in this cgroup (including tasks lower in the hierarchy). func (c *Container) CPUTime() (time.Duration, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } usage := c.cgroupItem("cpuacct.usage") if usage[0] == "" { return 0, nil } cpuUsage, err := strconv.ParseInt(usage[0], 10, 64) if err != nil { return -1, err } return time.Duration(cpuUsage), nil } // CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by // all tasks in this cgroup (including tasks lower in the hierarchy). func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } usagePerCPU := c.cgroupItem("cpuacct.usage_percpu") if usagePerCPU[0] == "" { return map[int]time.Duration{0: 0}, nil } cpuTimes := make(map[int]time.Duration) for i, v := range strings.Split(usagePerCPU[0], " ") { cpuUsage, err := strconv.ParseInt(v, 10, 64) if err != nil { return nil, err } cpuTimes[i] = time.Duration(cpuUsage) } return cpuTimes, nil } // CPUStats returns the number of CPU cycles (in the units defined by USER_HZ on the system) // consumed by tasks in this cgroup and its children in both user mode and system (kernel) mode. func (c *Container) CPUStats() (map[string]int64, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } stat := c.cgroupItem("cpuacct.stat") if stat[0] == "" { return map[string]int64{"user": 0, "system": 0}, nil } user, err := strconv.ParseInt(strings.Split(stat[0], "user ")[1], 10, 64) if err != nil { return nil, err } system, err := strconv.ParseInt(strings.Split(stat[1], "system ")[1], 10, 64) if err != nil { return nil, err } return map[string]int64{"user": user, "system": system}, nil } // ConsoleFd allocates a console tty from container // ttynum: tty number to attempt to allocate or -1 to allocate the first available tty // // Returns "ttyfd" on success, -1 on failure. The returned "ttyfd" is // used to keep the tty allocated. The caller should close "ttyfd" to // indicate that it is done with the allocated console so that it can // be allocated by another caller. func (c *Container) ConsoleFd(ttynum int) (int, error) { c.mu.Lock() defer c.mu.Unlock() // FIXME: Make idiomatic if err := c.makeSure(isRunning); err != nil { return -1, err } ret := int(C.go_lxc_console_getfd(c.container, C.int(ttynum))) if ret < 0 { return -1, ErrAttachFailed } return ret, nil } // Console allocates and runs a console tty from container // // This function will not return until the console has been exited by the user. func (c *Container) Console(options ConsoleOptions) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } ret := bool(C.go_lxc_console(c.container, C.int(options.Tty), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), C.int(options.EscapeCharacter))) if !ret { return ErrAttachFailed } return nil } // AttachShell attaches a shell to the container. // It clears all environment variables before attaching. func (c *Container) AttachShell(options AttachOptions) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) ret := int(C.go_lxc_attach(c.container, C.bool(options.ClearEnv), C.int(options.Namespaces), C.long(options.Arch), C.uid_t(options.UID), C.gid_t(options.GID), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, )) if ret < 0 { return ErrAttachFailed } return nil } func (c *Container) runCommandStatus(args []string, options AttachOptions) (int, error) { if len(args) == 0 { return -1, ErrInsufficientNumberOfArguments } if err := c.makeSure(isRunning); err != nil { return -1, err } cargs := makeNullTerminatedArgs(args) if cargs == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) ret := int(C.go_lxc_attach_run_wait( c.container, C.bool(options.ClearEnv), C.int(options.Namespaces), C.long(options.Arch), C.uid_t(options.UID), C.gid_t(options.GID), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, cargs, )) return ret, nil } // RunCommandStatus attachs a shell and runs the command within the container. // The process will wait for the command to finish and return the result of // waitpid(), i.e. the process' exit status. An error is returned only when // invocation of the command completely fails. func (c *Container) RunCommandStatus(args []string, options AttachOptions) (int, error) { c.mu.Lock() defer c.mu.Unlock() return c.runCommandStatus(args, options) } // RunCommandNoWait runs the given command and returns without waiting it to finish. func (c *Container) RunCommandNoWait(args []string, options AttachOptions) (int, error) { c.mu.Lock() defer c.mu.Unlock() if len(args) == 0 { return -1, ErrInsufficientNumberOfArguments } if err := c.makeSure(isRunning); err != nil { return -1, err } cargs := makeNullTerminatedArgs(args) if cargs == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) var attachedPid C.pid_t ret := int(C.go_lxc_attach_no_wait( c.container, C.bool(options.ClearEnv), C.int(options.Namespaces), C.long(options.Arch), C.uid_t(options.UID), C.gid_t(options.GID), C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, cargs, &attachedPid, )) if ret < 0 { return -1, ErrAttachFailed } return int(attachedPid), nil } // RunCommand attachs a shell and runs the command within the container. // The process will wait for the command to finish and return a success status. An error // is returned only when invocation of the command completely fails. func (c *Container) RunCommand(args []string, options AttachOptions) (bool, error) { c.mu.Lock() defer c.mu.Unlock() ret, err := c.runCommandStatus(args, options) if err != nil { return false, err } if ret < 0 { return false, ErrAttachFailed } return ret == 0, nil } // Interfaces returns the names of the network interfaces. func (c *Container) Interfaces() ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } result := C.go_lxc_get_interfaces(c.container) if result == nil { return nil, ErrInterfaces } return convertArgs(result), nil } // InterfaceStats returns the stats about container's network interfaces func (c *Container) InterfaceStats() (map[string]map[string]ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } var interfaceName string statistics := make(map[string]map[string]ByteSize) netPrefix := "lxc.net" if !VersionAtLeast(2, 1, 0) { netPrefix = "lxc.network" } for i := 0; i < len(c.configItem(netPrefix)); i++ { interfaceType := c.runningConfigItem(fmt.Sprintf("%s.%d.type", netPrefix, i)) if interfaceType == nil { continue } if interfaceType[0] == "veth" { interfaceName = c.runningConfigItem(fmt.Sprintf("%s.%d.veth.pair", netPrefix, i))[0] } else { interfaceName = c.runningConfigItem(fmt.Sprintf("%s.%d.link", netPrefix, i))[0] } for _, v := range []string{"rx", "tx"} { /* tx and rx are reversed from the host vs container */ content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/statistics/%s_bytes", interfaceName, v)) if err != nil { return nil, err } bytes, err := strconv.ParseInt(strings.Split(string(content), "\n")[0], 10, 64) if err != nil { return nil, err } if statistics[interfaceName] == nil { statistics[interfaceName] = make(map[string]ByteSize) } statistics[interfaceName][v] = ByteSize(bytes) } } return statistics, nil } // IPAddress returns the IP address of the given network interface. func (c *Container) IPAddress(interfaceName string) ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } cinterface := C.CString(interfaceName) defer C.free(unsafe.Pointer(cinterface)) result := C.go_lxc_get_ips(c.container, cinterface, nil, 0) if result == nil { return nil, ErrIPAddress } return convertArgs(result), nil } // IPv4Address returns the IPv4 address of the given network interface. func (c *Container) IPv4Address(interfaceName string) ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } cinterface := C.CString(interfaceName) defer C.free(unsafe.Pointer(cinterface)) cfamily := C.CString("inet") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0) if result == nil { return nil, ErrIPv4Addresses } return convertArgs(result), nil } // IPv6Address returns the IPv6 address of the given network interface. func (c *Container) IPv6Address(interfaceName string) ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } cinterface := C.CString(interfaceName) defer C.free(unsafe.Pointer(cinterface)) cfamily := C.CString("inet6") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, cinterface, cfamily, 0) if result == nil { return nil, ErrIPv6Addresses } return convertArgs(result), nil } // WaitIPAddresses waits until IPAddresses call returns something or time outs func (c *Container) WaitIPAddresses(timeout time.Duration) ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() now := time.Now() for { if result, err := c.ipAddresses(); err == nil && len(result) > 0 { return result, nil } // Python API sleeps 1 second as well time.Sleep(1 * time.Second) if time.Since(now) >= timeout { return nil, ErrIPAddresses } } } func (c *Container) ipAddresses() ([]string, error) { if err := c.makeSure(isRunning); err != nil { return nil, err } result := C.go_lxc_get_ips(c.container, nil, nil, 0) if result == nil { return nil, ErrIPAddresses } return convertArgs(result), nil } // IPAddresses returns all IP addresses. func (c *Container) IPAddresses() ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() return c.ipAddresses() } // IPv4Addresses returns all IPv4 addresses. func (c *Container) IPv4Addresses() ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } cfamily := C.CString("inet") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) if result == nil { return nil, ErrIPv4Addresses } return convertArgs(result), nil } // IPv6Addresses returns all IPv6 addresses. func (c *Container) IPv6Addresses() ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } cfamily := C.CString("inet6") defer C.free(unsafe.Pointer(cfamily)) result := C.go_lxc_get_ips(c.container, nil, cfamily, 0) if result == nil { return nil, ErrIPv6Addresses } return convertArgs(result), nil } // LogFile returns the name of the logfile. func (c *Container) LogFile() string { c.mu.RLock() defer c.mu.RUnlock() if VersionAtLeast(2, 1, 0) { return c.configItem("lxc.log.file")[0] } return c.configItem("lxc.logfile")[0] } // SetLogFile sets the name of the logfile. func (c *Container) SetLogFile(filename string) error { c.mu.Lock() defer c.mu.Unlock() var err error if VersionAtLeast(2, 1, 0) { err = c.setConfigItem("lxc.log.file", filename) } else { err = c.setConfigItem("lxc.logfile", filename) } if err != nil { return err } return nil } // LogLevel returns the level of the logfile. func (c *Container) LogLevel() LogLevel { c.mu.RLock() defer c.mu.RUnlock() if VersionAtLeast(2, 1, 0) { return logLevelMap[c.configItem("lxc.log.level")[0]] } return logLevelMap[c.configItem("lxc.loglevel")[0]] } // SetLogLevel sets the level of the logfile. func (c *Container) SetLogLevel(level LogLevel) error { c.mu.Lock() defer c.mu.Unlock() var err error if VersionAtLeast(2, 1, 0) { err = c.setConfigItem("lxc.log.level", level.String()) } else { err = c.setConfigItem("lxc.loglevel", level.String()) } if err != nil { return err } return nil } // AddDeviceNode adds specified device to the container. func (c *Container) AddDeviceNode(source string, destination ...string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning | isPrivileged); err != nil { return err } csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) if destination != nil && len(destination) == 1 { cdestination := C.CString(destination[0]) defer C.free(unsafe.Pointer(cdestination)) if !bool(C.go_lxc_add_device_node(c.container, csource, cdestination)) { return ErrAddDeviceNodeFailed } return nil } if !bool(C.go_lxc_add_device_node(c.container, csource, nil)) { return ErrAddDeviceNodeFailed } return nil } // RemoveDeviceNode removes the specified device from the container. func (c *Container) RemoveDeviceNode(source string, destination ...string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning | isPrivileged); err != nil { return err } csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) if destination != nil && len(destination) == 1 { cdestination := C.CString(destination[0]) defer C.free(unsafe.Pointer(cdestination)) if !bool(C.go_lxc_remove_device_node(c.container, csource, cdestination)) { return ErrRemoveDeviceNodeFailed } return nil } if !bool(C.go_lxc_remove_device_node(c.container, csource, nil)) { return ErrRemoveDeviceNodeFailed } return nil } // Checkpoint checkpoints the container. func (c *Container) Checkpoint(opts CheckpointOptions) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning | isGreaterEqualThanLXC11); err != nil { return err } cdirectory := C.CString(opts.Directory) defer C.free(unsafe.Pointer(cdirectory)) cstop := C.bool(opts.Stop) cverbose := C.bool(opts.Verbose) if !C.go_lxc_checkpoint(c.container, cdirectory, cstop, cverbose) { return ErrCheckpointFailed } return nil } // Restore restores the container from a checkpoint. func (c *Container) Restore(opts RestoreOptions) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isGreaterEqualThanLXC11); err != nil { return err } cdirectory := C.CString(opts.Directory) defer C.free(unsafe.Pointer(cdirectory)) cverbose := C.bool(opts.Verbose) if !C.bool(C.go_lxc_restore(c.container, cdirectory, cverbose)) { return ErrRestoreFailed } return nil } // Migrate migrates the container. func (c *Container) Migrate(cmd uint, opts MigrateOptions) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isNotDefined | isGreaterEqualThanLXC20); err != nil { return err } if cmd != MIGRATE_RESTORE { if err := c.makeSure(isRunning); err != nil { return err } } cdirectory := C.CString(opts.Directory) defer C.free(unsafe.Pointer(cdirectory)) var cpredumpdir *C.char if opts.PredumpDir != "" { cpredumpdir = C.CString(opts.PredumpDir) defer C.free(unsafe.Pointer(cpredumpdir)) } /* Since we can't do conditional compilation here, we allocate the * "extras" struct and then merge them in the C code. */ copts := C.struct_migrate_opts{ directory: cdirectory, verbose: C.bool(opts.Verbose), stop: C.bool(opts.Stop), predump_dir: cpredumpdir, } var cActionScript *C.char if opts.ActionScript != "" { cActionScript = C.CString(opts.ActionScript) defer C.free(unsafe.Pointer(cActionScript)) } extras := C.struct_extra_migrate_opts{ preserves_inodes: C.bool(opts.PreservesInodes), action_script: cActionScript, ghost_limit: C.uint64_t(opts.GhostLimit), features_to_check: C.uint64_t(opts.FeaturesToCheck), } ret := C.int(C.go_lxc_migrate(c.container, C.uint(cmd), &copts, &extras)) if ret != 0 { return fmt.Errorf("migration failed %d", ret) } return nil } // AttachInterface attaches specifed netdev to the container. func (c *Container) AttachInterface(source, destination string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { return err } csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) cdestination := C.CString(destination) defer C.free(unsafe.Pointer(cdestination)) if !bool(C.go_lxc_attach_interface(c.container, csource, cdestination)) { return ErrAttachInterfaceFailed } return nil } // DetachInterface detaches specifed netdev from the container. func (c *Container) DetachInterface(source string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { return err } csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) if !bool(C.go_lxc_detach_interface(c.container, csource, nil)) { return ErrDetachInterfaceFailed } return nil } // DetachInterfaceRename detaches specifed netdev from the container and renames it. func (c *Container) DetachInterfaceRename(source, target string) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning | isPrivileged | isGreaterEqualThanLXC11); err != nil { return err } csource := C.CString(source) defer C.free(unsafe.Pointer(csource)) ctarget := C.CString(target) defer C.free(unsafe.Pointer(ctarget)) if !bool(C.go_lxc_detach_interface(c.container, csource, ctarget)) { return ErrDetachInterfaceFailed } return nil } // ConsoleLog allows to perform operations on the container's in-memory console // buffer. func (c *Container) ConsoleLog(opt ConsoleLogOptions) ([]byte, error) { c.mu.Lock() defer c.mu.Unlock() cl := C.struct_lxc_console_log{ clear: C.bool(opt.ClearLog), read: C.bool(opt.ReadLog), data: nil, write_logfile: C.bool(opt.WriteToLogFile), } // CGO is a fickle little beast: // We need to manually allocate memory here that we pass to C. If we // were to pass a GO pointer by passing a C.uint64_t pointer we'd end in // the situation where we have a GO pointer that points to a GO pointer. // Go will freak out when this happens. So give C its own memory. var buf unsafe.Pointer buf = C.malloc(C.sizeof_uint64_t) if buf == nil { return nil, syscall.ENOMEM } defer C.free(buf) cl.read_max = (*C.uint64_t)(buf) *cl.read_max = C.uint64_t(opt.ReadMax) ret := C.go_lxc_console_log(c.container, &cl) if ret < 0 { return nil, syscall.Errno(-ret) } numBytes := C.int(*cl.read_max) if C.uint64_t(numBytes) != *cl.read_max { return nil, syscall.ERANGE } return C.GoBytes(unsafe.Pointer(cl.data), numBytes), nil } // ErrorNum returns the error_num field of the container. func (c *Container) ErrorNum() int { cError := C.go_lxc_error_num(c.container) return int(cError) } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/doc.go000066400000000000000000000005261323041231200221730ustar00rootroot00000000000000/* Package lxc provides Go Bindings for LXC (Linux Containers) C API. LXC (LinuX Containers) is an operating system–level virtualization method for running multiple isolated Linux systems (containers) on a single control host. LXC combines cgroups and namespace support to provide an isolated environment for applications. */ package lxc golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/error.go000066400000000000000000000132201323041231200225520ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc var ( ErrAddDeviceNodeFailed = NewError("adding device to container failed") ErrAllocationFailed = NewError("allocating memory failed") ErrAlreadyDefined = NewError("container already defined") ErrAlreadyFrozen = NewError("container is already frozen") ErrAlreadyRunning = NewError("container is already running") ErrAttachFailed = NewError("attaching to the container failed") ErrAttachInterfaceFailed = NewError("attaching specified netdev to the container failed") ErrBlkioUsage = NewError("BlkioUsage for the container failed") ErrCheckpointFailed = NewError("checkpoint failed") ErrClearingConfigItemFailed = NewError("clearing config item for the container failed") ErrClearingCgroupItemFailed = NewError("clearing cgroup item for the container failed") ErrCloneFailed = NewError("cloning the container failed") ErrCloseAllFdsFailed = NewError("setting close_all_fds flag for container failed") ErrCreateFailed = NewError("creating the container failed") ErrCreateSnapshotFailed = NewError("snapshotting the container failed") ErrDaemonizeFailed = NewError("setting daemonize flag for container failed") ErrDestroyAllSnapshotsFailed = NewError("destroying all snapshots failed") ErrDestroyFailed = NewError("destroying the container failed") ErrDestroySnapshotFailed = NewError("destroying the snapshot failed") ErrDestroyWithAllSnapshotsFailed = NewError("destroying the container with all snapshots failed") ErrDetachInterfaceFailed = NewError("detaching specified netdev to the container failed") ErrExecuteFailed = NewError("executing the command in a temporary container failed") ErrFreezeFailed = NewError("freezing the container failed") ErrInsufficientNumberOfArguments = NewError("insufficient number of arguments were supplied") ErrInterfaces = NewError("getting interface names for the container failed") ErrIPAddresses = NewError("getting IP addresses of the container failed") ErrIPAddress = NewError("getting IP address on the interface of the container failed") ErrIPv4Addresses = NewError("getting IPv4 addresses of the container failed") ErrIPv6Addresses = NewError("getting IPv6 addresses of the container failed") ErrKMemLimit = NewError("your kernel does not support cgroup kernel memory controller") ErrLoadConfigFailed = NewError("loading config file for the container failed") ErrMemLimit = NewError("your kernel does not support cgroup memory controller") ErrMemorySwapLimit = NewError("your kernel does not support cgroup swap controller") ErrMethodNotAllowed = NewError("the requested method is not currently supported with unprivileged containers") ErrNewFailed = NewError("allocating the container failed") ErrNoSnapshot = NewError("container has no snapshot") ErrNotDefined = NewError("container is not defined") ErrNotFrozen = NewError("container is not frozen") ErrNotRunning = NewError("container is not running") ErrNotSupported = NewError("method is not supported by this LXC version") ErrRebootFailed = NewError("rebooting the container failed") ErrRemoveDeviceNodeFailed = NewError("removing device from container failed") ErrRenameFailed = NewError("renaming the container failed") ErrRestoreFailed = NewError("restore failed") ErrRestoreSnapshotFailed = NewError("restoring the container failed") ErrSaveConfigFailed = NewError("saving config file for the container failed") ErrSettingCgroupItemFailed = NewError("setting cgroup item for the container failed") ErrSettingConfigItemFailed = NewError("setting config item for the container failed") ErrSettingConfigPathFailed = NewError("setting config file for the container failed") ErrSettingKMemoryLimitFailed = NewError("setting kernel memory limit for the container failed") ErrSettingMemoryLimitFailed = NewError("setting memory limit for the container failed") ErrSettingMemorySwapLimitFailed = NewError("setting memory+swap limit for the container failed") ErrSettingSoftMemoryLimitFailed = NewError("setting soft memory limit for the container failed") ErrShutdownFailed = NewError("shutting down the container failed") ErrSoftMemLimit = NewError("your kernel does not support cgroup memory controller") ErrStartFailed = NewError("starting the container failed") ErrStopFailed = NewError("stopping the container failed") ErrTemplateNotAllowed = NewError("unprivileged users only allowed to use \"download\" template") ErrUnfreezeFailed = NewError("unfreezing the container failed") ErrUnknownBackendStore = NewError("unknown backend type") ) // Error represents a basic error that implies the error interface. type Error struct { Message string } // NewError creates a new error with the given msg argument. func NewError(msg string) error { return &Error{ Message: msg, } } func (e *Error) Error() string { return e.Message } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/000077500000000000000000000000001323041231200227125ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/Makefile000066400000000000000000000012431323041231200243520ustar00rootroot00000000000000NO_COLOR=\033[0m OK_COLOR=\033[0;32m ALL_GO_FILES = $(wildcard *.go) ALL_FILES = $(patsubst %.go,%,$(ALL_GO_FILES)) all: $(ALL_FILES) define PROGRAM_template $(1): format vet lint @echo "$(OK_COLOR)==> Building $(1) $(NO_COLOR)" @go build $(1).go endef $(foreach prog,$(ALL_FILES),$(eval $(call PROGRAM_template,$(prog)))) clean: @$(foreach file,$(ALL_FILES),rm -f $(file);) format: @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" @gofmt -s -w *.go @goimports -w *.go vet: @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" @`which go` vet . lint: @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" @`which golint` . .PHONY: all clean format vet lint golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/attach.go000066400000000000000000000024661323041231200245150ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string clear bool x86 bool regular bool ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.BoolVar(&clear, "clear", false, "Attach with clear environment") flag.BoolVar(&x86, "x86", false, "Attach using x86 personality") flag.BoolVar(®ular, "regular", false, "Attach using a regular user") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } options := lxc.DefaultAttachOptions options.ClearEnv = false if clear { options.ClearEnv = true } if x86 { options.Arch = lxc.X86 } if regular { options.UID = 1000 options.GID = 1000 } log.Printf("AttachShell\n") err = c.AttachShell(options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("RunCommand\n") _, err = c.RunCommand([]string{"id"}, options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/attach_with_pipes.go000066400000000000000000000042511323041231200267420ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "io" "log" "os" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string clear bool x86 bool regular bool wg sync.WaitGroup ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.BoolVar(&clear, "clear", false, "Attach with clear environment") flag.BoolVar(&x86, "x86", false, "Attach using x86 personality") flag.BoolVar(®ular, "regular", false, "Attach using a regular user") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } stdoutReader, stdoutWriter, err := os.Pipe() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } stderrReader, stderrWriter, err := os.Pipe() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Add(1) go func() { defer wg.Done() _, err = io.Copy(os.Stdout, stdoutReader) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } }() wg.Add(1) go func() { defer wg.Done() _, err = io.Copy(os.Stderr, stderrReader) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } }() options := lxc.DefaultAttachOptions options.StdinFd = os.Stdin.Fd() options.StdoutFd = stdoutWriter.Fd() options.StderrFd = stderrWriter.Fd() options.ClearEnv = false if clear { options.ClearEnv = true } if x86 { options.Arch = lxc.X86 } if regular { options.UID = 1000 options.GID = 1000 } log.Printf("AttachShell\n") if err := c.AttachShell(options); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("RunCommand\n") _, err = c.RunCommand([]string{"uname", "-a"}, options) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err = stdoutWriter.Close(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err = stderrWriter.Close(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Wait() } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/checkpoint.go000066400000000000000000000021701323041231200253700ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string directory string name string stop bool verbose bool ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.StringVar(&directory, "directory", "/tmp/rubik", "directory to save the checkpoint in") flag.BoolVar(&verbose, "verbose", false, "Verbose output") flag.BoolVar(&stop, "stop", false, "Stop the container after checkpointing.") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if verbose { c.SetVerbosity(lxc.Verbose) } options := lxc.CheckpointOptions{ Directory: directory, Verbose: verbose, Stop: stop, } if err := c.Checkpoint(options); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/clone.go000066400000000000000000000020601323041231200243370ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string backend lxc.BackendStore ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.Var(&backend, "backend", "Backend type to use, possible values are [dir, zfs, btrfs, lvm, aufs, overlayfs, loopback, best]") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if backend == 0 { log.Fatalf("ERROR: %s\n", lxc.ErrUnknownBackendStore) } log.Printf("Cloning the container using %s backend...\n", backend) err = c.Clone(name+"_"+backend.String(), lxc.CloneOptions{ Backend: backend, }) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/concurrent_create.go000066400000000000000000000017431323041231200267530ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup options := lxc.BusyboxTemplateOptions for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Creating the container (%d)...\n", i) if err := c.Create(options); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/concurrent_destroy.go000066400000000000000000000016701323041231200272000ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Destroying the container (%d)...\n", i) if err := c.Destroy(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/concurrent_shutdown.go000066400000000000000000000017771323041231200273720ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Shutting down the container (%d)...\n", i) if err := c.Shutdown(30 * time.Second); err != nil { if err = c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } wg.Done() }(i) } wg.Wait() } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/concurrent_start.go000066400000000000000000000016641323041231200266470ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Starting the container (%d)...\n", i) if err := c.Start(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/concurrent_stop.go000066400000000000000000000016621323041231200264750ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string count int ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.IntVar(&count, "count", 10, "Number of containers") flag.Parse() } func main() { var wg sync.WaitGroup for i := 0; i < count; i++ { wg.Add(1) go func(i int) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Stoping the container (%d)...\n", i) if err := c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } wg.Done() }(i) } wg.Wait() } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/concurrent_stress.go000066400000000000000000000051031323041231200270250ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "io/ioutil" "log" "runtime" "strconv" "sync" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string iteration int threads int template string quiet bool startstop bool createdestroy bool ) func init() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&template, "template", "busybox", "Template to use") flag.IntVar(&threads, "threads", 10, "Number of operations to run concurrently") flag.IntVar(&iteration, "iteration", 1, "Number times to run the test") flag.BoolVar(&quiet, "quiet", false, "Don't produce any output") flag.BoolVar(&startstop, "startstop", false, "Flag to execute Start and Stop") flag.BoolVar(&createdestroy, "createdestroy", false, "Flag to execute Create and Destroy") flag.Parse() } func main() { if quiet { log.SetOutput(ioutil.Discard) } log.Printf("Using %d GOMAXPROCS\n", runtime.NumCPU()) var wg sync.WaitGroup options := lxc.BusyboxTemplateOptions options.Template = template for i := 0; i < iteration; i++ { log.Printf("-- ITERATION %d --\n", i+1) for _, mode := range []string{"CREATE", "START", "STOP", "DESTROY"} { log.Printf("\t-- %s --\n", mode) for j := 0; j < threads; j++ { wg.Add(1) go func(i int, mode string) { c, err := lxc.NewContainer(strconv.Itoa(i), lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if mode == "CREATE" && startstop == false { log.Printf("\t\tCreating the container (%d)...\n", i) if err := c.Create(options); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } else if mode == "START" && createdestroy == false { log.Printf("\t\tStarting the container (%d)...\n", i) if err := c.Start(); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } else if mode == "STOP" && createdestroy == false { log.Printf("\t\tStoping the container (%d)...\n", i) if err := c.Stop(); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } else if mode == "DESTROY" && startstop == false { log.Printf("\t\tDestroying the container (%d)...\n", i) if err := c.Destroy(); err != nil { log.Fatalf("\t\t\tERROR: %s\n", err.Error()) } } wg.Done() }(j, mode) } wg.Wait() } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/config.go000066400000000000000000000016731323041231200245150ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string hostname string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.StringVar(&hostname, "hostname", "rubik-host1", "Hostname of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } //setting hostname err = c.SetConfigItem("lxc.utsname", hostname) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } // fetching rootfs location rootfs := c.ConfigItem("lxc.rootfs")[0] log.Printf("Root FS: %s\n", rootfs) } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/console.go000066400000000000000000000014051323041231200247030ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Attaching to container's console...\n") if err := c.Console(lxc.DefaultConsoleOptions); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/create.go000066400000000000000000000030741323041231200245100ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string template string distro string release string arch string name string verbose bool flush bool validation bool ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&template, "template", "download", "Template to use") flag.StringVar(&distro, "distro", "ubuntu", "Template to use") flag.StringVar(&release, "release", "trusty", "Template to use") flag.StringVar(&arch, "arch", "amd64", "Template to use") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.BoolVar(&verbose, "verbose", false, "Verbose output") flag.BoolVar(&flush, "flush", false, "Flush the cache") flag.BoolVar(&validation, "validation", false, "GPG validation") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Creating container...\n") if verbose { c.SetVerbosity(lxc.Verbose) } options := lxc.TemplateOptions{ Template: template, Distro: distro, Release: release, Arch: arch, FlushCache: flush, DisableGPGValidation: validation, } if err := c.Create(options); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/create_snapshot.go000066400000000000000000000013571323041231200264310ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Snapshoting the container...\n") if _, err := c.CreateSnapshot(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/destroy.go000066400000000000000000000013401323041231200247300ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Destroying container...\n") if err := c.Destroy(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/destroy_snapshots.go000066400000000000000000000011551323041231200270360ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "log" "gopkg.in/lxc/go-lxc.v2" ) func main() { c := lxc.Containers() for i := range c { log.Printf("%s\n", c[i].Name()) l, err := c[i].Snapshots() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } for _, s := range l { log.Printf("Destroying Snaphot: %s\n", s.Name) if err := c[i].DestroySnapshot(s); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/device_add_remove.go000066400000000000000000000015631323041231200266720ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err := c.AddDeviceNode("/dev/network_latency"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } time.Sleep(10000 * time.Millisecond) if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/execute.go000066400000000000000000000014341323041231200247050ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.LoadConfigFile(lxc.DefaultConfigPath()) if output, err := c.Execute("uname", "-a"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("%s", output) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/freeze.go000066400000000000000000000014151323041231200245220ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Freezing the container...\n") if err := c.Freeze(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.Wait(lxc.FROZEN, 10*time.Second) } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/interfaces.go000066400000000000000000000014721323041231200253700ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Interfaces\n") if interfaces, err := c.Interfaces(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range interfaces { log.Printf("%d) %s\n", i, v) } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/ipaddress.go000066400000000000000000000026641323041231200252270ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the original container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("IPAddress(\"lo\")\n") if addresses, err := c.IPAddress("lo"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } log.Printf("IPAddresses()\n") if addresses, err := c.IPAddresses(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } log.Printf("IPv4Addresses()\n") if addresses, err := c.IPv4Addresses(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } log.Printf("IPv6Addresses()\n") if addresses, err := c.IPv6Addresses(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { for i, v := range addresses { log.Printf("%d) %s\n", i, v) } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/limit.go000066400000000000000000000020031323041231200243520ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } memLimit, err := c.MemoryLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } memorySwapLimit, err := c.MemorySwapLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err := c.SetMemoryLimit(memLimit / 4); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } if err := c.SetMemorySwapLimit(memorySwapLimit / 4); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/list.go000066400000000000000000000016261323041231200242210ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.Parse() } func main() { log.Printf("Defined containers:\n") c := lxc.DefinedContainers(lxcpath) for i := range c { log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) } log.Println() log.Printf("Active containers:\n") c = lxc.ActiveContainers(lxcpath) for i := range c { log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) } log.Println() log.Printf("Active and Defined containers:\n") c = lxc.ActiveContainers(lxcpath) for i := range c { log.Printf("%s (%s)\n", c[i].Name(), c[i].State()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/list_keys.go000066400000000000000000000012721323041231200252510ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } for _, k := range c.ConfigKeys() { log.Printf("%s -> %s", k, c.ConfigItem(k)) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/list_snapshots.go000066400000000000000000000012261323041231200263170ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "log" "gopkg.in/lxc/go-lxc.v2" ) func main() { c := lxc.Containers() for i := range c { log.Printf("%s\n", c[i].Name()) l, err := c[i].Snapshots() if err != nil { log.Printf("ERROR: %s\n", err.Error()) } for _, s := range l { log.Printf("Name: %s\n", s.Name) log.Printf("Comment path: %s\n", s.CommentPath) log.Printf("Timestamp: %s\n", s.Timestamp) log.Printf("LXC path: %s\n", s.Path) log.Println() } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/reboot.go000066400000000000000000000013421323041231200245330ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Rebooting the container...\n") if err := c.Reboot(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/rename.go000066400000000000000000000015161323041231200245130ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string newname string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&newname, "newname", "kibur", "New name of the container") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Renaming container to %s...\n", newname) if err := c.Rename(newname); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/restore_snapshot.go000066400000000000000000000014561323041231200266510ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Restoring the container...\n") snapshot := lxc.Snapshot{Name: "snap0"} if err := c.RestoreSnapshot(snapshot, "rubik-restore"); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/shutdown.go000066400000000000000000000014471323041231200251220ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Shutting down the container...\n") if err := c.Shutdown(30 * time.Second); err != nil { if err = c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/start.go000066400000000000000000000017221323041231200244000ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.SetLogFile("/tmp/" + name + ".log") c.SetLogLevel(lxc.TRACE) log.Printf("Starting the container...\n") if err := c.Start(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Waiting container to startup networking...\n") if _, err := c.WaitIPAddresses(5 * time.Second); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/stats.go000066400000000000000000000044361323041231200244060ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } // mem memUsed, err := c.MemoryUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemoryUsage: %s\n", memUsed) } memLimit, err := c.MemoryLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemoryLimit: %s\n", memLimit) } // kmem kmemUsed, err := c.KernelMemoryUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("KernelMemoryUsage: %s\n", kmemUsed) } kmemLimit, err := c.KernelMemoryLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("KernelMemoryLimit: %s\n", kmemLimit) } // swap swapUsed, err := c.MemorySwapUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemorySwapUsage: %s\n", swapUsed) } swapLimit, err := c.MemorySwapLimit() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("MemorySwapLimit: %s\n", swapLimit) } // blkio blkioUsage, err := c.BlkioUsage() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } else { log.Printf("BlkioUsage: %s\n", blkioUsage) } cpuTime, err := c.CPUTime() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("cpuacct.usage: %s\n", cpuTime) cpuTimePerCPU, err := c.CPUTimePerCPU() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("cpuacct.usageerrpercpu: %v\n", cpuTimePerCPU) cpuStats, err := c.CPUStats() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("cpuacct.stat: %v\n", cpuStats) interfaceStats, err := c.InterfaceStats() if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("InterfaceStats: %v\n", interfaceStats) } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/stop.go000066400000000000000000000014411323041231200242260ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.SetLogFile("/tmp/" + name + ".log") c.SetLogLevel(lxc.TRACE) log.Printf("Stopping the container...\n") if err := c.Stop(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/examples/unfreeze.go000066400000000000000000000014221323041231200250630ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package main import ( "flag" "log" "time" "gopkg.in/lxc/go-lxc.v2" ) var ( lxcpath string name string ) func init() { flag.StringVar(&lxcpath, "lxcpath", lxc.DefaultConfigPath(), "Use specified container path") flag.StringVar(&name, "name", "rubik", "Name of the container") flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } log.Printf("Unfreezing the container...\n") if err := c.Unfreeze(); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } c.Wait(lxc.RUNNING, 10*time.Second) } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/lxc-binding.c000066400000000000000000000272211323041231200234420ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo #include #include #include #include #include #include #include #include "lxc-binding.h" #ifndef LXC_DEVEL #define LXC_DEVEL 0 #endif bool go_lxc_defined(struct lxc_container *c) { return c->is_defined(c); } const char* go_lxc_state(struct lxc_container *c) { return c->state(c); } bool go_lxc_running(struct lxc_container *c) { return c->is_running(c); } bool go_lxc_freeze(struct lxc_container *c) { return c->freeze(c); } bool go_lxc_unfreeze(struct lxc_container *c) { return c->unfreeze(c); } pid_t go_lxc_init_pid(struct lxc_container *c) { return c->init_pid(c); } bool go_lxc_want_daemonize(struct lxc_container *c, bool state) { return c->want_daemonize(c, state); } bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state) { return c->want_close_all_fds(c, state); } bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]) { return c->create(c, t, bdevtype, NULL, !!(flags & LXC_CREATE_QUIET), argv); } bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]) { return c->start(c, useinit, argv); } bool go_lxc_stop(struct lxc_container *c) { return c->stop(c); } bool go_lxc_reboot(struct lxc_container *c) { return c->reboot(c); } bool go_lxc_shutdown(struct lxc_container *c, int timeout) { return c->shutdown(c, timeout); } char* go_lxc_config_file_name(struct lxc_container *c) { return c->config_file_name(c); } bool go_lxc_destroy(struct lxc_container *c) { return c->destroy(c); } bool go_lxc_destroy_with_snapshots(struct lxc_container *c) { #if VERSION_AT_LEAST(1, 1, 0) return c->destroy_with_snapshots(c); #else return false; #endif } bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout) { return c->wait(c, state, timeout); } char* go_lxc_get_config_item(struct lxc_container *c, const char *key) { int len = c->get_config_item(c, key, NULL, 0); if (len <= 0) { return NULL; } char* value = (char*)malloc(sizeof(char)*len + 1); if (c->get_config_item(c, key, value, len + 1) != len) { return NULL; } return value; } bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value) { return c->set_config_item(c, key, value); } void go_lxc_clear_config(struct lxc_container *c) { c->clear_config(c); } bool go_lxc_clear_config_item(struct lxc_container *c, const char *key) { return c->clear_config_item(c, key); } char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key) { return c->get_running_config_item(c, key); } char* go_lxc_get_keys(struct lxc_container *c, const char *key) { int len = c->get_keys(c, key, NULL, 0); if (len <= 0) { return NULL; } char* value = (char*)malloc(sizeof(char)*len + 1); if (c->get_keys(c, key, value, len + 1) != len) { return NULL; } return value; } char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key) { int len = c->get_cgroup_item(c, key, NULL, 0); if (len <= 0) { return NULL; } char* value = (char*)malloc(sizeof(char)*len + 1); if (c->get_cgroup_item(c, key, value, len + 1) != len) { return NULL; } return value; } bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value) { return c->set_cgroup_item(c, key, value); } const char* go_lxc_get_config_path(struct lxc_container *c) { return c->get_config_path(c); } bool go_lxc_set_config_path(struct lxc_container *c, const char *path) { return c->set_config_path(c, path); } bool go_lxc_load_config(struct lxc_container *c, const char *alt_file) { return c->load_config(c, alt_file); } bool go_lxc_save_config(struct lxc_container *c, const char *alt_file) { return c->save_config(c, alt_file); } bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype) { return c->clone(c, newname, lxcpath, flags, bdevtype, NULL, 0, NULL) != NULL; } int go_lxc_console_getfd(struct lxc_container *c, int ttynum) { int masterfd; if (c->console_getfd(c, &ttynum, &masterfd) < 0) { return -1; } return masterfd; } bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape) { if (c->console(c, ttynum, stdinfd, stdoutfd, stderrfd, escape) == 0) { return true; } return false; } char** go_lxc_get_interfaces(struct lxc_container *c) { return c->get_interfaces(c); } char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope) { return c->get_ips(c, interface, family, scope); } int wait_for_pid_status(pid_t pid) { int status, ret; again: ret = waitpid(pid, &status, 0); if (ret == -1) { if (errno == EINTR) goto again; return -1; } if (ret != pid) goto again; return status; } int go_lxc_attach_no_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[], pid_t *attached_pid) { int ret; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; lxc_attach_command_t command = (lxc_attach_command_t){.program = NULL}; attach_options.env_policy = LXC_ATTACH_KEEP_ENV; if (clear_env) { attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; } attach_options.namespaces = namespaces; attach_options.personality = personality; attach_options.uid = uid; attach_options.gid = gid; attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; command.program = (char *)argv[0]; command.argv = (char **)argv; ret = c->attach(c, lxc_attach_run_command, &command, &attach_options, attached_pid); if (ret < 0) return -1; return 0; } int go_lxc_attach(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env) { int ret; pid_t pid; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.env_policy = LXC_ATTACH_KEEP_ENV; if (clear_env) { attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; } attach_options.namespaces = namespaces; attach_options.personality = personality; attach_options.uid = uid; attach_options.gid = gid; attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; /* remount_sys_proc When using -s and the mount namespace is not included, this flag will cause lxc-attach to remount /proc and /sys to reflect the current other namespace contexts. default_options.attach_flags |= LXC_ATTACH_REMOUNT_PROC_SYS; elevated_privileges Do not drop privileges when running command inside the container. If this option is specified, the new process will not be added to the container's cgroup(s) and it will not drop its capabilities before executing. default_options.attach_flags &= ~(LXC_ATTACH_MOVE_TO_CGROUP | LXC_ATTACH_DROP_CAPABILITIES | LXC_ATTACH_APPARMOR); */ ret = c->attach(c, lxc_attach_run_shell, NULL, &attach_options, &pid); if (ret < 0) return -1; ret = wait_for_pid_status(pid); if (ret < 0) return -1; if (WIFEXITED(ret)) return WEXITSTATUS(ret); return -1; } int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[]) { int ret; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.env_policy = LXC_ATTACH_KEEP_ENV; if (clear_env) { attach_options.env_policy = LXC_ATTACH_CLEAR_ENV; } attach_options.namespaces = namespaces; attach_options.personality = personality; attach_options.uid = uid; attach_options.gid = gid; attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; ret = c->attach_run_wait(c, &attach_options, argv[0], argv); if (WIFEXITED(ret) && WEXITSTATUS(ret) == 255) return -1; return ret; } bool go_lxc_may_control(struct lxc_container *c) { return c->may_control(c); } int go_lxc_snapshot(struct lxc_container *c) { return c->snapshot(c, NULL); } int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret) { return c->snapshot_list(c, ret); } bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname) { return c->snapshot_restore(c, snapname, newname); } bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname) { return c->snapshot_destroy(c, snapname); } bool go_lxc_snapshot_destroy_all(struct lxc_container *c) { #if VERSION_AT_LEAST(1, 1, 0) return c->snapshot_destroy_all(c); #else return false; #endif } bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { return c->add_device_node(c, src_path, dest_path); } bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { return c->remove_device_node(c, src_path, dest_path); } bool go_lxc_rename(struct lxc_container *c, const char *newname) { return c->rename(c, newname); } bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose) { #if VERSION_AT_LEAST(1, 1, 0) return c->checkpoint(c, directory, stop, verbose); #else return false; #endif } bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose) { #if VERSION_AT_LEAST(1, 1, 0) return c->restore(c, directory, verbose); #else return false; #endif } int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras) { #if VERSION_AT_LEAST(3, 0, 0) opts->features_to_check = extras->features_to_check; #endif #if VERSION_AT_LEAST(2, 0, 4) opts->action_script = extras->action_script; opts->ghost_limit = extras->ghost_limit; #endif #if VERSION_AT_LEAST(2, 0, 1) opts->preserves_inodes = extras->preserves_inodes; #endif #if VERSION_AT_LEAST(2, 0, 0) return c->migrate(c, cmd, opts, sizeof(*opts)); #else return -EINVAL; #endif } bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { #if VERSION_AT_LEAST(1, 1, 0) return c->attach_interface(c, dev, dst_dev); #else return false; #endif } bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { #if VERSION_AT_LEAST(1, 1, 0) return c->detach_interface(c, dev, dst_dev); #else return false; #endif } bool go_lxc_config_item_is_supported(const char *key) { #if VERSION_AT_LEAST(2, 1, 0) return lxc_config_item_is_supported(key); #else return false; #endif } int go_lxc_error_num(struct lxc_container *c) { return c->error_num; } int go_lxc_console_log(struct lxc_container *c, struct lxc_console_log *log) { #if VERSION_AT_LEAST(3, 0, 0) return c->console_log(c, log); #else return false; #endif } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/lxc-binding.go000066400000000000000000000136751323041231200236350ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc // #cgo pkg-config: lxc // #cgo LDFLAGS: -llxc -lutil // #include // #include // #include "lxc-binding.h" // #ifndef LXC_DEVEL // #define LXC_DEVEL 0 // #endif import "C" import ( "fmt" "runtime" "strings" "unsafe" ) // NewContainer returns a new container struct. func NewContainer(name string, lxcpath ...string) (*Container, error) { var container *C.struct_lxc_container cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) container = C.lxc_container_new(cname, clxcpath) } else { container = C.lxc_container_new(cname, nil) } if container == nil { return nil, ErrNewFailed } c := &Container{container: container, verbosity: Quiet} // http://golang.org/pkg/runtime/#SetFinalizer runtime.SetFinalizer(c, Release) return c, nil } // Acquire increments the reference counter of the container object. func Acquire(c *Container) bool { return C.lxc_container_get(c.container) == 1 } // Release decrements the reference counter of the container object. func Release(c *Container) bool { // http://golang.org/pkg/runtime/#SetFinalizer runtime.SetFinalizer(c, nil) return C.lxc_container_put(c.container) == 1 } // Version returns the LXC version. func Version() string { version := C.GoString(C.lxc_get_version()) // New liblxc versions append "-devel" when LXC_DEVEL is set. if strings.HasSuffix(version, "-devel") { return fmt.Sprintf("%s (devel)", version[:(len(version)-len("-devel"))]) } return version } // GlobalConfigItem returns the value of the given global config key. func GlobalConfigItem(name string) string { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) return C.GoString(C.lxc_get_global_config_item(cname)) } // DefaultConfigPath returns default config path. func DefaultConfigPath() string { return GlobalConfigItem("lxc.lxcpath") } // DefaultLvmVg returns the name of the default LVM volume group. func DefaultLvmVg() string { return GlobalConfigItem("lxc.bdev.lvm.vg") } // DefaultZfsRoot returns the name of the default ZFS root. func DefaultZfsRoot() string { return GlobalConfigItem("lxc.bdev.zfs.root") } // ContainerNames returns the names of defined and active containers on the system. func ContainerNames(lxcpath ...string) []string { var size int var cnames **C.char if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) size = int(C.list_all_containers(clxcpath, &cnames, nil)) } else { size = int(C.list_all_containers(nil, &cnames, nil)) } if size < 1 { return nil } return convertNArgs(cnames, size) } // Containers returns the defined and active containers on the system. Only // containers that could retrieved successfully are returned. func Containers(lxcpath ...string) []*Container { var containers []*Container for _, v := range ContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // DefinedContainerNames returns the names of the defined containers on the system. func DefinedContainerNames(lxcpath ...string) []string { var size int var cnames **C.char if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) size = int(C.list_defined_containers(clxcpath, &cnames, nil)) } else { size = int(C.list_defined_containers(nil, &cnames, nil)) } if size < 1 { return nil } return convertNArgs(cnames, size) } // DefinedContainers returns the defined containers on the system. Only // containers that could retrieved successfully are returned. func DefinedContainers(lxcpath ...string) []*Container { var containers []*Container for _, v := range DefinedContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // ActiveContainerNames returns the names of the active containers on the system. func ActiveContainerNames(lxcpath ...string) []string { var size int var cnames **C.char if lxcpath != nil && len(lxcpath) == 1 { clxcpath := C.CString(lxcpath[0]) defer C.free(unsafe.Pointer(clxcpath)) size = int(C.list_active_containers(clxcpath, &cnames, nil)) } else { size = int(C.list_active_containers(nil, &cnames, nil)) } if size < 1 { return nil } return convertNArgs(cnames, size) } // ActiveContainers returns the active containers on the system. Only // containers that could retrieved successfully are returned. func ActiveContainers(lxcpath ...string) []*Container { var containers []*Container for _, v := range ActiveContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // VersionNumber returns the LXC version. func VersionNumber() (major int, minor int) { major = C.LXC_VERSION_MAJOR minor = C.LXC_VERSION_MINOR return } // VersionAtLeast returns true when the tested version >= current version. func VersionAtLeast(major int, minor int, micro int) bool { if C.LXC_DEVEL == 1 { return true } if major > C.LXC_VERSION_MAJOR { return false } if major == C.LXC_VERSION_MAJOR && minor > C.LXC_VERSION_MINOR { return false } if major == C.LXC_VERSION_MAJOR && minor == C.LXC_VERSION_MINOR && micro > C.LXC_VERSION_MICRO { return false } return true } // IsSupportedConfigItem returns true if the key belongs to a supported config item. func IsSupportedConfigItem(key string) bool { configItem := C.CString(key) defer C.free(unsafe.Pointer(configItem)) return bool(C.go_lxc_config_item_is_supported(configItem)) } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/lxc-binding.h000066400000000000000000000140241323041231200234440ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. #define VERSION_AT_LEAST(major, minor, micro) \ ((LXC_DEVEL == 1) || (!(major > LXC_VERSION_MAJOR || \ major == LXC_VERSION_MAJOR && minor > LXC_VERSION_MINOR || \ major == LXC_VERSION_MAJOR && minor == LXC_VERSION_MINOR && micro > LXC_VERSION_MICRO))) extern bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); extern void go_lxc_clear_config(struct lxc_container *c); extern bool go_lxc_clear_config_item(struct lxc_container *c, const char *key); extern bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype); extern bool go_lxc_console(struct lxc_container *c, int ttynum, int stdinfd, int stdoutfd, int stderrfd, int escape); extern bool go_lxc_create(struct lxc_container *c, const char *t, const char *bdevtype, int flags, char * const argv[]); extern bool go_lxc_defined(struct lxc_container *c); extern bool go_lxc_destroy(struct lxc_container *c); extern bool go_lxc_destroy_with_snapshots(struct lxc_container *c); extern bool go_lxc_freeze(struct lxc_container *c); extern bool go_lxc_load_config(struct lxc_container *c, const char *alt_file); extern bool go_lxc_may_control(struct lxc_container *c); extern bool go_lxc_reboot(struct lxc_container *c); extern bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path); extern bool go_lxc_rename(struct lxc_container *c, const char *newname); extern bool go_lxc_running(struct lxc_container *c); extern bool go_lxc_save_config(struct lxc_container *c, const char *alt_file); extern bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value); extern bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value); extern bool go_lxc_set_config_path(struct lxc_container *c, const char *path); extern bool go_lxc_shutdown(struct lxc_container *c, int timeout); extern bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname); extern bool go_lxc_snapshot_destroy_all(struct lxc_container *c); extern bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname); extern bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]); extern bool go_lxc_stop(struct lxc_container *c); extern bool go_lxc_unfreeze(struct lxc_container *c); extern bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout); extern bool go_lxc_want_close_all_fds(struct lxc_container *c, bool state); extern bool go_lxc_want_daemonize(struct lxc_container *c, bool state); extern char* go_lxc_config_file_name(struct lxc_container *c); extern char* go_lxc_get_cgroup_item(struct lxc_container *c, const char *key); extern char* go_lxc_get_config_item(struct lxc_container *c, const char *key); extern char** go_lxc_get_interfaces(struct lxc_container *c); extern char** go_lxc_get_ips(struct lxc_container *c, const char *interface, const char *family, int scope); extern char* go_lxc_get_keys(struct lxc_container *c, const char *key); extern char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key); extern const char* go_lxc_get_config_path(struct lxc_container *c); extern const char* go_lxc_state(struct lxc_container *c); extern int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[]); extern int go_lxc_attach(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env); extern int go_lxc_attach_no_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[], pid_t *attached_pid); extern int go_lxc_console_getfd(struct lxc_container *c, int ttynum); extern int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret); extern int go_lxc_snapshot(struct lxc_container *c); extern pid_t go_lxc_init_pid(struct lxc_container *c); extern bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose); extern bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose); extern bool go_lxc_config_item_is_supported(const char *key); /* n.b. that we're just adding the fields here to shorten the definition * of go_lxc_migrate; in the case where we don't have the ->migrate API call, * we don't want to have to pass all the arguments in to let conditional * compilation handle things, but the call will still fail */ #if LXC_VERSION_MAJOR != 2 struct migrate_opts { char *directory; bool verbose; bool stop; char *predump_dir; }; #endif /* This is a struct that we can add "extra" (i.e. options added after 2.0.0) * migrate options to, so that we don't have to have a massive function * signature when the list of options grows. */ struct extra_migrate_opts { bool preserves_inodes; char *action_script; uint64_t ghost_limit; uint64_t features_to_check; }; int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras); extern bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); extern bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); #if !VERSION_AT_LEAST(3, 0, 0) struct lxc_console_log { bool clear; bool read; uint64_t *read_max; char *data; bool write_logfile; }; #endif extern int go_lxc_console_log(struct lxc_container *c, struct lxc_console_log *log); extern int go_lxc_error_num(struct lxc_container *c); golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/lxc_test.go000066400000000000000000000676161323041231200232700ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc import ( "fmt" "math/rand" "os" "runtime" "strconv" "strings" "sync" "syscall" "testing" "time" ) const ( ContainerName = "lorem" SnapshotName = "snap0" ContainerRestoreName = "ipsum" ContainerCloneName = "consectetur" ContainerCloneOverlayName = "adipiscing" ContainerCloneAufsName = "pellentesque" ) func PathExists(name string) bool { _, err := os.Lstat(name) if err != nil && os.IsNotExist(err) { return false } return true } func unprivileged() bool { return os.Geteuid() != 0 } func supported(moduleName string) bool { if _, err := os.Stat("/sys/module/" + moduleName); err != nil { return false } return true } func TestVersion(t *testing.T) { t.Logf("LXC version: %s", Version()) } func TestDefaultConfigPath(t *testing.T) { if DefaultConfigPath() == "" { t.Errorf("DefaultConfigPath failed...") } } func TestSetConfigPath(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } currentPath := c.ConfigPath() if err := c.SetConfigPath("/tmp"); err != nil { t.Errorf(err.Error()) } newPath := c.ConfigPath() if currentPath == newPath { t.Errorf("SetConfigPath failed...") } } func TestAcquire(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } Acquire(c) Release(c) } func TestConcurrentDefined_Negative(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) var wg sync.WaitGroup for i := 0; i <= 100; i++ { wg.Add(1) go func() { c, err := NewContainer(strconv.Itoa(rand.Intn(10))) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if c.Defined() { t.Errorf("Defined_Negative failed...") } wg.Done() }() } wg.Wait() } func TestDefined_Negative(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.Defined() { t.Errorf("Defined_Negative failed...") } } func TestExecute(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.Execute("/bin/true"); err != nil { t.Errorf(err.Error()) } } func TestSetVerbosity(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } c.SetVerbosity(Quiet) } func TestCreate(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Create(BusyboxTemplateOptions); err != nil { t.Errorf(err.Error()) } } func TestClone(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err = c.Clone(ContainerCloneName, DefaultCloneOptions); err != nil { t.Errorf(err.Error()) } } func TestCloneUsingOverlayfs(t *testing.T) { if !supported("overlayfs") { t.Skip("skipping test as overlayfs support is missing.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } err = c.Clone(ContainerCloneOverlayName, CloneOptions{ Backend: Overlayfs, KeepName: true, KeepMAC: true, Snapshot: true, }) if err != nil { t.Errorf(err.Error()) } } func TestCloneUsingAufs(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } if !supported("aufs") { t.Skip("skipping test as aufs support is missing.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } err = c.Clone(ContainerCloneAufsName, CloneOptions{ Backend: Aufs, KeepName: true, KeepMAC: true, Snapshot: true, }) if err != nil { t.Errorf(err.Error()) } } func TestCreateSnapshot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CreateSnapshot(); err != nil { t.Errorf(err.Error()) } } func TestCreateSnapshots(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } for i := 0; i < 3; i++ { if _, err := c.CreateSnapshot(); err != nil { t.Errorf(err.Error()) } } } func TestRestoreSnapshot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } snapshot := Snapshot{Name: SnapshotName} if err := c.RestoreSnapshot(snapshot, ContainerRestoreName); err != nil { t.Errorf(err.Error()) } } func TestConcurrentCreate(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup options := BusyboxTemplateOptions for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if err := c.Create(options); err != nil { t.Errorf(err.Error()) } wg.Done() }(i) } wg.Wait() } func TestSnapshots(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.Snapshots(); err != nil { t.Errorf(err.Error()) } } func TestConcurrentStart(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } if err := c.Start(); err != nil { t.Errorf(err.Error()) } c.Wait(RUNNING, 30*time.Second) if !c.Running() { t.Errorf("Starting the container failed...") } wg.Done() }(i) } wg.Wait() } func TestConfigFileName(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.ConfigFileName() == "" { t.Errorf("ConfigFileName failed...") } } func TestDefined_Positive(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if !c.Defined() { t.Errorf("Defined_Positive failed...") } } func TestConcurrentDefined_Positive(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i <= 100; i++ { wg.Add(1) go func() { c, err := NewContainer(strconv.Itoa(rand.Intn(10))) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if !c.Defined() { t.Errorf("Defined_Positive failed...") } wg.Done() }() } wg.Wait() } func TestInitPid_Negative(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.InitPid() != -1 { t.Errorf("InitPid failed...") } } func TestStart(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Start(); err != nil { t.Errorf(err.Error()) } c.Wait(RUNNING, 30*time.Second) if !c.Running() { t.Errorf("Starting the container failed...") } } func TestWaitIPAddresses(t *testing.T) { if !unprivileged() { t.Skip("skipping test in privileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.WaitIPAddresses(30 * time.Second); err != nil { t.Errorf(err.Error()) } } func TestControllable(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if !c.Controllable() { t.Errorf("Controling the container failed...") } } func TestContainerNames(t *testing.T) { if ContainerNames() == nil { t.Errorf("ContainerNames failed...") } } func TestDefinedContainerNames(t *testing.T) { if DefinedContainerNames() == nil { t.Errorf("DefinedContainerNames failed...") } } func TestActiveContainerNames(t *testing.T) { if ActiveContainerNames() == nil { t.Errorf("ActiveContainerNames failed...") } } func TestContainers(t *testing.T) { if Containers() == nil { t.Errorf("Containers failed...") } } func TestDefinedContainers(t *testing.T) { if DefinedContainers() == nil { t.Errorf("DefinedContainers failed...") } } func TestActiveContainers(t *testing.T) { if ActiveContainers() == nil { t.Errorf("ActiveContainers failed...") } } func TestRunning(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if !c.Running() { t.Errorf("Checking the container failed...") } } func TestWantDaemonize(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.WantDaemonize(false); err != nil || c.Daemonize() { t.Errorf("WantDaemonize failed...") } } func TestWantCloseAllFds(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.WantCloseAllFds(true); err != nil { t.Errorf("WantCloseAllFds failed...") } } func TestSetLogLevel(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SetLogLevel(WARN); err != nil || c.LogLevel() != WARN { t.Errorf("SetLogLevel( failed...") } } func TestSetLogFile(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SetLogFile("/tmp/" + ContainerName); err != nil || c.LogFile() != "/tmp/"+ContainerName { t.Errorf("SetLogFile failed...") } } func TestInitPid_Positive(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.InitPid() == -1 { t.Errorf("InitPid failed...") } } func TestName(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.Name() != ContainerName { t.Errorf("Name failed...") } } func TestFreeze(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Freeze(); err != nil { t.Errorf(err.Error()) } c.Wait(FROZEN, 30*time.Second) if c.State() != FROZEN { t.Errorf("Freezing the container failed...") } } func TestUnfreeze(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Unfreeze(); err != nil { t.Errorf(err.Error()) } c.Wait(RUNNING, 30*time.Second) if !c.Running() { t.Errorf("Unfreezing the container failed...") } } func TestLoadConfigFile(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.LoadConfigFile(c.ConfigFileName()); err != nil { t.Errorf(err.Error()) } } func TestSaveConfigFile(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SaveConfigFile(c.ConfigFileName()); err != nil { t.Errorf(err.Error()) } } func TestConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.utsname")[0] != ContainerName { t.Errorf("ConfigItem failed...") } } func TestSetConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.SetConfigItem("lxc.utsname", ContainerName); err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.utsname")[0] != ContainerName { t.Errorf("ConfigItem failed...") } } func TestRunningConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if c.RunningConfigItem("lxc.network.0.type") == nil { t.Errorf("RunningConfigItem failed...") } } func TestSetCgroupItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } maxMem := c.CgroupItem("memory.max_usage_in_bytes")[0] currentMem := c.CgroupItem("memory.limit_in_bytes")[0] if err := c.SetCgroupItem("memory.limit_in_bytes", maxMem); err != nil { t.Errorf(err.Error()) } newMem := c.CgroupItem("memory.limit_in_bytes")[0] if newMem == currentMem { t.Errorf("SetCgroupItem failed...") } } func TestClearConfigItem(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.ClearConfigItem("lxc.cap.drop"); err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.cap.drop")[0] != "" { t.Errorf("ClearConfigItem failed...") } } func TestConfigKeys(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } keys := "" if VersionAtLeast(2, 1, 0) { keys = strings.Join(c.ConfigKeys("lxc.net.0"), " ") } else { keys = strings.Join(c.ConfigKeys("lxc.network.0"), " ") } if !strings.Contains(keys, "mtu") { t.Errorf("Keys failed...") } } func TestInterfaces(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.Interfaces(); err != nil { t.Errorf(err.Error()) } } func TestInterfaceStats(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.InterfaceStats(); err != nil { t.Errorf(err.Error()) } } func TestMemoryUsage(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemoryUsage(); err != nil { t.Errorf(err.Error()) } } func TestKernelMemoryUsage(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.KernelMemoryUsage(); err != nil { t.Errorf(err.Error()) } } func TestMemorySwapUsage(t *testing.T) { if !PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") { t.Skip("skipping the test as it requires memory.memsw.limit_in_bytes to be set") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemorySwapUsage(); err != nil { t.Errorf(err.Error()) } } func TestBlkioUsage(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.BlkioUsage(); err != nil { t.Errorf(err.Error()) } } func TestMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemoryLimit(); err != nil { t.Errorf(err.Error()) } } func TestSoftMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.SoftMemoryLimit(); err != nil { t.Errorf(err.Error()) } } func TestKernelMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.KernelMemoryLimit(); err != nil { t.Errorf(err.Error()) } } func TestMemorySwapLimit(t *testing.T) { if !PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") { t.Skip("skipping the test as it requires memory.memsw.limit_in_bytes to be set") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.MemorySwapLimit(); err != nil { t.Errorf(err.Error()) } } func TestSetMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemLimit, err := c.MemoryLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetMemoryLimit(oldMemLimit * 4); err != nil { t.Errorf(err.Error()) } newMemLimit, err := c.MemoryLimit() if err != nil { t.Errorf(err.Error()) } if newMemLimit != oldMemLimit*4 { t.Errorf("SetMemoryLimit failed") } } func TestSetSoftMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemLimit, err := c.MemoryLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetSoftMemoryLimit(oldMemLimit * 4); err != nil { t.Errorf(err.Error()) } newMemLimit, err := c.SoftMemoryLimit() if err != nil { t.Errorf(err.Error()) } if newMemLimit != oldMemLimit*4 { t.Errorf("SetSoftMemoryLimit failed") } } func TestSetKernelMemoryLimit(t *testing.T) { t.Skip("skipping the test as it requires memory.kmem.limit_in_bytes to be set") c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemLimit, err := c.KernelMemoryLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetKernelMemoryLimit(oldMemLimit * 4); err != nil { t.Errorf(err.Error()) } newMemLimit, err := c.KernelMemoryLimit() if err != nil { t.Errorf(err.Error()) } // Floats aren't exactly exact, check that we did get something smaller if newMemLimit < oldMemLimit*3 { t.Errorf("SetKernelMemoryLimit failed") } } func TestSetMemorySwapLimit(t *testing.T) { if !PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") { t.Skip("skipping the test as it requires memory.memsw.limit_in_bytes to be set") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } oldMemorySwapLimit, err := c.MemorySwapLimit() if err != nil { t.Errorf(err.Error()) } if err := c.SetMemorySwapLimit(oldMemorySwapLimit / 4); err != nil { t.Errorf(err.Error()) } newMemorySwapLimit, err := c.MemorySwapLimit() if err != nil { t.Errorf(err.Error()) } // Floats aren't exactly exact, check that we did get something smaller if newMemorySwapLimit > oldMemorySwapLimit/3 { t.Errorf("SetSwapLimit failed") } } func TestCPUTime(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CPUTime(); err != nil { t.Errorf(err.Error()) } } func TestCPUTimePerCPU(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CPUTimePerCPU(); err != nil { t.Errorf(err.Error()) } } func TestCPUStats(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.CPUStats(); err != nil { t.Errorf(err.Error()) } } func TestRunCommandNoWait(t *testing.T) { c, err := NewContainer("TestRunCommandNoWait") if err != nil { t.Errorf(err.Error()) t.FailNow() } if err := c.Create(BusyboxTemplateOptions); err != nil { t.Errorf(err.Error()) t.FailNow() } defer c.Destroy() err = c.Start() if err != nil { t.Errorf(err.Error()) t.FailNow() } defer c.Stop() argsThree := []string{"/bin/sh", "-c", "exit 0"} pid, err := c.RunCommandNoWait(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) t.FailNow() } proc, err := os.FindProcess(pid) if err != nil { t.Errorf(err.Error()) t.FailNow() } procState, err := proc.Wait() if err != nil { t.Errorf(err.Error()) t.FailNow() } if !procState.Success() { t.Errorf("Expected success") t.FailNow() } argsThree = []string{"/bin/sh", "-c", "exit 1"} pid, err = c.RunCommandNoWait(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) t.FailNow() } proc, err = os.FindProcess(pid) if err != nil { t.Errorf(err.Error()) t.FailNow() } procState, err = proc.Wait() if err != nil { t.Errorf(err.Error()) t.FailNow() } if procState.Success() { t.Errorf("Expected failure") t.FailNow() } } func TestRunCommand(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } argsThree := []string{"/bin/sh", "-c", "exit 0"} ok, err := c.RunCommand(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } argsThree = []string{"/bin/sh", "-c", "exit 1"} ok, err = c.RunCommand(argsThree, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) } if ok { t.Errorf("Expected failure") } } func TestCommandWithEnv(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.Env = []string{"FOO=BAR"} options.ClearEnv = true args := []string{"/bin/sh", "-c", "test $FOO = 'BAR'"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithEnvToKeep(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.ClearEnv = true options.EnvToKeep = []string{"TERM"} args := []string{"/bin/sh", "-c", fmt.Sprintf("test $TERM = '%s'", os.Getenv("TERM"))} ok, err := c.RunCommand(args, DefaultAttachOptions) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithCwd(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.Cwd = "/tmp" args := []string{"/bin/sh", "-c", "test `pwd` = /tmp"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithUIDGID(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.UID = 1000 options.GID = 1000 args := []string{"/bin/sh", "-c", "test `id -u` = 1000 && test `id -g` = 1000"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestCommandWithArch(t *testing.T) { uname := syscall.Utsname{} if err := syscall.Uname(&uname); err != nil { t.Errorf(err.Error()) } arch := "" for _, c := range uname.Machine { if c == 0 { break } arch += string(byte(c)) } if arch != "x86_64" && arch != "i686" { t.Skip("skipping architecture test, not on x86") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } options := DefaultAttachOptions options.Arch = X86 args := []string{"/bin/sh", "-c", "test `uname -m` = i686"} ok, err := c.RunCommand(args, options) if err != nil { t.Errorf(err.Error()) } if !ok { t.Errorf("Expected success") } } func TestConsoleFd(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.ConsoleFd(0); err != nil { t.Errorf(err.Error()) } } func TestIPAddress(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if unprivileged() { time.Sleep(3 * time.Second) } if _, err := c.IPAddress("lo"); err != nil { t.Errorf(err.Error()) } } func TestIPv4Address(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if unprivileged() { time.Sleep(3 * time.Second) } if _, err := c.IPv4Address("lo"); err != nil { t.Errorf(err.Error()) } } func TestIPv46ddress(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if unprivileged() { time.Sleep(3 * time.Second) } if _, err := c.IPv6Address("lo"); err != nil { t.Errorf(err.Error()) } } func TestAddDeviceNode(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.AddDeviceNode("/dev/network_latency"); err != nil { t.Errorf(err.Error()) } } func TestRemoveDeviceNode(t *testing.T) { if unprivileged() { t.Skip("skipping test in unprivileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { t.Errorf(err.Error()) } } func TestIPv4Addresses(t *testing.T) { if !unprivileged() { t.Skip("skipping test in privileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.IPv4Addresses(); err != nil { t.Errorf(err.Error()) } } func TestIPv6Addresses(t *testing.T) { if !unprivileged() { t.Skip("skipping test in privileged mode.") } c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if _, err := c.IPv6Addresses(); err != nil { t.Errorf(err.Error()) } } func TestReboot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Reboot(); err != nil { t.Errorf("Rebooting the container failed...") } c.Wait(RUNNING, 30*time.Second) } func TestConcurrentShutdown(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } if err := c.Shutdown(30 * time.Second); err != nil { t.Errorf(err.Error()) } c.Wait(STOPPED, 30*time.Second) if c.Running() { t.Errorf("Shutting down the container failed...") } wg.Done() }(i) } wg.Wait() } func TestShutdown(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Shutdown(30 * time.Second); err != nil { t.Errorf(err.Error()) } c.Wait(STOPPED, 30*time.Second) if c.Running() { t.Errorf("Shutting down the container failed...") } } func TestStop(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Start(); err != nil { t.Errorf(err.Error()) } if err := c.Stop(); err != nil { t.Errorf(err.Error()) } c.Wait(STOPPED, 30*time.Second) if c.Running() { t.Errorf("Stopping the container failed...") } } func TestDestroySnapshot(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } snapshot := Snapshot{Name: SnapshotName} if err := c.DestroySnapshot(snapshot); err != nil { t.Errorf(err.Error()) } } func TestDestroyAllSnapshots(t *testing.T) { c, err := NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.DestroyAllSnapshots(); err != nil { if err == ErrNotSupported { t.Skip("skipping due to lxc version.") } t.Errorf(err.Error()) } } func TestDestroy(t *testing.T) { if supported("overlayfs") { c, err := NewContainer(ContainerCloneOverlayName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } if !unprivileged() && supported("aufs") { c, err := NewContainer(ContainerCloneAufsName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } c, err := NewContainer(ContainerCloneName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } c, err = NewContainer(ContainerRestoreName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } c, err = NewContainer(ContainerName) if err != nil { t.Errorf(err.Error()) } if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } func TestConcurrentDestroy(t *testing.T) { defer runtime.GOMAXPROCS(runtime.NumCPU()) if unprivileged() { t.Skip("skipping test in unprivileged mode.") } var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(i int) { c, err := NewContainer(strconv.Itoa(i)) if err != nil { t.Errorf(err.Error()) } // sleep for a while to simulate some dummy work time.Sleep(time.Millisecond * time.Duration(rand.Intn(250))) if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } wg.Done() }(i) } wg.Wait() } func TestBackendStore(t *testing.T) { var X struct { store BackendStore } if X.store.String() != "" { t.Error("zero value of BackendStore should be invalid") } } func TestState(t *testing.T) { var X struct { state State } if X.state.String() != "" { t.Error("zero value of State should be invalid") } } func TestSupportedConfigItems(t *testing.T) { if VersionAtLeast(2, 1, 0) { if !IsSupportedConfigItem("lxc.arch") { t.Errorf("IsSupportedConfigItem failed to detect \"lxc.arch\" as supported config item...") } if IsSupportedConfigItem("lxc.nonsense") { t.Errorf("IsSupportedConfigItem failed to detect \"lxc.nonsense\" as unsupported config item...") } } } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/options.go000066400000000000000000000122621323041231200231210ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc import ( "os" ) // AttachOptions type is used for defining various attach options. type AttachOptions struct { // Specify the namespaces to attach to, as OR'ed list of clone flags (syscall.CLONE_NEWNS | syscall.CLONE_NEWUTS ...). Namespaces int // Specify the architecture which the kernel should appear to be running as to the command executed. Arch Personality // Cwd specifies the working directory of the command. Cwd string // UID specifies the user id to run as. UID int // GID specifies the group id to run as. GID int // If ClearEnv is true the environment is cleared before running the command. ClearEnv bool // Env specifies the environment of the process. Env []string // EnvToKeep specifies the environment of the process when ClearEnv is true. EnvToKeep []string // StdinFd specifies the fd to read input from. StdinFd uintptr // StdoutFd specifies the fd to write output to. StdoutFd uintptr // StderrFd specifies the fd to write error output to. StderrFd uintptr } // DefaultAttachOptions is a convenient set of options to be used. var DefaultAttachOptions = AttachOptions{ Namespaces: -1, Arch: -1, Cwd: "/", UID: -1, GID: -1, ClearEnv: false, Env: nil, EnvToKeep: nil, StdinFd: os.Stdin.Fd(), StdoutFd: os.Stdout.Fd(), StderrFd: os.Stderr.Fd(), } // TemplateOptions type is used for defining various template options. type TemplateOptions struct { // Template specifies the name of the template. Template string // Backend specifies the type of the backend. Backend BackendStore // Distro specifies the name of the distribution. Distro string // Release specifies the name/version of the distribution. Release string // Arch specified the architecture of the container. Arch string // Variant specifies the variant of the image (default: "default"). Variant string // Image server (default: "images.linuxcontainers.org"). Server string // GPG keyid (default: 0x...). KeyID string // GPG keyserver to use. KeyServer string // Disable GPG validation (not recommended). DisableGPGValidation bool // Flush the local copy (if present). FlushCache bool // Force the use of the local copy even if expired. ForceCache bool // ExtraArgs provides a way to specify template specific args. ExtraArgs []string } // DownloadTemplateOptions is a convenient set of options for "download" template. var DownloadTemplateOptions = TemplateOptions{ Template: "download", Distro: "ubuntu", Release: "trusty", Arch: "amd64", } // BusyboxTemplateOptions is a convenient set of options for "busybox" template. var BusyboxTemplateOptions = TemplateOptions{ Template: "busybox", } // UbuntuTemplateOptions is a convenient set of options for "ubuntu" template. var UbuntuTemplateOptions = TemplateOptions{ Template: "ubuntu", } // ConsoleOptions type is used for defining various console options. type ConsoleOptions struct { // Tty number to attempt to allocate, -1 to allocate the first available tty, or 0 to allocate the console. Tty int // StdinFd specifies the fd to read input from. StdinFd uintptr // StdoutFd specifies the fd to write output to. StdoutFd uintptr // StderrFd specifies the fd to write error output to. StderrFd uintptr // EscapeCharacter (a means , b maens ). EscapeCharacter rune } // DefaultConsoleOptions is a convenient set of options to be used. var DefaultConsoleOptions = ConsoleOptions{ Tty: -1, StdinFd: os.Stdin.Fd(), StdoutFd: os.Stdout.Fd(), StderrFd: os.Stderr.Fd(), EscapeCharacter: 'a', } // CloneOptions type is used for defining various clone options. type CloneOptions struct { // Backend specifies the type of the backend. Backend BackendStore // lxcpath in which to create the new container. If not set the original container's lxcpath will be used. ConfigPath string // Do not change the hostname of the container (in the root filesystem). KeepName bool // Use the same MAC address as the original container, rather than generating a new random one. KeepMAC bool // Create a snapshot rather than copy. Snapshot bool } // DefaultCloneOptions is a convenient set of options to be used. var DefaultCloneOptions = CloneOptions{ Backend: Directory, } // CheckpointOptions type is used for defining checkpoint options for CRIU. type CheckpointOptions struct { Directory string Stop bool Verbose bool } // RestoreOptions type is used for defining restore options for CRIU. type RestoreOptions struct { Directory string Verbose bool } // MigrateOptions type is used for defining migrate options. type MigrateOptions struct { Directory string PredumpDir string ActionScript string Verbose bool Stop bool PreservesInodes bool GhostLimit uint64 FeaturesToCheck CriuFeatures } // ConsoleLogOptioins type is used for defining console log options. type ConsoleLogOptions struct { ClearLog bool ReadLog bool ReadMax uint64 WriteToLogFile bool } golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/type.go000066400000000000000000000114051323041231200224050ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc // #include import "C" import "fmt" // Verbosity type type Verbosity int const ( // Quiet makes some API calls not to write anything to stdout Quiet Verbosity = 1 << iota // Verbose makes some API calls write to stdout Verbose ) // BackendStore type specifies possible backend types. type BackendStore int const ( // Btrfs backendstore type Btrfs BackendStore = iota + 1 // Directory backendstore type Directory // LVM backendstore type LVM // ZFS backendstore type ZFS // Aufs backendstore type Aufs // Overlayfs backendstore type Overlayfs // Loopback backendstore type Loopback // Best backendstore type Best ) // BackendStore as string func (t BackendStore) String() string { switch t { case Directory: return "dir" case ZFS: return "zfs" case Btrfs: return "btrfs" case LVM: return "lvm" case Aufs: return "aufs" case Overlayfs: return "overlayfs" case Loopback: return "loopback" case Best: return "best" } return "" } var backendStoreMap = map[string]BackendStore{ "dir": Directory, "zfs": ZFS, "btrfs": Btrfs, "lvm": LVM, "aufs": Aufs, "overlayfs": Overlayfs, "loopback": Loopback, "best": Best, } // Set is the method to set the flag value, part of the flag.Value interface. func (t *BackendStore) Set(value string) error { backend, ok := backendStoreMap[value] if ok { *t = backend return nil } return ErrUnknownBackendStore } // State type specifies possible container states. type State int const ( // STOPPED means container is not running STOPPED State = iota + 1 // STARTING means container is starting STARTING // RUNNING means container is running RUNNING // STOPPING means container is stopping STOPPING // ABORTING means container is aborting ABORTING // FREEZING means container is freezing FREEZING // FROZEN means containe is frozen FROZEN // THAWED means container is thawed THAWED ) // StateMap provides the mapping betweens the state names and states var StateMap = map[string]State{ "STOPPED": STOPPED, "STARTING": STARTING, "RUNNING": RUNNING, "STOPPING": STOPPING, "ABORTING": ABORTING, "FREEZING": FREEZING, "FROZEN": FROZEN, "THAWED": THAWED, } // State as string func (t State) String() string { switch t { case STOPPED: return "STOPPED" case STARTING: return "STARTING" case RUNNING: return "RUNNING" case STOPPING: return "STOPPING" case ABORTING: return "ABORTING" case FREEZING: return "FREEZING" case FROZEN: return "FROZEN" case THAWED: return "THAWED" } return "" } // Taken from http://golang.org/doc/effective_go.html#constants // ByteSize type type ByteSize float64 const ( _ = iota // KB - kilobyte KB ByteSize = 1 << (10 * iota) // MB - megabyte MB // GB - gigabyte GB // TB - terabyte TB // PB - petabyte PB // EB - exabyte EB // ZB - zettabyte ZB // YB - yottabyte YB ) func (b ByteSize) String() string { switch { case b >= YB: return fmt.Sprintf("%.2fYB", b/YB) case b >= ZB: return fmt.Sprintf("%.2fZB", b/ZB) case b >= EB: return fmt.Sprintf("%.2fEB", b/EB) case b >= PB: return fmt.Sprintf("%.2fPB", b/PB) case b >= TB: return fmt.Sprintf("%.2fTB", b/TB) case b >= GB: return fmt.Sprintf("%.2fGB", b/GB) case b >= MB: return fmt.Sprintf("%.2fMB", b/MB) case b >= KB: return fmt.Sprintf("%.2fKB", b/KB) } return fmt.Sprintf("%.2fB", b) } // LogLevel type specifies possible log levels. type LogLevel int const ( // TRACE priority TRACE LogLevel = iota // DEBUG priority DEBUG // INFO priority INFO // NOTICE priority NOTICE // WARN priority WARN // ERROR priority ERROR // CRIT priority CRIT // ALERT priority ALERT // FATAL priority FATAL ) var logLevelMap = map[string]LogLevel{ "TRACE": TRACE, "DEBUG": DEBUG, "INFO": INFO, "NOTICE": NOTICE, "WARN": WARN, "ERROR": ERROR, "CRIT": CRIT, "ALERT": ALERT, "FATAL": FATAL, } func (l LogLevel) String() string { switch l { case TRACE: return "TRACE" case DEBUG: return "DEBUG" case INFO: return "INFO" case NOTICE: return "NOTICE" case WARN: return "WARN" case ERROR: return "ERROR" case CRIT: return "CRIT" case ALERT: return "ALERT" case FATAL: return "FATAL" } return "NOTSET" } // Personality allows to set the architecture for the container. type Personality int64 const ( X86 Personality = 0x0008 X86_64 = 0x0000 ) const ( MIGRATE_PRE_DUMP = 0 MIGRATE_DUMP = 1 MIGRATE_RESTORE = 2 MIGRATE_FEATURE_CHECK = 3 ) type CriuFeatures uint64 const ( FEATURE_MEM_TRACK CriuFeatures = 1 << iota FEATURE_LAZY_PAGES ) golang-gopkg-lxc-go-lxc.v2-0.0~git20180119.b964baa/util.go000066400000000000000000000041731323041231200224050ustar00rootroot00000000000000// Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved. // Use of this source code is governed by a LGPLv2.1 // license that can be found in the LICENSE file. // +build linux,cgo package lxc /* #include #include static char** makeCharArray(size_t size) { // caller checks return value return calloc(sizeof(char*), size); } static void setArrayString(char **array, char *string, size_t n) { array[n] = string; } static void freeCharArray(char **array, size_t size) { size_t i; for (i = 0; i < size; i++) { free(array[i]); } free(array); } static void freeSnapshotArray(struct lxc_snapshot *s, size_t size) { size_t i; for (i = 0; i < size; i++) { s[i].free(&s[i]); } free(s); } static size_t getArrayLength(char **array) { char **p; size_t size = 0; for (p = (char **)array; *p; p++) { size++; } return size; } */ import "C" import ( "reflect" "unsafe" ) func makeNullTerminatedArgs(args []string) **C.char { cparams := C.makeCharArray(C.size_t(len(args) + 1)) if cparams == nil { return nil } for i := 0; i < len(args); i++ { C.setArrayString(cparams, C.CString(args[i]), C.size_t(i)) } C.setArrayString(cparams, nil, C.size_t(len(args))) return cparams } func freeNullTerminatedArgs(cArgs **C.char, length int) { C.freeCharArray(cArgs, C.size_t(length+1)) } func convertArgs(cArgs **C.char) []string { if cArgs == nil { return nil } return convertNArgs(cArgs, int(C.getArrayLength(cArgs))) } func convertNArgs(cArgs **C.char, size int) []string { if cArgs == nil || size <= 0 { return nil } var A []*C.char hdr := reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(cArgs)), Len: size, Cap: size, } cArgsInterface := reflect.NewAt(reflect.TypeOf(A), unsafe.Pointer(&hdr)).Elem().Interface() result := make([]string, size) for i := 0; i < size; i++ { result[i] = C.GoString(cArgsInterface.([]*C.char)[i]) } C.freeCharArray(cArgs, C.size_t(size)) return result } func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) { C.freeSnapshotArray(snapshots, C.size_t(size)) }