pax_global_header00006660000000000000000000000064146324240270014516gustar00rootroot0000000000000052 comment=ccf9f03829bec42df26138e9debe10d80866a0a7 golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/000077500000000000000000000000001463242402700206175ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/.github/000077500000000000000000000000001463242402700221575ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/.github/workflows/000077500000000000000000000000001463242402700242145ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/.github/workflows/commits.yml000066400000000000000000000016421463242402700264150ustar00rootroot00000000000000name: Commits on: - pull_request permissions: contents: read jobs: dco-check: permissions: pull-requests: read # for tim-actions/get-pr-commits to get list of commits from the PR name: Signed-off-by (DCO) runs-on: ubuntu-20.04 steps: - name: Get PR Commits id: 'get-pr-commits' uses: tim-actions/get-pr-commits@master with: token: ${{ secrets.GITHUB_TOKEN }} - name: Check that all commits are signed-off uses: tim-actions/dco@master with: commits: ${{ steps.get-pr-commits.outputs.commits }} target-branch: permissions: contents: none name: Branch target runs-on: ubuntu-20.04 steps: - name: Check branch target env: TARGET: ${{ github.event.pull_request.base.ref }} run: | set -x [ "${TARGET}" = "v2" ] && exit 0 echo "Invalid branch target: ${TARGET}" exit 1 golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/.github/workflows/static.yml000066400000000000000000000013541463242402700262310ustar00rootroot00000000000000name: Static analysis on: - push - pull_request jobs: test: runs-on: ubuntu-20.04 steps: - name: Install Go uses: actions/setup-go@v4 with: go-version: stable - name: Checkout code uses: actions/checkout@v2 - name: Validate Go modules run: | make update-gomod git diff --exit-code - name: Install dependencies run: | sudo add-apt-repository ppa:ubuntu-lxc/daily -y sudo apt-get install -qq lxc-dev pkg-config libdbus-1-dev libseccomp-dev libcap-dev go install golang.org/x/lint/golint@latest go install golang.org/x/tools/cmd/goimports@latest - name: Static analysis run: make all golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/.github/workflows/test.yml000066400000000000000000000061301463242402700257160ustar00rootroot00000000000000name: CI tests on: - push - pull_request jobs: test: strategy: fail-fast: false matrix: go: - 1.20.x - stable os: - ubuntu-20.04 - ubuntu-22.04 runs-on: ${{ matrix.os }} steps: - name: Install Go uses: actions/setup-go@v4 with: go-version: ${{ matrix.go }} - name: Checkout code uses: actions/checkout@v2 - name: Install dependencies run: | sudo add-apt-repository ppa:ubuntu-lxc/daily -y sudo apt-get install -qq apparmor lxc lxc-dev pkg-config uidmap busybox libdbus-1-dev libseccomp-dev libcap-dev libselinux-dev nftables iptables - name: Reset all firewalling run: | sudo iptables -F sudo iptables -P INPUT ACCEPT sudo iptables -P OUTPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo nft flush ruleset - name: Setup test environment run: | # Setup uid/gid and veth allocations 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 # Local user configuration for userns mkdir -p ~/.config/lxc/ cp /etc/lxc/default.conf ~/.config/lxc/default.conf echo "lxc.idmap = u 0 100000 65536" | tee -a ~/.config/lxc/default.conf echo "lxc.idmap = g 0 100000 65536" | tee -a ~/.config/lxc/default.conf # Allow traversal to the containers mkdir -p ~/.local/share/lxc chmod +x ~/ ~/.local ~/.local/share ~/.local/share/lxc - name: Build the test run: go test -c -coverprofile=profile - name: Unprivileged tests env: DOWNLOAD_KEYSERVER: keyserver.ubuntu.com run: | # Make all cgroups writable if [ ! -e /sys/fs/cgroup/cgroup.controllers ]; then # CGroup 1 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-test sudo chown -R $USER: $d/lxc-test echo $$ | sudo tee $d/lxc-test/cgroup.procs done # Run the unprivileged tests ./go-lxc.test -test.v -test.coverprofile=/tmp/unpriv.out else # CGroup 2 sudo mkdir -p /sys/fs/cgroup/lxc-test sudo chown -R $USER: /sys/fs/cgroup/lxc-test echo $$ | sudo tee /sys/fs/cgroup/lxc-test/cgroup.procs # Run the unprivileged tests systemd-run --unit=go-lxc-test --user --scope -p "Delegate=yes" ./go-lxc.test -test.v -test.coverprofile=/tmp/unpriv.out fi - name: Privileged tests env: DOWNLOAD_KEYSERVER: keyserver.ubuntu.com run: sudo -E ./go-lxc.test -test.v -test.coverprofile=/tmp/priv.out - name: Code coverage run: make cover golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/.gitignore000066400000000000000000000000771463242402700226130ustar00rootroot00000000000000examples/*/* !examples/*/*.go coverage.out tags *.swp **/.idea golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/AUTHORS000066400000000000000000000010321463242402700216630ustar00rootroot00000000000000# 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+git20240606.27b3d11/LICENSE000066400000000000000000000657151463242402700216420ustar00rootroot00000000000000This 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+git20240606.27b3d11/Makefile000066400000000000000000000033171463242402700222630ustar00rootroot00000000000000NO_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-privileged: @echo "$(OK_COLOR)==> Running tests for privileged user $(NO_COLOR)" @sudo `which go` test -v -coverprofile=/tmp/priv.out @sudo `which go` test -tags static_build -v -coverprofile=/tmp/priv.out test-privileged-race: @echo "$(OK_COLOR)==> Running tests with -race flag for privileged user $(NO_COLOR)" @sudo `which go` test -race -v @sudo `which go` test -tags static_build -race -v test: @echo "$(OK_COLOR)==> Running tests for unprivileged user $(NO_COLOR)" @`which go` test -v -coverprofile=/tmp/unpriv.out @`which go` test -tags static_build -v -coverprofile=/tmp/unpriv.out test-race: @echo "$(OK_COLOR)==> Running tests with -race flag for unprivileged user $(NO_COLOR)" @`which go` test -race -v @`which go` test -tags static_build -race -v cover: @echo "$(OK_COLOR)==> Running cover for privileged user $(NO_COLOR)" @`which go` tool cover -func=/tmp/priv.out || true @echo "$(OK_COLOR)==> Running cover for unprivileged user $(NO_COLOR)" @`which go` tool cover -func=/tmp/unpriv.out || true doc: @`which go` doc github.com/lxc/go-lxc | 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: @`which go` build -gcflags -m ctags: @ctags -R --languages=c,go update-gomod: go get -t -v -d -u ./... go mod tidy scope: @echo "$(OK_COLOR)==> Exported container calls in container.go $(NO_COLOR)" @/bin/grep -E "\bc+\.([A-Z])\w+" container.go || true .PHONY: all format test doc vet lint ctags golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/README.md000066400000000000000000000067551463242402700221130ustar00rootroot00000000000000[![go-lxc](https://linuxcontainers.org/static/img/containers.png)](https://linuxcontainers.org/) # Go Bindings for LXC (Linux Containers) LXC is the well-known and heavily tested low-level Linux container runtime. It is in active development since 2008 and has proven itself in critical production environments world-wide. Some of its core contributors are the same people that helped to implement various well-known containerization features inside the Linux kernel. This package implements [Go](https://golang.org) bindings for the [LXC](https://linuxcontainers.org/lxc/introduction/) C API (liblxc). ## Status Type | Service | Status --- | --- | --- CI (Linux) | Github | [![CI tests](https://github.com/lxc/go-lxc/actions/workflows/test.yml/badge.svg?branch=v2)](https://github.com/lxc/go-lxc/actions/workflows/test.yml) Go documentation | Godoc | [![GoDoc](https://godoc.org/github.com/lxc/go-lxc?status.svg)](https://godoc.org/github.com/lxc/go-lxc) Static analysis | GoReport | [![Go Report Card](https://goreportcard.com/badge/github.com/lxc/go-lxc)](https://goreportcard.com/report/github.com/lxc/go-lxc) ## Requirements This package requires [LXC >= 1.0.0](https://github.com/lxc/lxc/releases) and its development package and their dependencies to be installed. Additionally, go-lxc requires Golang 1.10 or later to work. Following command should install required dependencies on Ubuntu 18.10: ```bash sudo apt update sudo apt install git golang gcc make liblxc1 liblxc-dev lxc-utils pkg-config ``` ## Installing To install it, run: ```bash go get github.com/lxc/go-lxc ``` ## Trying To try examples, run: ```bash # cd ~/go/src/github.com/lxc/go-lxc/examples/ # make ==> Running go vet ==> Building ... ... # create/create 2018/12/27 22:39:27 Creating container... # start/start 2018/12/27 22:39:39 Starting the container... 2018/12/27 22:39:39 Waiting container to startup networking... # attach/attach 2018/12/27 22:39:46 AttachShell root@rubik:/# hostname rubik root@rubik:/# exit exit 2018/12/27 22:39:52 RunCommand uid=0(root) gid=0(root) groups=0(root) # stop/stop 2018/12/27 22:39:54 Stopping the container... # destroy/destroy 2018/12/27 22:39:57 Destroying container... ``` ## Backwards Compatibility LXC has always focused on strong backwards compatibility. In fact, the API hasn't been broken from release `1.0.0` onwards. Main LXC is currently at version `2.*.*`. ## Examples See the [examples](https://github.com/lxc/go-lxc/tree/v2/examples) directory for some. ## Bug reports Bug reports can be filed at: ## Contributing Fixes and new features are greatly appreciated. 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. ## Getting help When you find you need help, the LXC projects provides you with several options. ### Discuss Forum We maintain an discuss forum at - https://discuss.linuxcontainers.org/ where you can get support. ### IRC You can find support by joining `#lxcontainers` on `Freenode`. ### Mailing Lists You can check out one of the two LXC mailing list archives and register if interested: - http://lists.linuxcontainers.org/listinfo/lxc-devel - http://lists.linuxcontainers.org/listinfo/lxc-users golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/cgo.go000066400000000000000000000003511463242402700217150ustar00rootroot00000000000000// 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. package lxc // #cgo CFLAGS: -fvisibility=hidden import "C" golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/container.go000066400000000000000000001502121463242402700231310ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package lxc // #include // #include // #include "lxc-binding.h" import "C" import ( "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "sync" "syscall" "time" "unsafe" "golang.org/x/sys/unix" ) // 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 } // Release decrements the reference counter of the container object. // nil on success or if reference was successfully dropped and container has been freed, and ErrReleaseFailed on error. func (c *Container) Release() error { c.mu.Lock() defer c.mu.Unlock() if C.lxc_container_put(c.container) == -1 { return ErrReleaseFailed } c.container = nil return nil } func (c *Container) name() string { if c.container == nil { return "" } 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 representation 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 { if c.container == nil { return false } 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 { if c.container == nil { return false } 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() if c.container == nil { return false } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 } gosnapshots := (*[(1 << 26) - 1]C.struct_lxc_snapshot)(unsafe.Pointer(csnapshots))[:size:size] 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 { if c.container == nil { return StateMap["STOPPED"] } 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() if c.container == nil { return -1 } return int(C.go_lxc_init_pid(c.container)) } // InitPidFd returns the pidfd of the container's init process. func (c *Container) InitPidFd() (*os.File, error) { c.mu.RLock() defer c.mu.RUnlock() if c.container == nil { return nil, ErrNotDefined } pidfd := int(C.go_lxc_init_pidfd(c.container)) if pidfd < 0 { return nil, unix.Errno(unix.EBADF) } return os.NewFile(uintptr(pidfd), "[pidfd]"), nil } // DevptsFd returns the pidfd of the container's init process. func (c *Container) DevptsFd() (*os.File, error) { c.mu.RLock() defer c.mu.RUnlock() if c.container == nil { return nil, ErrNotDefined } devptsFd := int(C.go_lxc_devpts_fd(c.container)) if devptsFd < 0 { return nil, unix.Errno(unix.EBADF) } return os.NewFile(uintptr(devptsFd), "/dev/pts/ptmx"), nil } // SeccompNotifyFd returns the seccomp notify fd of the container. func (c *Container) SeccompNotifyFd() (*os.File, error) { c.mu.RLock() defer c.mu.RUnlock() if c.container == nil { return nil, ErrNotDefined } notifyFd := int(C.go_lxc_seccomp_notify_fd(c.container)) if notifyFd < 0 { return nil, unix.Errno(unix.EBADF) } return os.NewFile(uintptr(notifyFd), "seccomp notify"), nil } // SeccompNotifyFdActive returns the seccomp notify fd of the running container. func (c *Container) SeccompNotifyFdActive() (*os.File, error) { c.mu.RLock() defer c.mu.RUnlock() if c.container == nil { return nil, ErrNotDefined } notifyFd := int(C.go_lxc_seccomp_notify_fd_active(c.container)) if notifyFd < 0 { return nil, unix.Errno(unix.EBADF) } return os.NewFile(uintptr(notifyFd), "seccomp notify"), nil } // SetTimeout sets the response receive timeout for commands func (c *Container) SetTimeout(timeout time.Duration) error { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return ErrNotDefined } ret := int(C.go_lxc_set_timeout(c.container, C.int(timeout.Seconds()))) if ret < 0 { return unix.Errno(-ret) } return nil } // Daemonize returns true if the container wished to be daemonized. func (c *Container) Daemonize() bool { c.mu.RLock() defer c.mu.RUnlock() if c.container == nil { return false } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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() if c.container == nil { return ErrNotDefined } // 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 c.container == nil { return ErrNotDefined } 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() if err := c.makeSure(isNotDefined); err != nil { return err } bdevspecs := buildBdevSpecs(options.BackendSpecs) // 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, bdevspecs, C.int(c.verbosity), cargs)) } else { ret = bool(C.go_lxc_create(c.container, ctemplate, cbackend, bdevspecs, 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } if err := c.makeSure(isNotRunning); err != nil { return err } if args != nil { if !bool(C.go_lxc_start(c.container, 0, makeNullTerminatedArgs(args))) { return ErrStartFailed } } else { if !bool(C.go_lxc_start(c.container, 0, nil)) { 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 c.container == nil { return ErrNotDefined } if err := c.makeSure(isNotRunning); err != nil { return err } if args != nil { if !bool(C.go_lxc_start(c.container, 1, makeNullTerminatedArgs(args))) { return ErrStartFailed } } else { if !bool(C.go_lxc_start(c.container, 1, nil)) { return ErrStartFailed } } return nil } // Execute executes the given command in a temporary container. func (c *Container) Execute(args ...string) ([]byte, error) { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isNotDefined); err != nil { return nil, err } os.MkdirAll(filepath.Join(c.configPath(), c.name()), 0700) c.saveConfigFile(filepath.Join(c.configPath(), c.name(), "config")) defer os.RemoveAll(filepath.Join(c.configPath(), c.name())) cargs := []string{"lxc-execute", "-n", c.name(), "-P", c.configPath(), "--"} cargs = append(cargs, args...) // FIXME: Go runtime and src/lxc/start.c signal_handler are not playing nice together so use lxc-execute for now // go-nuts thread: https://groups.google.com/forum/#!msg/golang-nuts/h9GbvfYv83w/5Ly_jvOr86wJ output, err := exec.Command(cargs[0], cargs[1:]...).CombinedOutput() if err != nil { // Do not suppress stderr if the exit code != 0. Return with err. if len(output) > 1 { return output, ErrExecuteFailed } return nil, ErrExecuteFailed } return output, nil } // Stop stops the container. func (c *Container) Stop() error { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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() if c.container == nil { return false } 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() if c.container == nil { return "" } // 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 { if c.container == nil { return nil } 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 { if c.container == nil { return ErrNotDefined } 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 { if c.container == nil { return nil } 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 { if c.container == nil { return nil } 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 { if c.container == nil { return ErrNotDefined } 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() if c.container == nil { return } 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() if c.container == nil { return ErrNotDefined } 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() if c.container == nil { return nil } var ret string 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)) ret = strings.TrimSpace(C.GoString(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() if c.container == nil { return ErrNotDefined } 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 { if c.container == nil { return ErrNotDefined } 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 { if c.container == nil { return "" } 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() if c.container == nil { return ErrNotDefined } cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) if !bool(C.go_lxc_set_config_path(c.container, cpath)) { return ErrSettingConfigPathFailed } return nil } // MemoryUsage returns memory usage of the container in bytes. func (c *Container) MemoryUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.usage_in_bytes", ErrMemLimit) } // MemoryLimit returns memory limit of the container in bytes. func (c *Container) MemoryLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.limit_in_bytes", ErrMemLimit) } // SetMemoryLimit sets memory limit of the container in bytes. func (c *Container) SetMemoryLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.limit_in_bytes", limit, ErrSettingMemoryLimitFailed) } // SoftMemoryLimit returns soft memory limit of the container in bytes. func (c *Container) SoftMemoryLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.soft_limit_in_bytes", ErrSoftMemLimit) } // SetSoftMemoryLimit sets soft memory limit of the container in bytes. func (c *Container) SetSoftMemoryLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.soft_limit_in_bytes", limit, ErrSettingSoftMemoryLimitFailed) } // KernelMemoryUsage returns current kernel memory allocation of the container in bytes. func (c *Container) KernelMemoryUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.kmem.usage_in_bytes", ErrKMemLimit) } // KernelMemoryLimit returns kernel memory limit of the container in bytes. func (c *Container) KernelMemoryLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.kmem.limit_in_bytes", ErrKMemLimit) } // SetKernelMemoryLimit sets kernel memory limit of the container in bytes. func (c *Container) SetKernelMemoryLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.kmem.limit_in_bytes", limit, ErrSettingKMemoryLimitFailed) } // MemorySwapUsage returns memory+swap usage of the container in bytes. func (c *Container) MemorySwapUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.memsw.usage_in_bytes", ErrMemorySwapLimit) } // MemorySwapLimit returns the memory+swap limit of the container in bytes. func (c *Container) MemorySwapLimit() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } return c.cgroupItemAsByteSize("memory.memsw.limit_in_bytes", ErrMemorySwapLimit) } // SetMemorySwapLimit sets memory+swap limit of the container in bytes. func (c *Container) SetMemorySwapLimit(limit ByteSize) error { c.mu.Lock() defer c.mu.Unlock() if err := c.makeSure(isRunning); err != nil { return err } return c.setCgroupItemWithByteSize("memory.memsw.limit_in_bytes", limit, ErrSettingMemorySwapLimitFailed) } // BlkioUsage returns number of bytes transferred to/from the disk by the container. func (c *Container) BlkioUsage() (ByteSize, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } ioServiceBytes := c.cgroupItem("blkio.throttle.io_service_bytes") if ioServiceBytes[0] == "" { return 0, nil } for _, v := range ioServiceBytes { b := strings.Split(v, " ") if b[0] == "Total" { blkioUsed, err := strconv.ParseFloat(b[1], 64) if err != nil { return -1, err } return ByteSize(blkioUsed), nil } } return -1, ErrBlkioUsage } // CPUTime returns the total CPU time (in nanoseconds) consumed by all tasks // in this cgroup (including tasks lower in the hierarchy). func (c *Container) CPUTime() (time.Duration, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return -1, err } usage := c.cgroupItem("cpuacct.usage") if usage[0] == "" { return 0, nil } cpuUsage, err := strconv.ParseInt(usage[0], 10, 64) if err != nil { return -1, err } return time.Duration(cpuUsage), nil } // CPUTimePerCPU returns the CPU time (in nanoseconds) consumed on each CPU by // all tasks in this cgroup (including tasks lower in the hierarchy). func (c *Container) CPUTimePerCPU() (map[int]time.Duration, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } usagePerCPU := c.cgroupItem("cpuacct.usage_percpu") if usagePerCPU[0] == "" { return map[int]time.Duration{0: 0}, nil } cpuTimes := make(map[int]time.Duration) for i, v := range strings.Split(usagePerCPU[0], " ") { cpuUsage, err := strconv.ParseInt(v, 10, 64) if err != nil { return nil, err } cpuTimes[i] = time.Duration(cpuUsage) } return cpuTimes, nil } // CPUStats returns the number of CPU cycles (in the units defined by USER_HZ on the system) // consumed by tasks in this cgroup and its children in both user mode and system (kernel) mode. func (c *Container) CPUStats() (map[string]int64, error) { c.mu.RLock() defer c.mu.RUnlock() if err := c.makeSure(isRunning); err != nil { return nil, err } stat := c.cgroupItem("cpuacct.stat") if stat[0] == "" { return map[string]int64{"user": 0, "system": 0}, nil } user, err := strconv.ParseInt(strings.Split(stat[0], "user ")[1], 10, 64) if err != nil { return nil, err } system, err := strconv.ParseInt(strings.Split(stat[1], "system ")[1], 10, 64) if err != nil { return nil, err } return map[string]int64{"user": user, "system": system}, nil } // ConsoleFd allocates a console tty from container // ttynum: tty number to attempt to allocate or -1 to allocate the first available tty // // Returns "ttyfd" on success, -1 on failure. The returned "ttyfd" is // used to keep the tty allocated. The caller should close "ttyfd" to // indicate that it is done with the allocated console so that it can // be allocated by another caller. func (c *Container) ConsoleFd(ttynum int) (int, error) { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return -1, ErrNotDefined } // FIXME: Make idiomatic if err := c.makeSure(isRunning); err != nil { return -1, err } ret := int(C.go_lxc_console_getfd(c.container, C.int(ttynum))) if ret < 0 { return ret, ErrAttachFailed } return ret, nil } // Console allocates and runs a console tty from container // // This function will not return until the console has been exited by the user. func (c *Container) Console(options ConsoleOptions) error { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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)) groups := makeGroups(options.Groups) 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), groups, C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, C.int(attachFlags(options)), )) if ret < 0 { return ErrAttachFailed } return nil } func attachFlags(opts AttachOptions) int { flags := C.LXC_ATTACH_DEFAULT if opts.RemountSysProc { flags |= C.LXC_ATTACH_REMOUNT_PROC_SYS } if opts.ElevatedPrivileges { flags &^= (C.LXC_ATTACH_MOVE_TO_CGROUP | C.LXC_ATTACH_DROP_CAPABILITIES | C.LXC_ATTACH_LSM_EXEC) } return flags } func makeGroups(groups []int) C.struct_lxc_groups_t { if len(groups) == 0 { return C.struct_lxc_groups_t{size: 0, list: nil} } l := make([]C.gid_t, len(groups)) for i, g := range groups { l[i] = C.gid_t(g) } return C.struct_lxc_groups_t{size: C.size_t(len(groups)), list: &l[0]} } func (c *Container) runCommandStatus(args []string, options AttachOptions) (int, error) { if c.container == nil { return -1, ErrNotDefined } 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)) groups := makeGroups(options.Groups) 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), groups, C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, cargs, C.int(attachFlags(options)), )) if ret < 0 { return ret, nil } // Mirror the behavior of WEXITSTATUS(). return int((ret & 0xFF00) >> 8), nil } // RunCommandStatus attachs a shell and runs the command within the container. // The process will wait for the command to finish and return the result of // waitpid(), i.e. the process' exit status. An error is returned only when // invocation of the command completely fails. func (c *Container) RunCommandStatus(args []string, options AttachOptions) (int, error) { c.mu.Lock() defer c.mu.Unlock() return c.runCommandStatus(args, options) } // RunCommandNoWait runs the given command and returns without waiting it to finish. func (c *Container) RunCommandNoWait(args []string, options AttachOptions) (int, error) { c.mu.Lock() defer c.mu.Unlock() if len(args) == 0 { return -1, ErrInsufficientNumberOfArguments } if err := c.makeSure(isRunning); err != nil { return -1, err } cargs := makeNullTerminatedArgs(args) if cargs == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cargs, len(args)) cenv := makeNullTerminatedArgs(options.Env) if cenv == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenv, len(options.Env)) cenvToKeep := makeNullTerminatedArgs(options.EnvToKeep) if cenvToKeep == nil { return -1, ErrAllocationFailed } defer freeNullTerminatedArgs(cenvToKeep, len(options.EnvToKeep)) cwd := C.CString(options.Cwd) defer C.free(unsafe.Pointer(cwd)) groups := makeGroups(options.Groups) 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), groups, C.int(options.StdinFd), C.int(options.StdoutFd), C.int(options.StderrFd), cwd, cenv, cenvToKeep, cargs, &attachedPid, C.int(attachFlags(options)), )) if ret < 0 { return ret, ErrAttachFailed } return int(attachedPid), nil } // RunCommand attachs a shell and runs the command within the container. // The process will wait for the command to finish and return a success status. An error // is returned only when invocation of the command completely fails. func (c *Container) RunCommand(args []string, options AttachOptions) (bool, error) { c.mu.Lock() defer c.mu.Unlock() ret, err := c.runCommandStatus(args, options) if err != nil { return false, err } if ret < 0 { return false, ErrAttachFailed } return ret == 0, nil } // Interfaces returns the names of the network interfaces. func (c *Container) Interfaces() ([]string, error) { c.mu.RLock() defer c.mu.RUnlock() if c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return nil, ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 c.container == nil { return ErrNotDefined } 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 specified netdev to the container. func (c *Container) AttachInterface(source, destination string) error { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return ErrNotDefined } 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 specified netdev from the container. func (c *Container) DetachInterface(source string) error { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return ErrNotDefined } 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 specified netdev from the container and renames it. func (c *Container) DetachInterfaceRename(source, target string) error { c.mu.Lock() defer c.mu.Unlock() if c.container == nil { return ErrNotDefined } 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() if c.container == nil { return nil, ErrNotDefined } cl := C.struct_lxc_console_log{ clear: C.bool(opt.ClearLog), read: C.bool(opt.ReadLog), data: nil, } // CGO is a fickle little beast: // We need to manually allocate memory here that we pass to C. If we // were to pass a GO pointer by passing a C.uint64_t pointer we'd end in // the situation where we have a GO pointer that points to a GO pointer. // Go will freak out when this happens. So give C its own memory. var buf unsafe.Pointer buf = C.malloc(C.sizeof_uint64_t) if buf == nil { return nil, syscall.ENOMEM } defer C.free(buf) cl.read_max = (*C.uint64_t)(buf) *cl.read_max = C.uint64_t(opt.ReadMax) ret := C.go_lxc_console_log(c.container, &cl) if ret < 0 { return nil, syscall.Errno(-ret) } numBytes := C.int(*cl.read_max) if C.uint64_t(numBytes) != *cl.read_max { return nil, syscall.ERANGE } return C.GoBytes(unsafe.Pointer(cl.data), numBytes), nil } // ErrorNum returns the error_num field of the container. func (c *Container) ErrorNum() int { if c.container == nil { return -1 } cError := C.go_lxc_error_num(c.container) return int(cError) } func buildBdevSpecs(o *BackendStoreSpecs) *C.struct_bdev_specs { if o == nil { return nil } // bdev_specs: // zfs requires zfsroot // lvm requires lvname/vgname/thinpool as well as fstype and fssize // btrfs requires nothing // dir requires nothing specs := C.struct_bdev_specs{} if o.FSType != "" { fstype := C.CString(o.FSType) specs.fstype = fstype defer C.free(unsafe.Pointer(fstype)) } if o.FSSize > 0 { specs.fssize = C.uint64_t(o.FSSize) } if o.ZFS.Root != "" { zfsroot := C.CString(o.ZFS.Root) specs.zfs.zfsroot = zfsroot defer C.free(unsafe.Pointer(zfsroot)) } if o.LVM.VG != "" { vg := C.CString(o.LVM.VG) specs.lvm.vg = vg defer C.free(unsafe.Pointer(vg)) } if o.LVM.Thinpool != "" { lv := C.CString(o.LVM.Thinpool) specs.lvm.thinpool = lv defer C.free(unsafe.Pointer(lv)) } if o.RBD.Name != "" { lv := C.CString(o.RBD.Name) specs.rbd.rbdname = lv defer C.free(unsafe.Pointer(lv)) } if o.RBD.Pool != "" { lv := C.CString(o.RBD.Pool) specs.rbd.rbdpool = lv defer C.free(unsafe.Pointer(lv)) } if o.Dir != nil { dir := C.CString(*o.Dir) specs.dir = dir defer C.free(unsafe.Pointer(dir)) } return &specs } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/doc.go000066400000000000000000000005261463242402700217160ustar00rootroot00000000000000/* 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+git20240606.27b3d11/error.go000066400000000000000000000213621463242402700223030ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package lxc const ( // ErrAddDeviceNodeFailed - adding device to container failed ErrAddDeviceNodeFailed = lxcError("adding device to container failed") // ErrAllocationFailed - allocating memory failed ErrAllocationFailed = lxcError("allocating memory failed") // ErrAlreadyDefined - container already defined ErrAlreadyDefined = lxcError("container already defined") // ErrAlreadyFrozen - container is already frozen ErrAlreadyFrozen = lxcError("container is already frozen") // ErrAlreadyRunning - container is already running ErrAlreadyRunning = lxcError("container is already running") // ErrAttachFailed - attaching to the container failed ErrAttachFailed = lxcError("attaching to the container failed") // ErrAttachInterfaceFailed - attaching specified netdev to the container failed ErrAttachInterfaceFailed = lxcError("attaching specified netdev to the container failed") // ErrBlkioUsage - BlkioUsage for the container failed ErrBlkioUsage = lxcError("BlkioUsage for the container failed") // ErrCheckpointFailed - checkpoint failed ErrCheckpointFailed = lxcError("checkpoint failed") // ErrClearingConfigItemFailed - clearing config item for the container failed ErrClearingConfigItemFailed = lxcError("clearing config item for the container failed") // ErrClearingCgroupItemFailed - clearing cgroup item for the container failed ErrClearingCgroupItemFailed = lxcError("clearing cgroup item for the container failed") // ErrCloneFailed - cloning the container failed ErrCloneFailed = lxcError("cloning the container failed") // ErrCloseAllFdsFailed - setting close_all_fds flag for container failed ErrCloseAllFdsFailed = lxcError("setting close_all_fds flag for container failed") // ErrCreateFailed - creating the container failed ErrCreateFailed = lxcError("creating the container failed") // ErrCreateSnapshotFailed - snapshotting the container failed ErrCreateSnapshotFailed = lxcError("snapshotting the container failed") // ErrDaemonizeFailed - setting daemonize flag for container failed ErrDaemonizeFailed = lxcError("setting daemonize flag for container failed") // ErrDestroyAllSnapshotsFailed - destroying all snapshots failed ErrDestroyAllSnapshotsFailed = lxcError("destroying all snapshots failed") // ErrDestroyFailed - destroying the container failed ErrDestroyFailed = lxcError("destroying the container failed") // ErrDestroySnapshotFailed - destroying the snapshot failed ErrDestroySnapshotFailed = lxcError("destroying the snapshot failed") // ErrDestroyWithAllSnapshotsFailed - destroying the container with all snapshots failed ErrDestroyWithAllSnapshotsFailed = lxcError("destroying the container with all snapshots failed") // ErrDetachInterfaceFailed - detaching specified netdev to the container failed ErrDetachInterfaceFailed = lxcError("detaching specified netdev to the container failed") // ErrExecuteFailed - executing the command in a temporary container failed ErrExecuteFailed = lxcError("executing the command in a temporary container failed") // ErrFreezeFailed - freezing the container failed ErrFreezeFailed = lxcError("freezing the container failed") // ErrInsufficientNumberOfArguments - insufficient number of arguments were supplied ErrInsufficientNumberOfArguments = lxcError("insufficient number of arguments were supplied") // ErrInterfaces - getting interface names for the container failed ErrInterfaces = lxcError("getting interface names for the container failed") // ErrIPAddresses - getting IP addresses of the container failed ErrIPAddresses = lxcError("getting IP addresses of the container failed") // ErrIPAddress - getting IP address on the interface of the container failed ErrIPAddress = lxcError("getting IP address on the interface of the container failed") // ErrIPv4Addresses - getting IPv4 addresses of the container failed ErrIPv4Addresses = lxcError("getting IPv4 addresses of the container failed") // ErrIPv6Addresses - getting IPv6 addresses of the container failed ErrIPv6Addresses = lxcError("getting IPv6 addresses of the container failed") // ErrKMemLimit - your kernel does not support cgroup kernel memory controller ErrKMemLimit = lxcError("your kernel does not support cgroup kernel memory controller") // ErrLoadConfigFailed - loading config file for the container failed ErrLoadConfigFailed = lxcError("loading config file for the container failed") // ErrMemLimit - your kernel does not support cgroup memory controller ErrMemLimit = lxcError("your kernel does not support cgroup memory controller") // ErrMemorySwapLimit - your kernel does not support cgroup swap controller ErrMemorySwapLimit = lxcError("your kernel does not support cgroup swap controller") // ErrMethodNotAllowed - the requested method is not currently supported with unprivileged containers ErrMethodNotAllowed = lxcError("the requested method is not currently supported with unprivileged containers") // ErrNewFailed - allocating the container failed ErrNewFailed = lxcError("allocating the container failed") // ErrNoSnapshot - container has no snapshot ErrNoSnapshot = lxcError("container has no snapshot") // ErrNotDefined - container is not defined ErrNotDefined = lxcError("container is not defined") // ErrNotFrozen - container is not frozen ErrNotFrozen = lxcError("container is not frozen") // ErrNotRunning - container is not running ErrNotRunning = lxcError("container is not running") // ErrNotSupported - method is not supported by this LXC version ErrNotSupported = lxcError("method is not supported by this LXC version") // ErrRebootFailed - rebooting the container failed ErrRebootFailed = lxcError("rebooting the container failed") // ErrRemoveDeviceNodeFailed - removing device from container failed ErrRemoveDeviceNodeFailed = lxcError("removing device from container failed") // ErrRenameFailed - renaming the container failed ErrRenameFailed = lxcError("renaming the container failed") // ErrRestoreFailed - restore failed ErrRestoreFailed = lxcError("restore failed") // ErrRestoreSnapshotFailed - restoring the container failed ErrRestoreSnapshotFailed = lxcError("restoring the container failed") // ErrSaveConfigFailed - saving config file for the container failed ErrSaveConfigFailed = lxcError("saving config file for the container failed") // ErrSettingCgroupItemFailed - setting cgroup item for the container failed ErrSettingCgroupItemFailed = lxcError("setting cgroup item for the container failed") // ErrSettingConfigItemFailed - setting config item for the container failed ErrSettingConfigItemFailed = lxcError("setting config item for the container failed") // ErrSettingConfigPathFailed - setting config file for the container failed ErrSettingConfigPathFailed = lxcError("setting config file for the container failed") // ErrSettingKMemoryLimitFailed - setting kernel memory limit for the container failed ErrSettingKMemoryLimitFailed = lxcError("setting kernel memory limit for the container failed") // ErrSettingMemoryLimitFailed - setting memory limit for the container failed ErrSettingMemoryLimitFailed = lxcError("setting memory limit for the container failed") // ErrSettingMemorySwapLimitFailed - setting memory+swap limit for the container failed ErrSettingMemorySwapLimitFailed = lxcError("setting memory+swap limit for the container failed") // ErrSettingSoftMemoryLimitFailed - setting soft memory limit for the container failed ErrSettingSoftMemoryLimitFailed = lxcError("setting soft memory limit for the container failed") // ErrShutdownFailed - shutting down the container failed ErrShutdownFailed = lxcError("shutting down the container failed") // ErrSoftMemLimit - your kernel does not support cgroup memory controller ErrSoftMemLimit = lxcError("your kernel does not support cgroup memory controller") // ErrStartFailed - starting the container failed ErrStartFailed = lxcError("starting the container failed") // ErrStopFailed - stopping the container failed ErrStopFailed = lxcError("stopping the container failed") // ErrTemplateNotAllowed - unprivileged users only allowed to use "download" template ErrTemplateNotAllowed = lxcError("unprivileged users only allowed to use \"download\" template") // ErrUnfreezeFailed - unfreezing the container failed ErrUnfreezeFailed = lxcError("unfreezing the container failed") // ErrUnknownBackendStore - unknown backend type ErrUnknownBackendStore = lxcError("unknown backend type") // ErrReleaseFailed - releasing the container failed ErrReleaseFailed = lxcError("releasing the container failed") ) type lxcError string func (e lxcError) Error() string { return string(e) } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/000077500000000000000000000000001463242402700224355ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/Makefile000066400000000000000000000014701463242402700240770ustar00rootroot00000000000000NO_COLOR=\033[0m OK_COLOR=\033[0;32m ALL_GO_FILES = $(wildcard */*.go) ALL_BIN_FILES = $(patsubst %.go,%,$(ALL_GO_FILES)) all: $(ALL_GO_FILES) define PROGRAM_template $(1): vet @echo "$(OK_COLOR)==> Building $(1) $(NO_COLOR)" @cd $(dir $1); go build endef $(foreach prog,$(ALL_GO_FILES),$(eval $(call PROGRAM_template,$(prog)))) clean: @$(foreach file,$(ALL_BIN_FILES),rm -f $(file);) format: @echo "$(OK_COLOR)==> Formatting the code $(NO_COLOR)" @$(foreach file,$(ALL_GO_FILES),gofmt -s -w $(file);) @$(foreach file,$(ALL_GO_FILES),goimports -w $(file);) vet: @echo "$(OK_COLOR)==> Running go vet $(NO_COLOR)" @$(foreach file,$(ALL_GO_FILES),go vet -all $(file);) lint: @echo "$(OK_COLOR)==> Running golint $(NO_COLOR)" @$(foreach file,$(ALL_GO_FILES),golint $(file);) .PHONY: all clean format vet lint golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/attach/000077500000000000000000000000001463242402700237015ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/attach/attach.go000066400000000000000000000025401463242402700254750ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/attach_with_pipes/000077500000000000000000000000001463242402700261345ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/attach_with_pipes/attach_with_pipes.go000066400000000000000000000043231463242402700321640ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "io" "log" "os" "sync" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/checkpoint/000077500000000000000000000000001463242402700245645ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/checkpoint/checkpoint.go000066400000000000000000000022421463242402700272420ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/clone/000077500000000000000000000000001463242402700235355ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/clone/clone.go000066400000000000000000000021321463242402700251620ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/concurrent_create/000077500000000000000000000000001463242402700261425ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/concurrent_create/concurrent_create.go000066400000000000000000000020171463242402700321760ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/concurrent_destroy/000077500000000000000000000000001463242402700263705ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/concurrent_destroy/concurrent_destroy.go000066400000000000000000000017441463242402700326600ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/concurrent_shutdown/000077500000000000000000000000001463242402700265525ustar00rootroot00000000000000concurrent_shutdown.go000066400000000000000000000020531463242402700331370ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/concurrent_shutdown// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "time" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/concurrent_start/000077500000000000000000000000001463242402700260345ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/concurrent_start/concurrent_start.go000066400000000000000000000017401463242402700317640ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/concurrent_stop/000077500000000000000000000000001463242402700256645ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/concurrent_stop/concurrent_stop.go000066400000000000000000000017361463242402700314510ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "runtime" "strconv" "sync" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/concurrent_stress/000077500000000000000000000000001463242402700262225ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/concurrent_stress/concurrent_stress.go000066400000000000000000000051611463242402700323410ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "io/ioutil" "log" "runtime" "strconv" "sync" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/config/000077500000000000000000000000001463242402700237025ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/config/config.go000066400000000000000000000017441463242402700255040ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() //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+git20240606.27b3d11/examples/console/000077500000000000000000000000001463242402700240775ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/console/console.go000066400000000000000000000014571463242402700260770ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/create/000077500000000000000000000000001463242402700237005ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/create/create.go000066400000000000000000000043771463242402700255050ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) var ( lxcpath string template string distro string release string arch string name string verbose bool flush bool validation bool fssize string bdevtype string ) 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.StringVar(&bdevtype, "bdev", "dir", "backing store type") flag.StringVar(&fssize, "fssize", "", "backing store size") // TODO support more flags for zfs, lvm, or rbd flag.Parse() } func main() { c, err := lxc.NewContainer(name, lxcpath) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } defer c.Release() log.Printf("Creating container...\n") if verbose { c.SetVerbosity(lxc.Verbose) } var backend lxc.BackendStore if err := (&backend).Set(bdevtype); err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } var bdevSize lxc.ByteSize if fssize != "" { var err error bdevSize, err = lxc.ParseBytes(fssize) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } } options := lxc.TemplateOptions{ Template: template, Distro: distro, Release: release, Arch: arch, FlushCache: flush, DisableGPGValidation: validation, Backend: backend, BackendSpecs: &lxc.BackendStoreSpecs{ FSSize: uint64(bdevSize), }, } c.SetLogFile("log") c.SetLogLevel(lxc.DEBUG) if err := c.Create(options); err != nil { log.Printf("ERROR: %s\n", err.Error()) } } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/create_snapshot/000077500000000000000000000000001463242402700256175ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/create_snapshot/create_snapshot.go000066400000000000000000000014311463242402700313270ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/destroy/000077500000000000000000000000001463242402700241265ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/destroy/destroy.go000066400000000000000000000014121463242402700261440ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/destroy_snapshots/000077500000000000000000000000001463242402700262305ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/destroy_snapshots/destroy_snapshots.go000066400000000000000000000012251463242402700323520ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "log" "github.com/lxc/go-lxc" ) 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()) } } c[i].Release() } } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/device_add_remove/000077500000000000000000000000001463242402700260615ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/device_add_remove/device_add_remove.go000066400000000000000000000016351463242402700320410ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "time" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/execute/000077500000000000000000000000001463242402700240775ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/execute/execute.go000066400000000000000000000015061463242402700260720ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/freeze/000077500000000000000000000000001463242402700237155ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/freeze/freeze.go000066400000000000000000000014671463242402700255340ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "time" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/interfaces/000077500000000000000000000000001463242402700245605ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/interfaces/interfaces.go000066400000000000000000000015441463242402700272360ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/ipaddress/000077500000000000000000000000001463242402700244135ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/ipaddress/ipaddress.go000066400000000000000000000027361463242402700267300ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/limit/000077500000000000000000000000001463242402700235535ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/limit/limit.go000066400000000000000000000020551463242402700252220ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/list/000077500000000000000000000000001463242402700234105ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/list/list.go000066400000000000000000000017401463242402700247140ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) c[i].Release() } 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()) c[i].Release() } 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()) c[i].Release() } } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/list_keys/000077500000000000000000000000001463242402700244435ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/list_keys/list_keys.go000066400000000000000000000013441463242402700270020ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() for _, k := range c.ConfigKeys() { log.Printf("%s -> %s", k, c.ConfigItem(k)) } } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/list_snapshots/000077500000000000000000000000001463242402700255125ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/list_snapshots/list_snapshots.go000066400000000000000000000012761463242402700311240ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "log" "github.com/lxc/go-lxc" ) 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() } c[i].Release() } } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/reboot/000077500000000000000000000000001463242402700237275ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/reboot/reboot.go000066400000000000000000000014141463242402700255500ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/rename/000077500000000000000000000000001463242402700237045ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/rename/rename.go000066400000000000000000000015701463242402700255050ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/restore_snapshot/000077500000000000000000000000001463242402700260375ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/restore_snapshot/restore_snapshot.go000066400000000000000000000015301463242402700317670ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/shutdown/000077500000000000000000000000001463242402700243105ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/shutdown/shutdown.go000066400000000000000000000015211463242402700265110ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "time" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/start/000077500000000000000000000000001463242402700235725ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/start/start.go000066400000000000000000000017741463242402700252670ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "time" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/stats/000077500000000000000000000000001463242402700235735ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/stats/stats.go000066400000000000000000000045101463242402700252600ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() // 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+git20240606.27b3d11/examples/stop/000077500000000000000000000000001463242402700234225ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/stop/stop.go000066400000000000000000000015131463242402700247360ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/examples/unfreeze/000077500000000000000000000000001463242402700242605ustar00rootroot00000000000000golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/examples/unfreeze/unfreeze.go000066400000000000000000000014741463242402700264400ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package main import ( "flag" "log" "time" "github.com/lxc/go-lxc" ) 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()) } defer c.Release() 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+git20240606.27b3d11/go.mod000066400000000000000000000001101463242402700217150ustar00rootroot00000000000000module github.com/lxc/go-lxc go 1.20 require golang.org/x/sys v0.21.0 golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/go.sum000066400000000000000000000002311463242402700217460ustar00rootroot00000000000000golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/linking_dynamic.go000066400000000000000000000005221463242402700243040ustar00rootroot00000000000000// 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. //go:build linux && cgo && !static_build // +build linux,cgo,!static_build package lxc // #cgo CFLAGS: -std=gnu11 -Wvla -Werror // #cgo pkg-config: lxc import "C" golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/linking_static.go000066400000000000000000000005741463242402700241560ustar00rootroot00000000000000// 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. //go:build linux && cgo && static_build // +build linux,cgo,static_build package lxc // #cgo CFLAGS: -std=gnu11 -Wvla -Werror // #cgo pkg-config: --static lxc libcrypto // #cgo LDFLAGS: -static import "C" golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/lxc-binding.c000066400000000000000000000325361463242402700231720ustar00rootroot00000000000000// 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 #include #include "lxc-binding.h" #ifndef LXC_DEVEL #define LXC_DEVEL 0 #endif #define ret_errno(__errno__) \ ({ \ errno = (__errno__); \ -(__errno__); \ }) 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); } int go_lxc_init_pidfd(struct lxc_container *c) { #if VERSION_AT_LEAST(4, 0, 0) return c->init_pidfd(c); #else return ret_errno(ENOSYS); #endif } int go_lxc_seccomp_notify_fd(struct lxc_container *c) { #if VERSION_AT_LEAST(4, 0, 0) return c->seccomp_notify_fd(c); #else return ret_errno(ENOSYS); #endif } int go_lxc_seccomp_notify_fd_active(struct lxc_container *c) { #if VERSION_AT_LEAST(4, 0, 5) return c->seccomp_notify_fd_active(c); #else return ret_errno(ENOSYS); #endif } int go_lxc_set_timeout(struct lxc_container *c, int timeout) { #if VERSION_AT_LEAST(5, 0, 4) if (!c->set_timeout(c, timeout)) return ret_errno(EINVAL); return 0; #else return ret_errno(ENOSYS); #endif } int go_lxc_devpts_fd(struct lxc_container *c) { #if VERSION_AT_LEAST(4, 0, 5) return c->devpts_fd(c); #else return ret_errno(ENOSYS); #endif } 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, struct bdev_specs *specs, int flags, char * const argv[]) { if (strncmp(t, "none", strlen(t)) == 0) { return c->create(c, NULL, bdevtype, specs, !!(flags & LXC_CREATE_QUIET), argv); } return c->create(c, t, bdevtype, specs, !!(flags & LXC_CREATE_QUIET), argv); } bool go_lxc_start(struct lxc_container *c, int useinit, char * const argv[]) { return c->start(c, useinit, argv); } bool go_lxc_stop(struct lxc_container *c) { return c->stop(c); } bool go_lxc_reboot(struct lxc_container *c) { return c->reboot(c); } bool go_lxc_shutdown(struct lxc_container *c, int timeout) { return c->shutdown(c, timeout); } char* go_lxc_config_file_name(struct lxc_container *c) { return c->config_file_name(c); } bool go_lxc_destroy(struct lxc_container *c) { return c->destroy(c); } bool go_lxc_destroy_with_snapshots(struct lxc_container *c) { #if VERSION_AT_LEAST(1, 1, 0) return c->destroy_with_snapshots(c); #else return false; #endif } bool go_lxc_wait(struct lxc_container *c, const char *state, int timeout) { return c->wait(c, state, timeout); } char *go_lxc_get_config_item(struct lxc_container *c, const char *key) { char *value = NULL; int len = c->get_config_item(c, key, NULL, 0); if (len <= 0) return NULL; again: value = (char *)malloc(sizeof(char) * len + 1); if (value == NULL) goto again; if (c->get_config_item(c, key, value, len + 1) != len) { free(value); return NULL; } return value; } bool go_lxc_set_config_item(struct lxc_container *c, const char *key, const char *value) { return c->set_config_item(c, key, value); } void go_lxc_clear_config(struct lxc_container *c) { c->clear_config(c); } bool go_lxc_clear_config_item(struct lxc_container *c, const char *key) { return c->clear_config_item(c, key); } char* go_lxc_get_running_config_item(struct lxc_container *c, const char *key) { return c->get_running_config_item(c, key); } char *go_lxc_get_keys(struct lxc_container *c, const char *key) { char *value = NULL; int len = c->get_keys(c, key, NULL, 0); if (len <= 0) return NULL; again: value = (char *)malloc(sizeof(char) * len + 1); if (value == NULL) goto again; if (c->get_keys(c, key, value, len + 1) != len) { free(value); return NULL; } return value; } char *go_lxc_get_cgroup_item(struct lxc_container *c, const char *key) { char *value = NULL; int len = c->get_cgroup_item(c, key, NULL, 0); if (len <= 0) return NULL; again: value = (char *)malloc(sizeof(char) * len + 1); if (value == NULL) goto again; if (c->get_cgroup_item(c, key, value, len + 1) != len) { free(value); return NULL; } return value; } bool go_lxc_set_cgroup_item(struct lxc_container *c, const char *key, const char *value) { return c->set_cgroup_item(c, key, value); } const char* go_lxc_get_config_path(struct lxc_container *c) { return c->get_config_path(c); } bool go_lxc_set_config_path(struct lxc_container *c, const char *path) { return c->set_config_path(c, path); } bool go_lxc_load_config(struct lxc_container *c, const char *alt_file) { return c->load_config(c, alt_file); } bool go_lxc_save_config(struct lxc_container *c, const char *alt_file) { return c->save_config(c, alt_file); } bool go_lxc_clone(struct lxc_container *c, const char *newname, const char *lxcpath, int flags, const char *bdevtype) { struct lxc_container *c2 = c->clone(c, newname, lxcpath, flags, bdevtype, NULL, 0, NULL); if (c2 == NULL) { return false; } lxc_container_put(c2); return true; } int go_lxc_console_getfd(struct lxc_container *c, int ttynum) { int mainfd; int ret = 0; ret = c->console_getfd(c, &ttynum, &mainfd); if (ret < 0) return ret; return mainfd; } 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, lxc_groups_t groups, 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 attach_flags) { int ret; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.attach_flags = attach_flags; 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; #if VERSION_AT_LEAST(4, 0, 9) if ( groups.size > 0 ) { attach_options.groups = groups; attach_options.attach_flags &= LXC_ATTACH_SETGROUPS; } #endif attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; command.program = (char *)argv[0]; command.argv = (char **)argv; ret = c->attach(c, lxc_attach_run_command, &command, &attach_options, attached_pid); if (ret < 0) return ret; return 0; } int go_lxc_attach(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, lxc_groups_t groups, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, int attach_flags) { int ret; pid_t pid; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.attach_flags = attach_flags; 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; #if VERSION_AT_LEAST(4, 0, 9) if ( groups.size > 0 ) { attach_options.groups = groups; attach_options.attach_flags &= LXC_ATTACH_SETGROUPS; } #endif 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(c, lxc_attach_run_shell, NULL, &attach_options, &pid); if (ret < 0) return ret; ret = wait_for_pid_status(pid); if (ret < 0) return ret; if (WIFEXITED(ret)) return WEXITSTATUS(ret); return ret; } int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, lxc_groups_t groups, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[], int attach_flags) { int ret; lxc_attach_options_t attach_options = LXC_ATTACH_OPTIONS_DEFAULT; attach_options.attach_flags = attach_flags; 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; #if VERSION_AT_LEAST(4, 0, 9) if ( groups.size > 0 ) { attach_options.groups = groups; attach_options.attach_flags &= LXC_ATTACH_SETGROUPS; } #endif attach_options.stdin_fd = stdinfd; attach_options.stdout_fd = stdoutfd; attach_options.stderr_fd = stderrfd; attach_options.initial_cwd = initial_cwd; attach_options.extra_env_vars = extra_env_vars; attach_options.extra_keep_env = extra_keep_env; ret = c->attach_run_wait(c, &attach_options, argv[0], argv); if (WIFEXITED(ret) && WEXITSTATUS(ret) == 255) return -1; return ret; } bool go_lxc_may_control(struct lxc_container *c) { return c->may_control(c); } int go_lxc_snapshot(struct lxc_container *c) { return c->snapshot(c, NULL); } int go_lxc_snapshot_list(struct lxc_container *c, struct lxc_snapshot **ret) { return c->snapshot_list(c, ret); } bool go_lxc_snapshot_restore(struct lxc_container *c, const char *snapname, const char *newname) { return c->snapshot_restore(c, snapname, newname); } bool go_lxc_snapshot_destroy(struct lxc_container *c, const char *snapname) { return c->snapshot_destroy(c, snapname); } bool go_lxc_snapshot_destroy_all(struct lxc_container *c) { #if VERSION_AT_LEAST(1, 1, 0) return c->snapshot_destroy_all(c); #else return false; #endif } bool go_lxc_add_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { return c->add_device_node(c, src_path, dest_path); } bool go_lxc_remove_device_node(struct lxc_container *c, const char *src_path, const char *dest_path) { return c->remove_device_node(c, src_path, dest_path); } bool go_lxc_rename(struct lxc_container *c, const char *newname) { return c->rename(c, newname); } bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose) { #if VERSION_AT_LEAST(1, 1, 0) return c->checkpoint(c, directory, stop, verbose); #else return false; #endif } bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose) { #if VERSION_AT_LEAST(1, 1, 0) return c->restore(c, directory, verbose); #else return false; #endif } int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras) { #if VERSION_AT_LEAST(3, 0, 0) opts->features_to_check = extras->features_to_check; #endif #if VERSION_AT_LEAST(2, 0, 4) opts->action_script = extras->action_script; opts->ghost_limit = extras->ghost_limit; #endif #if VERSION_AT_LEAST(2, 0, 1) opts->preserves_inodes = extras->preserves_inodes; #endif #if VERSION_AT_LEAST(2, 0, 0) return c->migrate(c, cmd, opts, sizeof(*opts)); #else return -EINVAL; #endif } bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { #if VERSION_AT_LEAST(1, 1, 0) return c->attach_interface(c, dev, dst_dev); #else return false; #endif } bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev) { #if VERSION_AT_LEAST(1, 1, 0) return c->detach_interface(c, dev, dst_dev); #else return false; #endif } bool go_lxc_config_item_is_supported(const char *key) { #if VERSION_AT_LEAST(2, 1, 0) return lxc_config_item_is_supported(key); #else return false; #endif } int go_lxc_error_num(struct lxc_container *c) { return c->error_num; } int go_lxc_console_log(struct lxc_container *c, struct lxc_console_log *log) { #if VERSION_AT_LEAST(3, 0, 0) return c->console_log(c, log); #else return false; #endif } bool go_lxc_has_api_extension(const char *extension) { #if VERSION_AT_LEAST(3, 1, 0) return lxc_has_api_extension(extension); #else return false; #endif } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/lxc-binding.go000066400000000000000000000177311463242402700233550ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package lxc // #include // #include // #include "lxc-binding.h" // #ifndef LXC_DEVEL // #define LXC_DEVEL 0 // #endif import "C" import ( "fmt" "strconv" "strings" "unsafe" ) // NewContainer returns a new container struct. // Caller needs to call Release() on the returned container to release its resources. 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} return c, nil } // Acquire increments the reference counter of the container object. func Acquire(c *Container) bool { c.mu.RLock() defer c.mu.RUnlock() return C.lxc_container_get(c.container) == 1 } // Release decrements the reference counter of the container object. func Release(c *Container) bool { return c.Release() == nil } // 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. // Caller needs to call Release() on the returned containers to release resources. 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. // Caller needs to call Release() on the returned containers to release resources. 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. // Caller needs to call Release() on the returned containers to release resources. func ActiveContainers(lxcpath ...string) []*Container { var containers []*Container for _, v := range ActiveContainerNames(lxcpath...) { if container, err := NewContainer(v, lxcpath...); err == nil { containers = append(containers, container) } } return containers } // VersionNumber returns the LXC version. func VersionNumber() (major int, minor int) { major = C.LXC_VERSION_MAJOR minor = C.LXC_VERSION_MINOR return } // VersionAtLeast returns true when the tested version >= current version. func VersionAtLeast(major int, minor int, micro int) bool { if C.LXC_DEVEL == 1 { return true } if major > C.LXC_VERSION_MAJOR { return false } if major == C.LXC_VERSION_MAJOR && minor > C.LXC_VERSION_MINOR { return false } if major == C.LXC_VERSION_MAJOR && minor == C.LXC_VERSION_MINOR && micro > C.LXC_VERSION_MICRO { return false } return true } // IsSupportedConfigItem returns true if the key belongs to a supported config item. func IsSupportedConfigItem(key string) bool { configItem := C.CString(key) defer C.free(unsafe.Pointer(configItem)) return bool(C.go_lxc_config_item_is_supported(configItem)) } // RuntimeLiblxcVersionAtLeast checks if the system's liblxc matches the // provided version requirement func RuntimeLiblxcVersionAtLeast(version string, major int, minor int, micro int) bool { // Strip git versioning from pre-release snapshots. version = strings.Split(version, "~")[0] // Convert devel indicator into a valid version. version = strings.Replace(version, " (devel)", "-devel", 1) // Split the version into its major, minor and micro parts. parts := strings.Split(version, ".") partsLen := len(parts) if partsLen == 0 { return false } // If the last part includes -devel, assume everything is supported. develParts := strings.Split(parts[partsLen-1], "-") if len(develParts) == 2 && develParts[1] == "devel" { return true } // Actually parse and compare the version string now. maj := -1 min := -1 mic := -1 for i, v := range parts { if i > 2 { break } num, err := strconv.Atoi(v) if err != nil { return false } switch i { case 0: maj = num case 1: min = num case 2: mic = num } } /* Major version is greater. */ if maj > major { return true } if maj < major { return false } /* Minor number is greater.*/ if min > minor { return true } if min < minor { return false } /* Patch number is greater. */ if mic > micro { return true } if mic < micro { return false } return true } // HasApiExtension returns true if the extension is supported. // Deprecated: Please use HasAPIExtension instead. func HasApiExtension(extension string) bool { return HasAPIExtension(extension) } // HasAPIExtension returns true if the extension is supported. func HasAPIExtension(extension string) bool { if RuntimeLiblxcVersionAtLeast(Version(), 3, 1, 0) { apiExtension := C.CString(extension) defer C.free(unsafe.Pointer(apiExtension)) return bool(C.go_lxc_has_api_extension(apiExtension)) } return false } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/lxc-binding.h000066400000000000000000000153001463242402700231650ustar00rootroot00000000000000// 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. #include #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, struct bdev_specs *specs, 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); #if !VERSION_AT_LEAST(4, 0, 9) && !defined(LXC_ATTACH_SETGROUPS) typedef struct lxc_groups_t { size_t size; gid_t *list; } lxc_groups_t; # endif extern int go_lxc_attach_run_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, lxc_groups_t groups, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, const char * const argv[], int attach_flags); extern int go_lxc_attach(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, lxc_groups_t groups, int stdinfd, int stdoutfd, int stderrfd, char *initial_cwd, char **extra_env_vars, char **extra_keep_env, int attach_flags); extern int go_lxc_attach_no_wait(struct lxc_container *c, bool clear_env, int namespaces, long personality, uid_t uid, gid_t gid, lxc_groups_t groups, 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 attach_flags); 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 int go_lxc_init_pidfd(struct lxc_container *c); extern int go_lxc_devpts_fd(struct lxc_container *c); extern int go_lxc_seccomp_notify_fd(struct lxc_container *c); extern int go_lxc_seccomp_notify_fd_active(struct lxc_container *c); extern int go_lxc_set_timeout(struct lxc_container *c, int timeout); extern bool go_lxc_checkpoint(struct lxc_container *c, char *directory, bool stop, bool verbose); extern bool go_lxc_restore(struct lxc_container *c, char *directory, bool verbose); extern bool go_lxc_config_item_is_supported(const char *key); extern bool go_lxc_has_api_extension(const char *extension); /* n.b. that we're just adding the fields here to shorten the definition * of go_lxc_migrate; in the case where we don't have the ->migrate API call, * we don't want to have to pass all the arguments in to let conditional * compilation handle things, but the call will still fail */ #if !VERSION_AT_LEAST(2, 0, 0) struct migrate_opts { char *directory; bool verbose; bool stop; char *predump_dir; }; #endif /* This is a struct that we can add "extra" (i.e. options added after 2.0.0) * migrate options to, so that we don't have to have a massive function * signature when the list of options grows. */ struct extra_migrate_opts { bool preserves_inodes; char *action_script; uint64_t ghost_limit; uint64_t features_to_check; }; int go_lxc_migrate(struct lxc_container *c, unsigned int cmd, struct migrate_opts *opts, struct extra_migrate_opts *extras); extern bool go_lxc_attach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); extern bool go_lxc_detach_interface(struct lxc_container *c, const char *dev, const char *dst_dev); #if !VERSION_AT_LEAST(3, 0, 0) struct lxc_console_log { bool clear; bool read; uint64_t *read_max; char *data; }; #endif extern int go_lxc_console_log(struct lxc_container *c, struct lxc_console_log *log); extern int go_lxc_error_num(struct lxc_container *c); golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/lxc_test.go000066400000000000000000001017031463242402700227750ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package lxc import ( "fmt" "io/ioutil" "math/rand" "net" "os" "runtime" "strconv" "strings" "sync" "syscall" "testing" "time" ) const ( DefaultContainerName = "lorem" DefaultSnapshotName = "snap0" DefaultContainerRestoreName = "ipsum" DefaultContainerCloneName = "consectetur" DefaultContainerCloneOverlayName = "adipiscing" ) func exists(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 ipv6() bool { lxcbr0, err := net.InterfaceByName("lxcbr0") if err != nil { return false } addresses, err := lxcbr0.Addrs() if err != nil { return false } // https://github.com/asaskevich/govalidator/blob/master/validator.go#L621 for _, v := range addresses { if ipnet, ok := v.(*net.IPNet); ok && strings.Count(v.String(), ":") >= 2 && !ipnet.IP.IsLinkLocalUnicast() { return true } } return false } func template() TemplateOptions { return TemplateOptions{ Template: "download", Distro: "alpine", Release: "edge", Arch: "amd64", } } func ContainerName() string { if unprivileged() { return fmt.Sprintf("%s-unprivileged", DefaultContainerName) } return DefaultContainerName } func ContainerRestoreName() string { if unprivileged() { return fmt.Sprintf("%s-unprivileged", DefaultContainerRestoreName) } return DefaultContainerRestoreName } func ContainerCloneName() string { if unprivileged() { return fmt.Sprintf("%s-unprivileged", DefaultContainerCloneName) } return DefaultContainerCloneName } func ContainerCloneOverlayName() string { if unprivileged() { return fmt.Sprintf("%s-unprivileged", DefaultContainerCloneOverlayName) } return DefaultContainerCloneOverlayName } 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()) } defer c.Release() 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()) } defer c.Release() Acquire(c) Release(c) } func TestConcurrentDefined_Negative(t *testing.T) { t.Skip("Skipping concurrent tests for now") 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()) } defer c.Release() // sleep for a while to simulate some 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()) } defer c.Release() if c.Defined() { t.Errorf("Defined_Negative failed...") } } func TestSetVerbosity(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() c.SetVerbosity(Quiet) } func TestCreate(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() c.SetVerbosity(Verbose) if err := c.Create(template()); err != nil { t.Errorf(err.Error()) } } func TestClone(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if err = c.Clone(ContainerCloneName(), DefaultCloneOptions); err != nil { t.Errorf(err.Error()) } } func TestCloneUsingOverlayfs(t *testing.T) { if !(supported("overlayfs") || supported("overlay")) { t.Skip("skipping test as overlayfs support is missing.") } c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() err = c.Clone(ContainerCloneOverlayName(), CloneOptions{ Backend: Overlayfs, 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()) } defer c.Release() 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()) } defer c.Release() for i := 0; i < 3; i++ { if _, err := c.CreateSnapshot(); err != nil { t.Errorf(err.Error()) } } } func TestRestoreSnapshot(t *testing.T) { if os.Getenv("GITHUB_ACTION") != "" { t.Skip("Test broken on Github") } c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() snapshot := Snapshot{Name: DefaultSnapshotName} if err := c.RestoreSnapshot(snapshot, ContainerRestoreName()); err != nil { t.Errorf(err.Error()) } } func TestConcurrentCreate(t *testing.T) { t.Skip("Skipping concurrent tests for now") defer runtime.GOMAXPROCS(runtime.NumCPU()) var wg sync.WaitGroup options := template() 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()) } defer c.Release() // sleep for a while to simulate some 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()) } defer c.Release() if _, err := c.Snapshots(); err != nil { t.Errorf(err.Error()) } } func TestConcurrentStart(t *testing.T) { t.Skip("Skipping concurrent tests for now") defer runtime.GOMAXPROCS(runtime.NumCPU()) 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()) } defer c.Release() 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()) } defer c.Release() if c.ConfigFileName() == "" { t.Errorf("ConfigFileName failed...") } } func TestDefined_Positive(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if !c.Defined() { t.Errorf("Defined_Positive failed...") } } func TestConcurrentDefined_Positive(t *testing.T) { t.Skip("Skipping concurrent tests for now") 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()) } defer c.Release() // sleep for a while to simulate some 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()) } defer c.Release() if c.InitPid() != -1 { t.Errorf("InitPid failed...") } } func TestStart(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() log := fmt.Sprintf("/tmp/%s", ContainerName()) if err := c.SetLogFile(log); err != nil { t.Errorf("SetLogFile failed...") } 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...") b, err := ioutil.ReadFile(log) if err != nil { t.Errorf("Reading %s file failed...", log) } t.Logf("%s\n", b) } } func TestWaitIPAddresses(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() 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()) } defer c.Release() if !c.Controllable() { t.Errorf("Controlling 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() if c.InitPid() == -1 { t.Errorf("InitPid failed...") } } func TestName(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if c.Name() != ContainerName() { t.Errorf("Name failed...") } } func TestFreeze(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() if c.ConfigItem("lxc.uts.name")[0] != ContainerName() { t.Errorf("ConfigItem failed...") } } func TestSetConfigItem(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if err := c.SetConfigItem("lxc.uts.name", ContainerName()); err != nil { t.Errorf(err.Error()) } if c.ConfigItem("lxc.uts.name")[0] != ContainerName() { t.Errorf("ConfigItem failed...") } } func TestRunningConfigItem(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() 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()) } defer c.Release() maxMem := c.CgroupItem("memory.max_usage_in_bytes")[0] currentMem := c.CgroupItem("memory.limit_in_bytes")[0] if maxMem == "" && currentMem == "" { // Cgroup2 handling. maxMem := c.CgroupItem("memory.peak")[0] currentMem := c.CgroupItem("memory.max")[0] if err := c.SetCgroupItem("memory.max", maxMem); err != nil { t.Errorf(err.Error()) } newMem := c.CgroupItem("memory.max")[0] if newMem == currentMem { t.Errorf("SetCgroupItem failed...") } } else { // Cgroup1 handling. 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() if _, err := c.MemoryUsage(); err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } } func TestKernelMemoryUsage(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if _, err := c.KernelMemoryUsage(); err != nil { if err == ErrKMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } } func TestMemorySwapUsage(t *testing.T) { if !exists("/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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() if _, err := c.MemoryLimit(); err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } } func TestSoftMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if _, err := c.SoftMemoryLimit(); err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } } func TestKernelMemoryLimit(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if _, err := c.KernelMemoryLimit(); err != nil { if err == ErrKMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } } func TestMemorySwapLimit(t *testing.T) { if !exists("/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()) } defer c.Release() 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()) } defer c.Release() oldMemLimit, err := c.MemoryLimit() if err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } if err := c.SetMemoryLimit(oldMemLimit * 4); err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } newMemLimit, err := c.MemoryLimit() if err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } 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()) } defer c.Release() oldMemLimit, err := c.MemoryLimit() if err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } if err := c.SetSoftMemoryLimit(oldMemLimit * 4); err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } t.Errorf(err.Error()) } newMemLimit, err := c.SoftMemoryLimit() if err != nil { if err == ErrMemLimit { t.Skip("Skipping test due to kernel support (maybe cgroup2?)") return } 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()) } defer c.Release() 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 !exists("/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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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() } defer c.Release() if err := c.Create(template()); 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() options := DefaultAttachOptions options.ClearEnv = true options.EnvToKeep = []string{"USER"} args := []string{"/bin/sh", "-c", fmt.Sprintf("test $USER = '%s'", os.Getenv("USER"))} 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() if _, err := c.IPv4Address("lo"); err != nil { t.Errorf(err.Error()) } } func TestIPv46ddress(t *testing.T) { if !ipv6() { t.Skip("skipping test since lxc bridge does not have ipv6 address") } c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() 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.") } if !exists("/dev/network_latency") { t.Skip("skipping the test as it requires/dev/network_latency") } c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() 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.") } if !exists("/dev/network_latency") { t.Skip("skipping the test as it requires/dev/network_latency") } c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if err := c.RemoveDeviceNode("/dev/network_latency"); err != nil { t.Errorf(err.Error()) } } func TestIPv4Addresses(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() // Wait for IP configuration. time.Sleep(5 * time.Second) if _, err := c.IPv4Addresses(); err != nil { t.Errorf(err.Error()) } } func TestIPv6Addresses(t *testing.T) { c, err := NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() // Wait for IP configuration. time.Sleep(5 * time.Second) 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()) } defer c.Release() if err := c.Reboot(); err != nil { t.Errorf("Rebooting the container failed...") } c.Wait(RUNNING, 30*time.Second) } func TestConcurrentShutdown(t *testing.T) { t.Skip("Skipping concurrent tests for now") defer runtime.GOMAXPROCS(runtime.NumCPU()) 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() 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()) } defer c.Release() snapshot := Snapshot{Name: DefaultSnapshotName} 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()) } defer c.Release() 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") || supported("overlay") { c, err := NewContainer(ContainerCloneOverlayName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } c, err := NewContainer(ContainerCloneName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } c, err = NewContainer(ContainerRestoreName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if c.Defined() { if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } c, err = NewContainer(ContainerName()) if err != nil { t.Errorf(err.Error()) } defer c.Release() if err := c.Destroy(); err != nil { t.Errorf(err.Error()) } } func TestConcurrentDestroy(t *testing.T) { t.Skip("Skipping concurrent tests for now") defer runtime.GOMAXPROCS(runtime.NumCPU()) 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()) } defer c.Release() // sleep for a while to simulate some 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...") } } } func TestRuntimeLiblxcVersionAtLeast(t *testing.T) { type args struct { version string major int minor int micro int } tests := []struct { name string args args want bool }{ { name: "Check 5.0.0 is at least 2.1.0 returns true", args: args{ version: "5.0.0", major: 2, minor: 1, micro: 0, }, want: true, }, { name: "Check 5.0.0-devel is at least 2.1.0", args: args{ version: "5.0.0-devel", major: 2, minor: 1, micro: 0, }, want: true, }, { name: "Check 5.0.0~git2209-g5a7b9ce67-0ubuntu1 is at least 2.1.0", args: args{ version: "5.0.0~git2209-g5a7b9ce67-0ubuntu1", major: 2, minor: 1, micro: 0, }, want: true, }, { name: "Check 1.0.0 is not at least 2.1.0 returns true", args: args{ version: "1.0.0", major: 2, minor: 1, micro: 0, }, want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := RuntimeLiblxcVersionAtLeast(tt.args.version, tt.args.major, tt.args.minor, tt.args.micro); got != tt.want { t.Errorf("RuntimeLiblxcVersionAtLeast() = %v, want %v", got, tt.want) } }) } } golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/options.go000066400000000000000000000142771463242402700226540ustar00rootroot00000000000000// 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. //go:build linux && cgo // +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 // Groups specifies the list of additional group ids to run with. Groups []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 // RemountSysProc remounts /sys and /proc for the executed command. // This is required to reflect the container (PID) namespace context // if the command does not attach to the container's mount namespace. RemountSysProc bool // ElevatedPrivileges runs the command with elevated privileges. // The capabilities, cgroup and security module restrictions of the container are not applied. // WARNING: This may leak privileges into the container. ElevatedPrivileges bool } // DefaultAttachOptions is a convenient set of options to be used. var DefaultAttachOptions = AttachOptions{ Namespaces: -1, Arch: -1, Cwd: "/", UID: -1, GID: -1, Groups: nil, ClearEnv: false, Env: nil, EnvToKeep: nil, StdinFd: os.Stdin.Fd(), StdoutFd: os.Stdout.Fd(), StderrFd: os.Stderr.Fd(), RemountSysProc: false, ElevatedPrivileges: false, } // 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 BackendSpecs *BackendStoreSpecs // 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 } // BackendStoreSpecs represents a LXC storage backend. type BackendStoreSpecs struct { FSType string FSSize uint64 Dir *string ZFS struct { Root string } LVM struct { VG, LV, Thinpool string } RBD struct { Name, Pool 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 } // ConsoleLogOptions 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+git20240606.27b3d11/type.go000066400000000000000000000154121463242402700221320ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package lxc // #include import "C" import ( "errors" "fmt" "strconv" "strings" "unicode" ) // 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 "loop" 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 ( // B - byte B = 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) } // Used to convert user input to ByteSize var unitMap = map[string]ByteSize{ "B": B, "BYTE": B, "BYTES": B, "KB": KB, "KILOBYTE": KB, "KILOBYTES": KB, "MB": MB, "MEGABYTE": MB, "MEGABYTES": MB, "GB": GB, "GIGABYTE": GB, "GIGABYTES": GB, "TB": TB, "TERABYTE": TB, "TERABYTES": TB, "PB": PB, "PETABYTE": PB, "PETABYTES": PB, "EB": EB, "EXABYTE": EB, "EXABYTES": EB, } // Inspired from https://github.com/inhies/go-bytesize // ParseBytes parses a byte size string. A byte size string is a number followed by // a unit suffix, such as "1024B" or "1 MB". Valid byte units are "B", "KB", // "MB", "GB", "TB", "PB" and "EB". You can also use the long // format of units, such as "kilobyte" or "kilobytes". func ParseBytes(s string) (ByteSize, error) { // Remove leading and trailing space s = strings.TrimSpace(s) split := make([]string, 0) for i, r := range s { if !unicode.IsDigit(r) { // Split the string by digit and size designator, remove space split = append(split, strings.TrimSpace(string(s[:i]))) split = append(split, strings.TrimSpace(string(s[i:]))) break } } // Check to see if we split successfully if len(split) != 2 { return 0, errors.New("Unrecognized size suffix") } // Check for MB, MEGABYTE, and MEGABYTES unit, ok := unitMap[strings.ToUpper(split[1])] if !ok { return 0, errors.New("Unrecognized size suffix " + split[1]) } value, err := strconv.ParseFloat(split[0], 64) if err != nil { return 0, err } bytesize := ByteSize(value * float64(unit)) return bytesize, nil } // 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 - Intel 32bit X86 Personality = 0x0008 // X86_64 - Intel 64bit X86_64 = 0x0000 ) const ( // MIGRATE_PRE_DUMP - pre-dump live migration phase MIGRATE_PRE_DUMP = 0 // MIGRATE_DUMP - main live migration phase MIGRATE_DUMP = 1 // MIGRATE_RESTORE - post migration phase MIGRATE_RESTORE = 2 // MIGRATE_FEATURE_CHECK - migration feature check MIGRATE_FEATURE_CHECK = 3 ) // CriuFeatures represents a set of CRIU features type CriuFeatures uint64 const ( // FEATURE_MEM_TRACK - memory tracking support FEATURE_MEM_TRACK CriuFeatures = 1 << iota // FEATURE_LAZY_PAGES - lazy pages support FEATURE_LAZY_PAGES ) golang-gopkg-lxc-go-lxc.v2-0.0+git20240606.27b3d11/util.go000066400000000000000000000036721463242402700221330ustar00rootroot00000000000000// 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. //go:build linux && cgo // +build linux,cgo package lxc /* #include #include static char** makeCharArray(size_t size) { // caller checks return value return calloc(size, sizeof(char*)); } static void setArrayString(char **array, char *string, size_t n) { array[n] = string; } static void freeCharArray(char **array, size_t size) { size_t i; for (i = 0; i < size; i++) { free(array[i]); } free(array); } static void freeSnapshotArray(struct lxc_snapshot *s, size_t size) { size_t i; for (i = 0; i < size; i++) { s[i].free(&s[i]); } free(s); } static size_t getArrayLength(char **array) { char **p; size_t size = 0; for (p = (char **)array; *p; p++) { size++; } return size; } */ import "C" import ( "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 } tmpslice := (*[(1 << 29) - 1]*C.char)(unsafe.Pointer(cArgs))[:size:size] result := make([]string, size) for i, s := range tmpslice { result[i] = C.GoString(s) } return result } func freeSnapshots(snapshots *C.struct_lxc_snapshot, size int) { C.freeSnapshotArray(snapshots, C.size_t(size)) }