uvtool-0~bzr99/LICENSE0000644000000000000000000010333012512767613013006 0ustar 00000000000000 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, 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 them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state 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 program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . uvtool-0~bzr99/README0000644000000000000000000000360112512767613012661 0ustar 00000000000000Images are stored as follows: /var/lib/uvtool/libvirt/images is a used as a libvirt volume pool called "uvtool". It is accessed through the libvirt API only. /var/lib/uvtool/libvirt/metadata contains files whose names correspond to the names defined in the "uvtool" libvirt volume pool. Metadata file semantics are as follows: If a metadata file does not exist, and the corresponding volume does not exist, then nothing is known about the volume (that doesn't exist). If a metadata file exists and the corresponding volume also exists, then the volume is known about and can be used. The metadata file is a JSON-formatted file containing the simplestreams key/value pairs associated with the image. If a metadata file does not exist, but the corresponding volume does exist, then the image is gone from the uvtool-simplestreams-libvirt view and cannot be used to create an instance. However, the image may still be in use by existing instances. It will be cleaned up on the next "uvtool-simplestreams-libvirt sync" command but only if it the volume is no longer in use. This is a common case: official "release" images go out of date, since updated images with new updated packages and kernels are continually produced. So the sync logic will drop images for use with new instances, but old instances will continue to use them as their copy-on-write backing volumes. If a metadata file exists, but the corresponding volume does not exist, then this is an error. "uvtool-simplestreams-libvirt sync" will erase the spurious metadata file on its next run. In all cases, a volume is treated as "in use" if an instance exists that uses it: either directly or through another volume as a backing store. These cases correspond to specific XPath searches in the libvirt domain and volume XML object definitions. Any other cases that should be covered need to be specifically added to the volume "in use" detection logic. uvtool-0~bzr99/bin/0000755000000000000000000000000012512767613012551 5ustar 00000000000000uvtool-0~bzr99/debian/0000755000000000000000000000000012512767613013223 5ustar 00000000000000uvtool-0~bzr99/man/0000755000000000000000000000000012512767613012554 5ustar 00000000000000uvtool-0~bzr99/remote-wait.sh0000644000000000000000000000050112512767613014566 0ustar 00000000000000#!/bin/sh set -e # Wait for runlevel 2 (upstart) or 5 (systemd) while :; do runlevel=`runlevel|awk '{print $2}'` [ "$runlevel" = 2 -o "$runlevel" = 5 ] && break sleep $UVTOOL_WAIT_INTERVAL done # Wait for cloud-init's signal while [ ! -e /var/lib/cloud/instance/boot-finished ]; do sleep $UVTOOL_WAIT_INTERVAL; done uvtool-0~bzr99/setup.py0000644000000000000000000000216312512767613013515 0ustar 00000000000000# Copyright (C) 2013 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import distutils.core import glob VERSION = '0.1' distutils.core.setup( name="uvtool", description="Library and tools for using Ubuntu Cloud Images", version=VERSION, author="Robie Basak", license="AGPL3+", packages=['uvtool.libvirt'], scripts=glob.glob('bin/*'), data_files=[ ('/usr/share/uvtool/libvirt', ['template.xml', 'remote-wait.sh']) ], ) uvtool-0~bzr99/template.xml0000644000000000000000000000101212512767613014330 0ustar 00000000000000 hvm uvtool-0~bzr99/uvtool/0000755000000000000000000000000012512767613013331 5ustar 00000000000000uvtool-0~bzr99/bin/uvt-kvm0000755000000000000000000000227512512767613014116 0ustar 00000000000000#!/usr/bin/python # Wrapper around cloud-localds and libvirt # Copyright (C) 2012-3 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # Depends: distro-info, cloud-utils, python-libvirt, python-lxml # also qemu-kvm (precise) or kvm (newer?) # The import subcommand needs: qemu-utils (for qemu-img) from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys import uvtool.libvirt.kvm if __name__ == '__main__': uvtool.libvirt.kvm.main_cli_wrapper(sys.argv[1:]) uvtool-0~bzr99/bin/uvt-simplestreams-libvirt0000644000000000000000000000203412512767613017650 0ustar 00000000000000#!/usr/bin/python # Keep Ubuntu Cloud images synced to a local libvirt storage pool. # Copyright (C) 2013 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # This is written using Python 2 because libvirt bindings were not available # for Python 3 at the time of writing. import uvtool.libvirt.simplestreams if __name__ == '__main__': uvtool.libvirt.simplestreams.main() uvtool-0~bzr99/debian/changelog0000644000000000000000000000033312512767613015074 0ustar 00000000000000uvtool (0~~) UNRELEASED; urgency=low * Template changelog for daily builds. * Replace with distribution changelog for distribution builds. -- Robie Basak Tue, 29 Oct 2013 16:28:04 +0000 uvtool-0~bzr99/debian/compat0000644000000000000000000000000212512767613014421 0ustar 000000000000007 uvtool-0~bzr99/debian/control0000644000000000000000000000330012512767613014622 0ustar 00000000000000Source: uvtool Section: admin Priority: extra Standards-Version: 3.9.4 Maintainer: Ubuntu Developers Build-Depends: debhelper (>= 7), python-all, python-setuptools, python-mock, python-libvirt, python-lxml, python-pyinotify, python-simplestreams, python-yaml X-Python-Version: >= 2.7 Package: uvtool Architecture: all Depends: ${misc:Depends} Recommends: uvtool-libvirt Description: Library and tools for using Ubuntu Cloud images This package provides tools, utilities and wrappers to make it easy to consume Ubuntu Cloud images. It is intended to support different subsystems such as libvirt and lxc. Use this package to pull in all the separate packages for all supported subsystems. This will configure all supported subsystems with sensible defaults. If you do not want this, consider installing the subsystem packages individually, instead. Package: uvtool-libvirt Architecture: all Depends: libvirt-bin, python-libvirt, python-simplestreams, python-lxml, python-pyinotify, python-yaml, distro-info, cloud-image-utils (>= 0.27), qemu-utils, ubuntu-cloudimage-keyring, socat, ${misc:Depends}, ${python:Depends} Recommends: qemu-kvm, cpu-checker Description: Library and tools for using Ubuntu Cloud Images with libvirt This package provides libvirt-specific tools for consuming Ubuntu Cloud images. Since it depends on libvirt-bin, installing this package will also install libvirt which by defaults configures it with a bridge on your system. uvtool-0~bzr99/debian/copyright0000644000000000000000000000104612512767613015157 0ustar 00000000000000Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Contact: Robie Basak Files: * Copyright: 2012-3 Canonical Ltd. License: AGPLv3 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 . Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. . The complete text of the AGPL version 3 can be seen in http://www.gnu.org/licenses/agpl-3.0.html uvtool-0~bzr99/debian/rules0000755000000000000000000000051512512767613014304 0ustar 00000000000000#!/usr/bin/make -f %: dh $@ --with python2 override_dh_auto_build: $(MAKE) -C uvtool/tests/streams dh_auto_build PYTHONPATH=$(CURDIR) python -m unittest uvtool.tests.test_kvm PYTHONPATH=$(CURDIR) python -m unittest uvtool.tests.test_simplestreams override_dh_auto_clean: $(MAKE) -C uvtool/tests/streams clean dh_auto_clean uvtool-0~bzr99/debian/source/0000755000000000000000000000000012512767613014523 5ustar 00000000000000uvtool-0~bzr99/debian/uvtool-libvirt.install0000644000000000000000000000002612512767613017612 0ustar 00000000000000usr/bin/* usr/share/* uvtool-0~bzr99/debian/uvtool-libvirt.manpages0000644000000000000000000000000612512767613017735 0ustar 00000000000000man/* uvtool-0~bzr99/debian/uvtool-libvirt.postinst0000644000000000000000000000337612512767613020042 0ustar 00000000000000#!/bin/sh set -e # libvirtd not running seems to be a common error condition during # configuration. Check for this and give the user a more helpful message than a # mysteriously failed uvtool-libvirt.postinst. configure_diagnostic() { if ! socat UNIX-CONNECT:/var/run/libvirt/libvirt-sock - < /dev/null 2>/dev/null; then echo "libvirtd does not appear to be listening on \"/var/run/libvirt/libvirt-sock\"." >&2 echo "On Ubuntu, libvirtd is managed with the \"libvirt-bin\" upstart job." >&2 echo "Repair libvirtd, then reconfigure uvtool-libvirt with:" echo " sudo apt-get -f install" >&2 fi } define_pool() { if ! virsh -q pool-list --all|grep -q '^\s*uvtool\s'; then # Idempotently create virsh pool tmpfile=`mktemp` echo "uvtool/var/lib/uvtool/libvirt/images0700" > "$tmpfile" if ! virsh -q pool-define "$tmpfile"; then rm -f "$tmpfile" echo "Failed to define libvirt pool 'uvtool'" >&2 exit 1 fi rm -f "$tmpfile" fi } start_pool() { # Idempotently start virsh pool if ! virsh -q pool-list|grep -q '^\s*uvtool\s'; then if ! virsh -q pool-start uvtool; then echo "Failed to start libvirt pool 'uvtool'" >&2 exit 1 fi fi } if [ "$1" = configure ]; then trap configure_diagnostic EXIT mkdir -p /var/lib/uvtool/libvirt/images if [ ! -e /var/lib/uvtool/libvirt/metadata ]; then mkdir -pm775 /var/lib/uvtool/libvirt/metadata chown root.libvirtd /var/lib/uvtool/libvirt/metadata fi # Make sure that libvirtd is ready. This is a workaround for LP: #1228210. socat UNIX-CONNECT:/var/run/libvirt/libvirt-sock,retry=15 - < /dev/null define_pool virsh -q pool-autostart uvtool # this is idempotent start_pool fi #DEBHELPER# uvtool-0~bzr99/debian/uvtool-libvirt.postrm0000644000000000000000000000102112512767613017464 0ustar 00000000000000#!/bin/sh set -e stop_pool() { if virsh -q pool-list|grep -q '^\s*uvtool\s'; then # In the postrm virsh may be gone or deconfigured, so ignore # failures gracefully. virsh -q pool-destroy uvtool || true fi } undefine_pool() { if virsh -q pool-list --all|grep -q '^\s*uvtool\s'; then # In the postrm virsh may be gone or deconfigured, so ignore # failures gracefully. virsh -q pool-undefine uvtool || true fi } if [ "$1" = purge ]; then stop_pool undefine_pool rm -Rf /var/lib/uvtool/libvirt fi #DEBHELPER# uvtool-0~bzr99/debian/uvtool-libvirt.pyinstall0000644000000000000000000000016312512767613020165 0ustar 00000000000000uvtool/__init__.py uvtool/wait.py uvtool/libvirt/__init__.py uvtool/libvirt/kvm.py uvtool/libvirt/simplestreams.py uvtool-0~bzr99/debian/uvtool.postrm0000644000000000000000000000013312512767613016016 0ustar 00000000000000#!/bin/sh set -e if [ "$1" = purge ]; then rmdir /var/lib/uvtool || true fi #DEBHELPER# uvtool-0~bzr99/debian/source/format0000644000000000000000000000001412512767613015731 0ustar 000000000000003.0 (quilt) uvtool-0~bzr99/man/uvt-kvm.10000644000000000000000000004052612512767613014256 0ustar 00000000000000.TH uvt\-kvm 1 "2014-03-10" uvtool uvtool .SH NAME uvt-kvm \- Ubuntu virtualisation front-end for libvirt and KVM .SH SYNOPSIS .SY uvt-kvm\ list .YS .SY uvt-kvm\ create .RI [ options ] .I name .RI [ filter .IR ... ] .YS .SY uvt-kvm\ wait .RI [ options ] .I name .YS .SY uvt-kvm\ ip .I name .YS .SY uvt-kvm\ ssh .RI [ options ] .R [\fIuser\fB@\fR]\fIname\fR .RI [ command .IR ... ] .YS .SY uvt-kvm\ destroy .I name .YS .SH DESCRIPTION uvtool provides a unified and integrated VM front-end to Ubuntu cloud image downloads, libvirt, and cloud-init. .B uvt-kvm uses the volume storage pool maintained by .BR uvt-simplestreams-libvirt (1) as a basis to provide quick start and management of Ubuntu VMs by wrapping libvirt and cloud-init. .B uvt-kvm is not intended to wrap all possible use cases. Where possible, it provides access to some more advanced cases using options to override entire sections of default operation, such as the ability to directly override the backing volume image used, the libvirt domain definition and cloud-init metadata and userdata. For yet more complex cases, it is expected that the user will call libvirt directly (for example by using .BR virsh (1)), and use uvt-kvm for only the simpler operations required on affected VMs. See ADVANCED OVERRIDE OPTIONS and ADVANCED USAGE for details. .SH SUBCOMMANDS .BR uvt-kvm 's interface is designed around subcommands. The subcommand to be used must be specified as the first positional argument. Each subcommand has its own set of available options. Where a subcommand requires a VM to be specified, the VM name must be provided as a second positional argument. When using .B uvt-kvm\ create to create VMs, the VM name is specified by the user at this time. Where users have manipulated libvirt directly, VM names are expected to match libvirt domain names. .SS list .SY uvt-kvm\ list .YS Print a list of existing VMs to stdout. This list currently includes libvirt domains that are defined but were not created by uvt-kvm, but in future this is expected to change to VMs created by uvt-kvm only. .SS create .SY uvt-kvm\ create .RI [ options ] .I name .RI [ filter .IR ... ] .YS Create a new VM based on a backing volume specified by the provided simplestreams filters. This VM will be called .IR name , and the same .I name must be used when referring to the VM from the other subcommands. Each .I filter operates on the images downloaded and managed by .BR uvt-simplestreams-libvirt (1), and when combined together must uniquely specify a single image. See .BR uvt-simplestreams-libvirt (1) for details on image selection. Since backing volume images are downloaded and maintained by .BR uvt-simplestreams-libvirt (1), it is necessary to first run .BR uvt-simplestreams-libvirt (1) to download images before this subcommand will succeed. See EXAMPLES, below. If no filters are specified, a filter of \fBrelease=\fIrelease\fR is assumed, where .I release corresponds to the current LTS release as returned by .BR distro-info (1). Alternatively, see \fB--backing-image-file\fR under ADVANCED OVERRIDE OPTIONS below to supply a backing image directly yourself. This subcommand supports an extensive set of options to modify the definition and behavior of the VM. See LIBVIRT DOMAIN DEFINTION OPTIONS, CLOUD-INIT CONFIGURATION OPTIONS and ADVANCED OVERRIDE OPTIONS below. .SS wait .SY uvt-kvm\ wait .RI [ options ] .I name .YS Wait for a VM to become ready. This includes: waiting for the VM to request an IP address, waiting for ssh to become available on this IP, and an .BR ssh (1) operation into the VM to wait for cloud-init to finish and the system to enter runlevel 2. By using the wait command, scripts can create, operate on and destroy VMs synchronously and reliably. .TP .BI --timeout\ timeout Give up waiting after .I timeout seconds. Default: 120 seconds. .TP .BI --interval\ interval For wait operations that must poll, poll every .I interval seconds. Default: 8 seconds. .TP .BI --remote-wait-script\ remote_wait_script Run .I remote_wait_script through .BR sh (1) on the guest system, which must block and exit with a zero status when the system is ready. Default: .IR /usr/share/uvtool/remote-wait.sh , which assumes that upstart and cloud-init are being used on the guest, waits for upstart to enter runlevel 2 and then waits for cloud-init to signal that it has finished booting the system. When .I remote_wait_script is run on the guest system, its environment will define the variables .B UVTOOL_WAIT_INTERVAL and .B UVTOOL_WAIT_TIMEOUT which contain the poll interval and wait timeout as specified by the .B --interval and .B --timeout options, respectively. .TP .BI --remote-wait-user\ user Run the remote wait script as user .IR user . It must be possible to .BR ssh (1) into the guest system as this user for the remote wait mechanism to work. .TP .B --insecure Permit potentially insecure operations, which is currently required for the remote wait script to work. See COMMON OPTIONS, below. .TP .BI --ssh-private-key-file\ ssh_private_key_file Use .I ssh_private_key_file to authenticate to the guest machine when performing the .BR ssh (1) operation . .TP .B --without-ssh Skip the .BR ssh (1) operation. This will cause the command to exit with success as soon as the ssh port is available, but without logging to the guest to wait until it is ready internally. .SS ip .SY uvt-kvm\ ip .I name .YS Guess the IP address of a VM and print it to stdout. Currently, this assumes a default (Ubuntu) installation of libvirt and dnsmasq on the host, and default networking behaviour on the VM. IP address guessing is currently implemented by examining dnsmasq's leases file .I /var/lib/libvirt/dnsmasq/default.leases for the VM's NIC. This subcommand assumes that the VM has successfully acquired an IP address, and will fail otherwise. Callers can use .B uvt-kvm\ wait after creating or rebooting a VM to wait for this to become the case. In future, this subcommand may incorporate multiple IP address detection mechanisms. .SS ssh .SY uvt-kvm\ ssh .RI [ options ] .R [\fIuser\fB@\fR]\fIname\fR .RI [ command .IR ... ] .YS Run .BR ssh (1) against the VM. This is a limited wrapper around .BR ssh (1) and the ip subcommand, designed for ease-of-use in the common case. For full functionality, use the ip subcommand to obtain the VM's IP address, and then call .BR ssh (1) directly instead. .TP .B --insecure Permit potentially insecure operations, which is currently required for this subcommand to work. See COMMON OPTIONS, below. .TP .BI --login-name\ user .TQ .BI -l\ user Specify the username to pass to .BR ssh (1). This is the recommended method for use in scripts. This option overrides the username provided by the .B @ notation in the first positional argument, and thus allows the VM name to include an .B @ symbol. Default: .BR ubuntu , to match the default on Ubuntu cloud images. .SS destroy .SY uvt-kvm\ destroy .I name .YS Stop and completely destroy an existing VM. This stops the libvirt domain if it is running, undefines it, and deletes all volumes that had been part of the domain's definition. It does not, however, delete any backing volumes, thus keeping intact pristine Ubuntu cloud images as maintained by .BR uvt-simplestreams-libvirt (8). .SH COMMON OPTIONS .TP .B --insecure Valid for: \fBuvt-kvm\ wait\fR, \fBuvt-kvm\ ssh\fR. Permit connections which may not be secure. For .BR ssh (1) connections, this skips host key validation, since uvtool currently has no mechanism to securely acquire the ssh host key from a guest. In the common case, this should not be a problem since the guest system is located on the same system and this network path can be trusted. However, .B uvt-kvm will refuse to make a connection (for .BR uvt-kvm\ ssh ) or skip steps (for .BR uvt-kvm\ wait ) without this option, in order to make absolutely sure that the user cannot compromise his path to the guest system without being aware of this caveat. .TP .B -d .TQ .B --developer Valid for: \fBuvt-kvm\ create\fR only. Turn on a set of options deemed most useful for developers but not suitable for turning on by default. Currently this is the same as specifying .B --unsafe-caching and .B --log-console-output but this may change between releases. Scripts should never use this option. To protect against future changes to the definition of this option, they should instead use the expansion defined above. .SH LIBVIRT DOMAIN DEFINITION OPTIONS Valid for: \fBuvt-kvm\ create\fR only. These options modify the definition of the guest VM, and its connection to the host. .B uvt-kvm\ create takes the default or user-supplied libvirt domain XML template definition and modifies it according to the following parameters. Each of these parameters has a sensible default which may change between releases. .TP .BI --memory\ size Amount of system RAM in megabytes. Default: 512 (MiB). .TP .BI --disk\ size Size of the OS disk in gigabytes. Default: 8 (GiB). .TP .B --unsafe-caching Do not flush guest syncs to the host on the OS disk. This can improve guest I/O performance at the cost of losing data on host power failure. This option is useful for ephemeral guest machines that do not need to be persistent beyond a host power cycle. .TP .BI --cpu\ cores Number of CPU cores. Default: 1. .TP .BI --bridge\ bridge Replace the first defined NIC with one that connects to the given host bridge. Default: unaltered from the libvirt domain template. .TP .B --log-console-output Log output to a disk file on the host instead of to a pty. With libvirt's default configuration on Ubuntu, this log can be found in .IR /var/log/libvirt/qemu/.log . This options enables retrospective examination of VM console output, but breaks .B virsh\ console for interactive use. .SH CLOUD-INIT CONFIGURATION OPTIONS Valid for: \fBuvt-kvm\ create\fR only. These options modify operation within the guest VM itself. Unless .B --user-data is used to override this behaviour, uvt-kvm generates cloud-init userdata with some sensible defaults when a VM is created. These defaults can be altered using the following options: .TP .BI --password\ password Permit login to the VM to the default user .B ubuntu and password .IR password . This is useful for debugging purposes, since it also enables a VT login. Using this command line option leaks the password used to other users on the same system, so should never be used in production for security reasons. Default: no password login. .TP .BI --run-script-once\ script_file Run .I script_file as root on the VM the first time it is booted, but never again. This option can be used multiple times to run multiple scripts. If the script exits with a non-zero status, it will be left on the VM in /tmp for debugging purposes. .I script_file will be copied to the guest, marked as executable, and executed directly, so it must be an appropriate binary, start with a shebang, or otherwise be directly executable by the guest kernel. Default: no scripts. .TP .BI --ssh-public-key-file\ ssh_public_key_file Permit login to the VM to the default user .B ubuntu and the ssh keys specified in .IR ssh_public_key_file . Default: use the output of .B ssh-add\ -L if available; otherwise use .IR ~/.ssh/id_rsa.pub . If no source is found at all, then a warning will be printed to stderr, and VM creation will continue with no arrangement for access to the guest. .TP .BI --packages\ package_list Install the comma-separated packages specified in .I package_list on first boot. This option can be used multiple times; each additional option adds to the final package list. Default: no packages. .SH ADVANCED OVERRIDE OPTIONS Valid for: \fBuvt-kvm\ create\fR only. .TP .BI --template\ template_file The base libvirt domain definition XML template to use when constructing a new VM's definition. This is dynamically altered before domain creation; see LIBVIRT DOMAIN DEFINITION OPTIONS. Default: .IR /usr/share/uvtool/default.xml . .TP .BI --user-data\ user_data_file Override cloud-init userdata, instead using the file supplied. This overrides all options in the section CLOUD-INIT CONFIGURATION OPTIONS. Default: as described in CLOUD-INIT CONFIGURATION OPTIONS. .TP .BI --meta-data\ meta_data_file Override default cloud-init metadata, instead using the file supplied. This does not override any other options, since cloud-init metadata is not otherwise tunable. Default: minimal file with automatically generated instance-id. .TP .BI --backing-image-file\ image_file Specify the name of a local file that will be used to create the VM instead of relying on the volume storage pool. It must point to a qcow2 formatted file. This option overrides any simplestreams filters provided. .SH ADVANCED USAGE .B uvt-kvm is carefully constructed to avoid impeding the ability of the user to directly use .BR virsh (1) or other libvirt tooling at any time, and provides override options to supply backing image volumes and cloud-init userdata and metadata where possible. VMs created by uvt-kvm are not "special" in libvirt. What uvt-kvm does with VMs is well-defined, so that advanced users can manipulate a VM using libvirt directly without necessarily losing the ability for uvt-kvm to continue to manipulate that VM for common use cases. .SS TERMINOLOGY AND LIFECYCLE For simplicity, uvt-kvm uses .I create to mean the definition, allocation and running of a VM, and .I destroy to mean the stopping and removing of all persistent state associated with a VM, including VM-specific disk image files and the VM definition itself. This matches the commonly expected lifecycle of VMs created with uvt-kvm. This works well for the common use case, but if VMs created with uvt-kvm need to be manipulated with .BR virsh (1) or libvirt directly, then it becomes necessary to understand how this matches up to the more complex libvirt terminology. In libvirt, a VM is called a .IR domain . A domain is first defined, and then independently started. In libvirt terminology, .I destroy means a VM stop; after a .IR destroy , the domain still exists and can be restarted. .I undefine finally removes the domain definition. Resources associated with a VM (such as disk image files, which in libvirt are called .IR volumes ) must be created and destroyed separately. When uvt-kvm creates a VM, libvirt volumes are defined and populated, a libvirt domain is defined, marked as autostarted, and the domain started. When uvt-kvm destroys a VM, the corresponding libvirt domain is stopped, domain-specific volumes deleted and the libvirt domain itself is undefined. .SH EXAMPLES .EX # Update uvtool's libvirt volume storage pool with the # latest Precise image .B uvt-simplestreams-libvirt sync release=precise arch=amd64 # Create an ssh key for the local user (if you don't have # one already) .B ssh-keygen # (...) # Create an amd64 VM running Precise .B uvt-kvm create myvm release=precise arch=amd64 # Wait for the VM to become ready .B uvt-kvm wait --insecure myvm # Shell into the VM to do some testing there .B uvt-kvm ssh --insecure myvm # (...) # Destroy the VM .B uvt-kvm destroy myvm .EE .SH TROUBLESHOOTING .SS Common Errors .EX .B Failed to connect socket to '/var/run/libvirt/libvirt-sock': Permission denied .EE Do you have permission to connect to libvirt? On Ubuntu, you must belong to the .B libvirtd group. Users with .BR sudo (8) access are added to this group by default, but users only get group membership on the next login after the .B libvirt-bin package has been installed. To temporarily add yourself to this group in advance of your next login, try .BR newgrp\ libvirtd . .EX .B no supported architecture for os type 'hvm' .EE libvirt did not find KVM support on your system. Try .B sudo\ kvm-ok for diagnostics, and .B service\ libvirt-bin\ restart to pick up any changes before retrying. .SS Interactive console access If you cannot access the VM from the host system, try using .B --password to set a password for the default .B ubuntu user inside the VM, and then logging in to the VM over the console in order to examine it from the inside. To access the console interactively, use \fBvirsh\ console\fR\ \fIname\fR. However, note that interactive access is disabled if you are using .B --log-console-output or .BR -d , so for interactive access you will have to drop these options if you are using them. If you are using .BR --user-data , then .B --password will be overridden by it and you will need to modify your cloud-init userdata manually to achieve the same effect. .SH SEE ALSO .BR uvt-simplestreams-libvirt (1), .BR distro-info (1), .BR dnsmasq (8), .BR virsh (1). uvtool-0~bzr99/man/uvt-simplestreams-libvirt.10000644000000000000000000000450612512767613020020 0ustar 00000000000000.TH uvt\-simplestreams\-libvirt 1 "2014-03-11" uvtool uvtool .SH NAME uvt-simplestreams-libvirt \- manage simplestreams images in libvirt .SH SYNOPSIS .SY uvt-simplestreams-libvirt\ sync .RB [ --no-authentication ] .OP --keyring keyring .OP --source source .OP --path path .RI [ filter .IR ... ] .YS .SY uvt-simplestreams-libvirt\ query .RI [ filter .IR ... ] .YS .SY uvt-simplestreams-libvirt\ purge .YS .SH DESCRIPTION .B uvt-simplestreams-libvirt maintains a libvirt volume storage pool as a local mirror of a subset of images available from a simplestreams source, such as Ubuntu cloud images. .B uvt-simplestreams-libvirt\ sync updates the local mirror with the latest version of each product available in the simplestreams source. Each .I filter restricts the set of images visible to the tool. .B uvt-simplestreams-libvirt\ query queries the local mirror. Each .I filter restricts the output. .B uvt-simplestreams-libvirt\ purge exists only for development and debugging purposes, and should not normally be used. It purges the entire libvirt volume storage pool and all metadata associated with it, breaking any existing VMs that use these volumes. This subcommand may disappear in the future. .SH OPTIONS .TP .B --no-authentication Do not authenticate the source. This is useful when you are using a local source, or can otherwise trust both the source and your network path to the source. It is insecure in other cases and should not be used. .TP .BI --keyring\ keyring Use the .BR gpg (1) .I keyring to authenticate the source. Default: .IR /usr/share/keyrings/ubuntu-cloudimage-keyring.gpg . .TP .BI --source\ source Use the .I source URL as the simplestreams source of product images to sync. .TP .BI --path\ path Pass .I path to the simplestreams library. .SH EXAMPLES .EX # Update uvtool's libvirt volume storage pool with all # current amd64 images. .B uvt-simplestreams-libvirt sync arch=amd64 # Update uvtool's libvirt volume storage pool with the # latest amd64 Precise image .B uvt-simplestreams-libvirt sync release=precise arch=amd64 # Update uvtool's libvirt volume storage pool with the # latest amd64 (development) trusty image .B uvt-simplestreams-libvirt sync \e .B \ \ \ \ \ \ \ \ --source http://cloud-images.ubuntu.com/daily \e .B \ \ \ \ \ \ \ \ release=trusty arch=amd64 .EE .SH SEE ALSO .BR gpg (1), .BR uvt-kvm (1). uvtool-0~bzr99/uvtool/__init__.py0000644000000000000000000000000012512767613015430 0ustar 00000000000000uvtool-0~bzr99/uvtool/libvirt/0000755000000000000000000000000012512767613015004 5ustar 00000000000000uvtool-0~bzr99/uvtool/tests/0000755000000000000000000000000012512767613014473 5ustar 00000000000000uvtool-0~bzr99/uvtool/wait.py0000644000000000000000000001055512512767613014655 0ustar 00000000000000# Copyright (C) 2013 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from __future__ import print_function from __future__ import unicode_literals import argparse import contextlib import functools import os import socket import sys import time import pyinotify import uvtool.libvirt from uvtool.libvirt import ( LIBVIRT_DNSMASQ_LEASE_FILE, LIBVIRT_DNSMASQ_STATUS_FILE ) SSH_PORT = 22 class LeaseModifyWaiter(object): def __init__(self): self.wm = pyinotify.WatchManager() self.notifier = pyinotify.Notifier(self.wm, pyinotify.ProcessEvent()) def start_watching(self): for f in [LIBVIRT_DNSMASQ_LEASE_FILE, LIBVIRT_DNSMASQ_STATUS_FILE]: if os.path.exists(f): self.wm.add_watch(f, pyinotify.IN_MODIFY) def wait(self, timeout): if self.notifier.check_events(timeout=(timeout*1000)): self.notifier.read_events() self.notifier.process_events() return True else: return False def close(self): self.wm.close() def lease_has_mac(mac): return uvtool.libvirt.mac_to_ip(mac) is not None def wait_for_libvirt_dnsmasq_lease(mac, timeout): # Shortcut check to save inotify setup if lease_has_mac(mac): return True timeout_time = time.time() + timeout waiter = LeaseModifyWaiter() with contextlib.closing(waiter): waiter.start_watching() # Check after we've set up a watch to avoid the race of something # happening between the last check and the watch starting if lease_has_mac(mac): return True current_time = time.time() while current_time < timeout_time: remaining_time_to_timeout = timeout_time - current_time waiter.wait(timeout=remaining_time_to_timeout) if lease_has_mac(mac): return True current_time = time.time() return False def has_open_ssh_port(host, timeout=4): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) with contextlib.closing(s): s.settimeout(timeout) try: s.connect((host, SSH_PORT)) except: return False else: return True def poll_for_true(fn, interval, timeout): timeout_time = time.time() + timeout while time.time() < timeout_time: if fn(): return True # This could do with a little more care to ensure that we never # sleep beyond timeout_time. time.sleep(interval) return False def wait_for_open_ssh_port(host, interval, timeout): return poll_for_true( functools.partial(has_open_ssh_port, host), interval, timeout ) def main_libvirt_dnsmasq_lease(parser, args): if not wait_for_libvirt_dnsmasq_lease(mac=args.mac, timeout=args.timeout): print("cloud-wait: timed out", file=sys.stderr) sys.exit(1) def main_ssh(parser, args): if not wait_for_open_ssh_port(args.host, args.interval, args.timeout): print("cloud-wait: timed out", file=sys.stderr) sys.exit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument('--timeout', type=float, default=120.0) subparsers = parser.add_subparsers() libvirt_dnsmasq_lease_parser = subparsers.add_parser( 'libvirt-dnsmasq-lease') libvirt_dnsmasq_lease_parser.set_defaults(func=main_libvirt_dnsmasq_lease) libvirt_dnsmasq_lease_parser.add_argument('mac') ssh_parser = subparsers.add_parser('ssh') ssh_parser.set_defaults(func=main_ssh) ssh_parser.add_argument('--interval', type=float, default=8.0) ssh_parser.add_argument('host') args = parser.parse_args() args.func(parser, args) if __name__ == '__main__': main() uvtool-0~bzr99/uvtool/libvirt/__init__.py0000644000000000000000000002160112512767613017115 0ustar 00000000000000# Copyright (C) 2013 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import codecs import contextlib import errno import itertools import json import os import shutil import subprocess import tempfile import libvirt from lxml import etree from lxml.builder import E LIBVIRT_DNSMASQ_LEASE_FILE = '/var/lib/libvirt/dnsmasq/default.leases' LIBVIRT_DNSMASQ_STATUS_FILE = '/var/lib/libvirt/dnsmasq/virbr0.status' def get_libvirt_pool_object(libvirt_conn, pool_name): try: pool = libvirt_conn.storagePoolLookupByName(pool_name) except libvirt.libvirtError: raise RuntimeError("Cannot find pool %s." % repr(pool_name)) return pool def create_volume_from_fobj(new_volume_name, fobj, image_type='raw', pool_name='default'): """Create a new libvirt volume and populate it from a file-like object.""" compressed_fobj = tempfile.NamedTemporaryFile() decompressed_fobj = tempfile.NamedTemporaryFile() with contextlib.closing(compressed_fobj): with contextlib.closing(decompressed_fobj): shutil.copyfileobj(fobj, compressed_fobj) compressed_fobj.flush() compressed_fobj.seek(0) # is this necessary? subprocess.check_call( [ 'qemu-img', 'convert', '-f', image_type, '-O', image_type, compressed_fobj.name, decompressed_fobj.name ], shell=False, close_fds=False) decompressed_fobj.seek(0) # is this necessary? return _create_volume_from_fobj_with_size( new_volume_name=new_volume_name, fobj=decompressed_fobj, fobj_size=os.fstat(decompressed_fobj.fileno()).st_size, image_type=image_type, pool_name=pool_name ) def _create_volume_from_fobj_with_size(new_volume_name, fobj, fobj_size, image_type, pool_name): conn = libvirt.open('qemu:///system') pool = get_libvirt_pool_object(conn, pool_name) if image_type == 'raw': extra = [E.allocation(str(fobj_size)), E.capacity(str(fobj_size))] elif image_type == 'qcow2': extra = [E.capacity('0')] else: raise NotImplementedError("Unknown image type %r." % image_type) new_vol = E.volume( E.name(new_volume_name), E.target(E.format(type=image_type)), *extra ) vol = pool.createXML(etree.tostring(new_vol), 0) try: stream = conn.newStream(0) vol.upload(stream, 0, fobj_size, 0) def handler(stream_ignored, size, opaque_ignored): return fobj.read(size) try: stream.sendAll(handler, None) except Exception as e: try: # This unexpectedly raises an exception even on a normal call, # so ignore it. stream.abort() except: pass raise e stream.finish() except: vol.delete(flags=0) raise return vol def volume_names_in_pool(pool_name='default'): conn = libvirt.open('qemu:///system') pool = get_libvirt_pool_object(conn, pool_name) return pool.listVolumes() def delete_volume_by_name(volume_name, pool_name='default'): conn = libvirt.open('qemu:///system') pool = get_libvirt_pool_object(conn, pool_name) volume = pool.storageVolLookupByName(volume_name) volume.delete(flags=0) def have_volume_by_name(volume_name, pool_name='default'): conn = libvirt.open('qemu:///system') pool = get_libvirt_pool_object(conn, pool_name) try: volume = pool.storageVolLookupByName(volume_name) except libvirt.libvirtError: return False else: return True def _get_all_domains(conn=None): if conn is None: conn = libvirt.open('qemu:///system') # libvirt in Precise doesn't seem to have a binding for # virConnectListAllDomains, and it seems that we must enumerate # defined-by-not-running and running instances separately and in different # ways. for domain_id in conn.listDomainsID(): yield conn.lookupByID(domain_id) for domain_name in conn.listDefinedDomains(): yield conn.lookupByName(domain_name) def _domain_element_to_volume_paths(element): assert element.tag == 'domain' return ( source.get('file') for source in element.xpath( "/domain/devices/disk[@type='file']/source[@file]" ) ) def _domain_volume_paths(domain): volume_paths = set() for flags in [0, libvirt.VIR_DOMAIN_XML_INACTIVE]: element = etree.fromstring(domain.XMLDesc(flags)) volume_paths.update(_domain_element_to_volume_paths(element)) return frozenset(volume_paths) def _volume_element_to_volume_paths(element): assert element.tag == 'volume' return itertools.chain( (path.text for path in element.xpath('/volume/target/path')), (path.text for path in element.xpath('/volume/backingStore/path')), ) def _volume_volume_paths(volume): # Volumes can depend on other volumes ("backing stores"), so return all # paths a volume needs to function, including the top level one. volume_paths = set() element = etree.fromstring(volume.XMLDesc(0)) volume_paths.update(_volume_element_to_volume_paths(element)) return frozenset(volume_paths) def _get_all_domain_volume_paths(conn=None): if conn is None: conn = libvirt.open('qemu:///system') all_volume_paths = set() for domain in _get_all_domains(conn): for path in _domain_volume_paths(domain): try: volume = conn.storageVolLookupByKey(path) except libvirt.libvirtError: # ignore a lookup failure, since if a volume doesn't exist, # it isn't reasonable to consider what backing volumes it may # have continue all_volume_paths.update(_volume_volume_paths(volume)) return frozenset(all_volume_paths) def get_all_domain_volume_names(conn=None, filter_by_dir=None): # Limitation: filter_by_dir must currently end in a '/' and be the # canonical path as libvirt returns it. Ideally I'd filter by pool instead, # but the libvirt API appears to not provide any method to find what pool a # volume is in when looked up by key. if conn is None: conn = libvirt.open('qemu:///system') for path in _get_all_domain_volume_paths(conn=conn): volume = conn.storageVolLookupByKey(path) if filter_by_dir and not volume.path().startswith(filter_by_dir): continue yield volume.name() def get_domain_macs(domain_name, conn=None): if conn is None: conn = libvirt.open('qemu:///system') domain = conn.lookupByName(domain_name) xml = etree.fromstring(domain.XMLDesc(0)) for mac in xml.xpath( "/domain/devices/interface[@type='network']/mac[@address]"): yield mac.get('address') def dnsmasq_lease_file_mac_to_ip(lowercase_mac): MAC_FIELD = 1 IP_FIELD = 2 MIN_FIELDS = max(MAC_FIELD, IP_FIELD) try: f = codecs.open(LIBVIRT_DNSMASQ_LEASE_FILE, 'r') except IOError as e: if e.errno == errno.ENOENT: return None else: raise with contextlib.closing(f): for line in f: fields = line.split() if (len(fields) >= MIN_FIELDS and fields[MAC_FIELD].lower() == lowercase_mac): return fields[IP_FIELD] return None def libvirt_dnsmasq_status_file_mac_to_ip(lowercase_mac): try: f = codecs.open(LIBVIRT_DNSMASQ_STATUS_FILE , 'r') except IOError as e: if e.errno == errno.ENOENT: return None else: raise with contextlib.closing(f): try: j = json.load(f) except ValueError: return None for entry in j: if entry.get('mac-address') == lowercase_mac: return entry['ip-address'] return None def mac_to_ip(mac): lowercase_mac = mac.lower() return ( dnsmasq_lease_file_mac_to_ip(lowercase_mac) or libvirt_dnsmasq_status_file_mac_to_ip(lowercase_mac) ) uvtool-0~bzr99/uvtool/libvirt/kvm.py0000755000000000000000000005577712512767613016203 0ustar 00000000000000#!/usr/bin/python # Wrapper around cloud-localds and libvirt # Copyright (C) 2012-3 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse import errno import itertools import os import shutil import signal import StringIO import subprocess import sys import tempfile import uuid import yaml import libvirt from lxml import etree from lxml.builder import E import uvtool.libvirt import uvtool.libvirt.simplestreams import uvtool.wait DEFAULT_TEMPLATE = '/usr/share/uvtool/libvirt/template.xml' DEFAULT_REMOTE_WAIT_SCRIPT = '/usr/share/uvtool/libvirt/remote-wait.sh' POOL_NAME = 'uvtool' class CLIError(Exception): """An error that should be reflected back to the CLI user.""" pass # From: http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html def subprocess_setup(): # Python installs a SIGPIPE handler by default. This is usually not what # non-Python subprocesses expect. signal.signal(signal.SIGPIPE, signal.SIG_DFL) def run_script_once_arg_to_config(arg, unique_id): with open(arg, 'rb') as f: script = f.read() encoded_script = script.encode('base64') return [ b'cloud-init-per', b'once', unique_id.encode('utf-8'), b'sh', b'-c', ( b'f=$(mktemp --tmpdir %s-XXXXXXXXXX) && ' + b'echo "%s" | base64 -d > "$f" && ' + b'chmod 700 "$f" && ' + b'"$f" && ' + b'rm "$f"' ) % (unique_id.encode('utf-8'), encoded_script) ] def run_script_once_args_to_config(args): return [ run_script_once_arg_to_config(arg, 'uvt-kvm-%s' % i) for i, arg in enumerate(args) ] def get_ssh_agent_public_keys(): """Read public keys from an agent, if available, or return None.""" try: with open("/dev/null") as fpnull: output = subprocess.check_output( ['ssh-add', '-L'], stderr=fpnull ) except subprocess.CalledProcessError: return None output = output.strip() if output: return output.splitlines() else: return None def read_ssh_public_key_file(filename): """Read public keys from a file, or return None.""" if filename is None: filename = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa.pub') try: f = open(filename, 'rb') except IOError as e: if e.errno != errno.ENOENT: raise return None, filename else: with f: return f.read().strip().splitlines(), filename def get_ssh_authorized_keys(filename): # If the user hasn't explicitly specified a file source, then try # the agent first. if filename is None: agent_keys = get_ssh_agent_public_keys() if agent_keys: return agent_keys # Fall back to reading the public key file. # Read the public key file if one is present. file_keys, filename_used = read_ssh_public_key_file(filename) if file_keys: return file_keys else: print( "Warning: %s not found; instance will be started " "with no ssh access by default." % repr(filename_used), file=sys.stderr, ) return [] def create_default_user_data(fobj, args): """Write some sensible default cloud-init user-data to the given file object. """ ssh_authorized_keys = get_ssh_authorized_keys(args.ssh_public_key_file) data = { b'hostname': args.hostname.encode('ascii'), b'manage_etc_hosts': b'localhost', } if ssh_authorized_keys: data[b'ssh_authorized_keys'] = ssh_authorized_keys if args.password: data[b'password'] = args.password.encode('utf-8') data[b'chpasswd'] = {b'expire': False} data[b'ssh_pwauth'] = True if args.run_script_once: data[b'runcmd'] = run_script_once_args_to_config(args.run_script_once) if args.packages: data[b'packages'] = [ s.encode('ascii') # Debian Policy dictates a-z,0-9,+,-,. for s in itertools.chain(*[p.split(',') for p in args.packages]) ] fobj.write("#cloud-config\n") fobj.write(yaml.dump(data)) def create_default_meta_data(fobj, args): data = { b'instance-id': str(uuid.uuid1()).encode('ascii'), } fobj.write(yaml.dump(data)) def create_ds_image(temp_dir, hostname, user_data_fobj, meta_data_fobj): """Create a file called ds.img inside temp_dir that contains a useful cloud-init data source. Other temporary files created in temp_dir are currently metadata and userdata and can be safely deleted. """ with open(os.path.join(temp_dir, 'userdata'), 'wb') as f: f.write(user_data_fobj.read()) with open(os.path.join(temp_dir, 'metadata'), 'wb') as f: f.write(meta_data_fobj.read()) subprocess.check_call( ['cloud-localds', 'ds.img', 'userdata', 'metadata'], cwd=temp_dir) def create_ds_volume(new_volume_name, hostname, user_data_fobj, meta_data_fobj): """Create a new libvirt cloud-init datasource volume.""" temp_dir = tempfile.mkdtemp(prefix='uvt-kvm-') try: create_ds_image(temp_dir, hostname, user_data_fobj, meta_data_fobj) with open(os.path.join(temp_dir, 'ds.img'), 'rb') as f: return uvtool.libvirt.create_volume_from_fobj( new_volume_name, f, pool_name=POOL_NAME) finally: shutil.rmtree(temp_dir) def create_cow_volume(backing_volume_name, new_volume_name, new_volume_size, conn=None): if conn is None: conn = libvirt.open('qemu:///system') pool = conn.storagePoolLookupByName(POOL_NAME) try: backing_vol = pool.storageVolLookupByName(backing_volume_name) except libvirt.libvirtError: raise RuntimeError("Cannot find volume %s" % backing_volume_name) return create_cow_volume_by_path( backing_volume_path=backing_vol.path(), new_volume_name=new_volume_name, new_volume_size=new_volume_size, conn=conn ) def create_cow_volume_by_path(backing_volume_path, new_volume_name, new_volume_size, conn=None): """Create a new libvirt qcow2 volume backed by an existing volume path.""" if conn is None: conn = libvirt.open('qemu:///system') pool = conn.storagePoolLookupByName(POOL_NAME) new_vol = E.volume( E.name(new_volume_name), E.allocation('0'), E.capacity(str(new_volume_size), unit='G'), E.target(E.format(type='qcow2')), E.backingStore( E.path(backing_volume_path), E.format(type='qcow2'), ) ) return pool.createXML(etree.tostring(new_vol), 0) def compose_domain_xml(name, volumes, cpu=1, memory=512, unsafe_caching=False, template_path=DEFAULT_TEMPLATE, log_console_output=False, bridge=None): tree = etree.parse(template_path) domain = tree.getroot() assert domain.tag == 'domain' etree.strip_elements(domain, 'name') etree.SubElement(domain, 'name').text = name etree.strip_elements(domain, 'vcpu') etree.SubElement(domain, 'vcpu').text = str(cpu) etree.strip_elements(domain, 'currentMemory') etree.SubElement(domain, 'currentMemory').text = str(memory * 1024) etree.strip_elements(domain, 'memory') etree.SubElement(domain, 'memory').text = str(memory * 1024) devices = domain.find('devices') etree.strip_elements(devices, 'disk') for disk_device, vol in zip(['vda', 'vdb'], volumes): disk_format_type = ( etree.fromstring(vol.XMLDesc(0)). find('target'). find('format'). get('type') ) if unsafe_caching: disk_driver = E.driver( name='qemu', type=disk_format_type, cache='unsafe') else: disk_driver = E.driver(name='qemu', type=disk_format_type) devices.append( E.disk( disk_driver, E.source(file=vol.path()), E.target(dev=disk_device), type='file', device='disk', ) ) if bridge: etree.strip_elements(devices, 'interface') devices.append(E.interface( E.source(bridge=bridge), E.model(type='virtio'), type='bridge'), ) if log_console_output: print( "Warning: logging guest console output introduces a DoS " + "security problem on the host and should not be used in " + "production.", file=sys.stderr ) etree.strip_elements(devices, 'serial') devices.append(E.serial(E.target(port='0'), type='stdio')) return etree.tostring(tree) def get_base_image(filters): result = list(uvtool.libvirt.simplestreams.query(filters)) if not result: raise CLIError( "no images found that match filters %s." % repr(filters)) elif len(result) != 1: raise CLIError( "multiple images found that match filters %s." % repr(filters)) return result[0] def create(hostname, filters, user_data_fobj, meta_data_fobj, memory=512, cpu=1, disk=2, unsafe_caching=False, template_path=DEFAULT_TEMPLATE, log_console_output=False, bridge=None, backing_image_file=None): if backing_image_file is None: base_volume_name = get_base_image(filters) undo_volume_creation = [] try: # cow image names must end in ".qcow" so that the current Apparmor # profile for /usr/lib/libvirt/virt-aa-helper is able to read them, # determine their backing volumes, and generate a dynamic libvirt # profile that permits reading the backing volume. Once our pool # directory is added to the virt-aa-helper profile, this requirement # can be dropped. if backing_image_file: main_vol = create_cow_volume_by_path( backing_image_file, "%s.qcow" % hostname, disk) else: main_vol = create_cow_volume( base_volume_name, "%s.qcow" % hostname, disk) undo_volume_creation.append(main_vol) ds_vol = create_ds_volume( "%s-ds.qcow" % hostname, hostname, user_data_fobj, meta_data_fobj) undo_volume_creation.append(ds_vol) xml = compose_domain_xml( hostname, [main_vol, ds_vol], bridge=bridge, cpu=cpu, log_console_output=log_console_output, memory=memory, template_path=template_path, unsafe_caching=unsafe_caching, ) conn = libvirt.open('qemu:///system') domain = conn.defineXML(xml) try: domain.create() except: domain.undefine() raise except: for vol in undo_volume_creation: vol.delete(0) raise def delete_domain_volumes(conn, domain): """Delete all volumes associated with a domain. :param conn: libvirt connection object :param domain: libvirt domain object """ domain_xml = etree.fromstring(domain.XMLDesc(0)) assert domain_xml.tag == 'domain' for disk in domain_xml.find('devices').iter('disk'): disk_file = disk.find('source').get('file') vol = conn.storageVolLookupByKey(disk_file) vol.delete(0) def destroy(hostname): conn = libvirt.open('qemu:///system') try: domain = conn.lookupByName(hostname) except libvirt.libvirtError as e: if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN: raise CLIError("domain %s not found." % repr(hostname)) else: raise state = domain.state(0)[0] if state != libvirt.VIR_DOMAIN_SHUTOFF: domain.destroy() delete_domain_volumes(conn, domain) domain.undefine() def get_lts_series(): output = subprocess.check_output(['distro-info', '--lts'], close_fds=True) return output.strip() def apply_default_fobj(args, key, create_default_data_fn): """Return the fobj specified, creating it if required. If the "key" attribute inside args is not None, then just return it. Otherwise, construct a new temporary fobj, populate it with the result of create_default_data_fn, and then return that. This is useful to apply default file objects to argparse.FileType command line parameters. """ specified_fobj = getattr(args, key) if specified_fobj: return specified_fobj else: default_fobj = StringIO.StringIO() create_default_data_fn(default_fobj, args) default_fobj.seek(0) return default_fobj def check_kvm_ok(): try: process = subprocess.Popen( ['kvm-ok'], shell=False, stdout=subprocess.PIPE, close_fds=True) except OSError as e: if e.errno != errno.ENOENT: raise # Ignore if we can't find kvm-ok executable return True, None stdout, stderr = process.communicate() return (False, stdout) if process.returncode else (True, None) def name_to_ips(name): macs = uvtool.libvirt.get_domain_macs(name) return [ ip for ip in (uvtool.libvirt.mac_to_ip(mac) for mac in macs) if ip ] def ssh(name, login_name, arguments, stdin=None, checked=False, sysexit=True, private_key_file=None): ips = name_to_ips(name) ip_count = len(ips) if not ip_count: raise CLIError( "no IP address found for libvirt machine %s. " "Has it had time to boot yet?\nTry: %s wait" % (repr(name), sys.argv[0])) elif ip_count > 1: raise CLIError( "multiple IPs detected for %s %s and are not supported." % (repr(name), repr(ips)) ) ip = ips[0] ssh_call = [ 'ssh', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', '-o', 'CheckHostIP=no' ] if login_name: ssh_call.extend(['-l', login_name]) if private_key_file: ssh_call.extend(['-i', private_key_file]) ssh_call.append(ip) ssh_call.extend(arguments) call = subprocess.check_call if checked else subprocess.call result = call( ssh_call, preexec_fn=subprocess_setup, close_fds=True, stdin=stdin ) if sysexit: sys.exit(result) return result def main_create(parser, args): if args.user_data and args.password: parser.error("--password cannot be used with --user-data.") if args.password: print( "Warning: using --password from the command line is " + "not secure and should be used for debugging only.", file=sys.stderr ) kvm_ok, is_kvm_ok_output = check_kvm_ok() if not kvm_ok: print( "KVM not available. kvm-ok returned:", is_kvm_ok_output, sep="\n", end="", file=sys.stderr ) return user_data_fobj = apply_default_fobj( args, 'user_data', create_default_user_data ) meta_data_fobj = apply_default_fobj( args, 'meta_data', create_default_meta_data ) if args.backing_image_file: abs_image_backing_file = os.path.abspath(args.backing_image_file) else: abs_image_backing_file = None create( args.hostname, args.filters, user_data_fobj, meta_data_fobj, backing_image_file=abs_image_backing_file, bridge=args.bridge, cpu=args.cpu, disk=args.disk, log_console_output=args.log_console_output, memory=args.memory, template_path=args.template, unsafe_caching=args.unsafe_caching, ) def main_destroy(parser, args): for h in args.hostname: destroy(h) def main_list(parser, args): # Hack for now. In time this should properly use the API and list # only instances created with this tool. subprocess.check_call('virsh -q list --all|awk \'{print $2}\'', shell=True) def main_ip(parser, args): ips = name_to_ips(args.name) count = len(ips) if not count: raise CLIError( "no IP address found for libvirt machine %s." % repr(args.name)) elif count > 1: print( "Warning: multiple IP address found for libvirt machine %s; " + "listing the first one only", file=sys.stderr ) print(ips[0]) def main_ssh(parser, args, default_login_name='ubuntu'): if not args.insecure: raise CLIError( "ssh access with host key verification is not implemented. " + "Use --insecure iff you trust your network path to the guest." ) if args.login_name: login_name = args.login_name name = args.name elif '@' in args.name: login_name, name = args.name.split('@', 1) else: login_name = default_login_name name = args.name return ssh(name, login_name, args.ssh_arguments) def main_wait_remote(parser, args): if not args.insecure: print( "Warning: secure wait for boot-finished not yet implemented; " "use --insecure.", file=sys.stderr ) return with open(args.remote_wait_script, 'rb') as wait_script: ssh( args.name, args.remote_wait_user, [ 'env', 'UVTOOL_WAIT_INTERVAL=%s' % args.interval, 'UVTOOL_WAIT_TIMEOUT=%s' % args.timeout, 'sh', '-' ], checked=True, stdin=wait_script, private_key_file=args.ssh_private_key_file, ) def main_wait(parser, args): conn = libvirt.open('qemu:///system') domain = conn.lookupByName(args.name) state = domain.state(0)[0] if state != libvirt.VIR_DOMAIN_RUNNING: raise CLIError( "libvirt domain %s is not running." % repr(args.name)) macs = list(uvtool.libvirt.get_domain_macs(args.name)) if not macs: raise CLIError( "libvirt domain %s has no NIC MACs available." % repr(args.name)) if len(macs) > 1: raise CLIError( "libvirt domain %s has more than one NIC defined." % repr(args.name) ) mac = macs[0] if not uvtool.wait.wait_for_libvirt_dnsmasq_lease( mac, args.timeout): raise CLIError( "timed out waiting for dnsmasq lease for %s." % mac) host_ip = uvtool.libvirt.mac_to_ip(mac) if not uvtool.wait.wait_for_open_ssh_port( host_ip, args.interval, args.timeout): raise CLIError( "timed out waiting for ssh to open on %s." % host_ip) if not args.without_ssh: main_wait_remote(parser, args) class DeveloperOptionAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): namespace.unsafe_caching = True namespace.log_console_output = True def main(args): # Workaround for https://bugzilla.redhat.com/show_bug.cgi?id=1063766 # (LP: #1228231) libvirt.registerErrorHandler(lambda _: None, None) parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() create_subparser = subparsers.add_parser('create') create_subparser.set_defaults(func=main_create) create_subparser.add_argument( '--developer', '-d', nargs=0, action=DeveloperOptionAction) create_subparser.add_argument('--template', default=DEFAULT_TEMPLATE) create_subparser.add_argument('--memory', default=512, type=int) create_subparser.add_argument('--cpu', default=1, type=int) create_subparser.add_argument('--disk', default=8, type=int) create_subparser.add_argument('--bridge') create_subparser.add_argument('--unsafe-caching', action='store_true') create_subparser.add_argument( '--user-data', type=argparse.FileType('rb')) create_subparser.add_argument( '--meta-data', type=argparse.FileType('rb')) create_subparser.add_argument('--password') create_subparser.add_argument('--log-console-output', action='store_true') create_subparser.add_argument('--backing-image-file') create_subparser.add_argument('--run-script-once', action='append') create_subparser.add_argument('--ssh-public-key-file') create_subparser.add_argument('--packages', action='append') create_subparser.add_argument('hostname') create_subparser.add_argument( 'filters', nargs='*', metavar='filter', default=["release=%s" % get_lts_series()], ) destroy_subparser = subparsers.add_parser('destroy') destroy_subparser.set_defaults(func=main_destroy) destroy_subparser.add_argument('hostname', nargs='+') list_subparser = subparsers.add_parser('list') list_subparser.set_defaults(func=main_list) ip_subparser = subparsers.add_parser('ip') ip_subparser.set_defaults(func=main_ip) ip_subparser.add_argument('name') ssh_subparser = subparsers.add_parser('ssh') ssh_subparser.set_defaults(func=main_ssh) ssh_subparser.add_argument('--insecure', action='store_true') ssh_subparser.add_argument('--login-name', '-l') ssh_subparser.add_argument('name') ssh_subparser.add_argument('ssh_arguments', nargs='*') wait_subparser = subparsers.add_parser('wait') wait_subparser.set_defaults(func=main_wait) wait_subparser.add_argument('--timeout', type=float, default=120.0) wait_subparser.add_argument('--interval', type=float, default=8.0) wait_subparser.add_argument('--remote-wait-script', default=DEFAULT_REMOTE_WAIT_SCRIPT) wait_subparser.add_argument('--insecure', action='store_true') wait_subparser.add_argument('--remote-wait-user', default='ubuntu') wait_subparser.add_argument('--without-ssh', action='store_true') wait_subparser.add_argument('--ssh-private-key-file') wait_subparser.add_argument('name') args = parser.parse_args(args) args.func(parser, args) def main_cli_wrapper(*args, **kwargs): try: main(*args, **kwargs) except CLIError as e: print( "%s: error: %s" % (os.path.basename(sys.argv[0]), e), file=sys.stderr ) sys.exit(1) except libvirt.libvirtError as e: libvirt_message = e.get_error_message() print( "%s: error: libvirt: %s" % ( os.path.basename(sys.argv[0]), libvirt_message ), file=sys.stderr ) sys.exit(1) if __name__ == '__main__': main_cli_wrapper(sys.argv[1:]) uvtool-0~bzr99/uvtool/libvirt/simplestreams.py0000755000000000000000000002702212512767613020254 0ustar 00000000000000#!/usr/bin/python # Keep Ubuntu Cloud images synced to a local libvirt storage pool. # Copyright (C) 2013 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # This is written using Python 2 because libvirt bindings were not available # for Python 3 at the time of writing. from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse import base64 import codecs import collections import errno import json import os import subprocess import sys import libvirt import simplestreams.filters import simplestreams.mirrors import simplestreams.util import uvtool.libvirt LIBVIRT_POOL_NAME = 'uvtool' IMAGE_DIR = '/var/lib/uvtool/libvirt/images/' # must end in '/'; see use METADATA_DIR = '/var/lib/uvtool/libvirt/metadata' USEFUL_FIELD_NAMES = ['release', 'arch', 'label'] def mkdir_p(path): """Create path if it doesn't exist already""" try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise class Metadata(object): def __init__(self, metadata_dir=METADATA_DIR): self.metadata_dir = metadata_dir # Deliberately do not create metadata_dir as a side-effect here, since # this class is instantiated below when the module is loaded, and we # want to be able to test this module without the side-effect of it # affecting the system metadata directory. def _metadata_path(self, encoded_libvirt_image_name): return os.path.join(self.metadata_dir, encoded_libvirt_image_name) def __contains__(self, encoded_libvirt_image_name): return os.path.exists(self._metadata_path(encoded_libvirt_image_name)) def __delitem__(self, encoded_libvirt_image_name): os.unlink(self._metadata_path(encoded_libvirt_image_name)) def __setitem__(self, encoded_libvirt_image_name, metadata): mkdir_p(self.metadata_dir) with codecs.open( self._metadata_path(encoded_libvirt_image_name), 'wb', encoding='utf-8') as f: json.dump(metadata, f, indent=4) def __getitem__(self, encoded_libvirt_image_name): with codecs.open( self._metadata_path(encoded_libvirt_image_name), 'rb', encoding='utf-8') as f: return json.load(f) def keys(self): try: return os.listdir(self.metadata_dir) except OSError as e: if e.errno != errno.ENOENT: raise return [] def items(self): return [(key, self[key]) for key in self.keys()] pool_metadata = Metadata(METADATA_DIR) BASE64_PREFIX = 'x-uvt-b64-' def _encode_libvirt_pool_name(product_name, version_name): return BASE64_PREFIX + base64.b64encode( (' '.join([product_name, version_name])).encode(), b'-_' ) def _decode_libvirt_pool_name(encoded_pool_name): if not encoded_pool_name.startswith(BASE64_PREFIX): raise ValueError( "Volume name cannot be parsed for simplestreams identity: %s" % repr(encoded_pool_name) ) return base64.b64decode( encoded_pool_name[len(BASE64_PREFIX):], altchars=b'-_' ).split(None, 1) def purge_pool(conn=None): '''Delete all volumes and metadata with prejudice. This removes images from the pool whether they are in use or not. ''' # Remove all metadata first. If this is interrupted, then it just looks # like there are volumes waiting to be cleaned up. for key in pool_metadata.keys(): del pool_metadata[key] # Remove actual volumes themselves if conn is None: conn = libvirt.open('qemu:///system') pool = uvtool.libvirt.get_libvirt_pool_object(conn, LIBVIRT_POOL_NAME) for volume_name in pool.listVolumes(): volume = pool.storageVolLookupByName(volume_name) volume.delete(0) def clean_extraneous_images(): conn = libvirt.open('qemu:///system') pool = uvtool.libvirt.get_libvirt_pool_object(conn, LIBVIRT_POOL_NAME) encoded_libvirt_pool_names = uvtool.libvirt.volume_names_in_pool( LIBVIRT_POOL_NAME) volume_names_in_use = frozenset( uvtool.libvirt.get_all_domain_volume_names( filter_by_dir=IMAGE_DIR) ) for encoded_libvirt_name in encoded_libvirt_pool_names: if (encoded_libvirt_name not in volume_names_in_use and not encoded_libvirt_name in pool_metadata): uvtool.libvirt.delete_volume_by_name( encoded_libvirt_name, pool_name=LIBVIRT_POOL_NAME) def _load_products(path=None, content_id=None, clean=False): # If clean evaluates to True, then remove any metadata files for which # the corresponding volume is missing. def new_product(): return {'versions': {}} products = collections.defaultdict(new_product) for encoded_libvirt_name_string, metadata in pool_metadata.items(): encoded_libvirt_name_bytes = encoded_libvirt_name_string.encode( 'utf-8') if not uvtool.libvirt.have_volume_by_name( encoded_libvirt_name_bytes, pool_name=LIBVIRT_POOL_NAME): if clean: del pool_metadata[encoded_libvirt_name_string] continue product, version = _decode_libvirt_pool_name( encoded_libvirt_name_bytes) assert(product == metadata['product_name']) assert(version == metadata['version_name']) products[product]['versions'][version] = { 'items': { 'disk1.img': metadata } } return {'content_id': content_id, 'products': products} class LibvirtQuery(simplestreams.mirrors.BasicMirrorWriter): def __init__(self, filters): super(LibvirtQuery, self).__init__() self.filters = filters self.result = [] def load_products(self, path=None, content_id=None): return {'content_id': content_id, 'products': {}} def filter_item(self, data, src, target, pedigree): return simplestreams.filters.filter_item( self.filters, data, src, pedigree) def insert_item(self, data, src, target, pedigree, contentsource): product_name, version_name, item_name = pedigree self.result.append((product_name, version_name)) def query(filter_args): query = LibvirtQuery(simplestreams.filters.get_filters(filter_args)) query.sync_products(None, src=_load_products()) return (_encode_libvirt_pool_name(product_name, version_name) for product_name, version_name in query.result) class LibvirtMirror(simplestreams.mirrors.BasicMirrorWriter): def __init__(self, filters, verbose=False): super(LibvirtMirror, self).__init__({'max_items': 1}) self.filters = filters self.verbose = verbose def load_products(self, path=None, content_id=None): return _load_products(path=path, content_id=content_id, clean=True) def filter_index_entry(self, data, src, pedigree): return data['datatype'] == 'image-downloads' def filter_item(self, data, src, target, pedigree): return simplestreams.filters.filter_item( self.filters, data, src, pedigree) def insert_item(self, data, src, target, pedigree, contentsource): product_name, version_name, item_name = pedigree assert(item_name == 'disk1.img') if self.verbose: print("Adding: %s %s" % (product_name, version_name)) encoded_libvirt_name = _encode_libvirt_pool_name( product_name, version_name) if not uvtool.libvirt.have_volume_by_name( encoded_libvirt_name, pool_name=LIBVIRT_POOL_NAME): uvtool.libvirt.create_volume_from_fobj( encoded_libvirt_name, contentsource, image_type='qcow2', pool_name=LIBVIRT_POOL_NAME ) pool_metadata[encoded_libvirt_name] = ( simplestreams.util.products_exdata(src, pedigree) ) def remove_version(self, data, src, target, pedigree): product_name, version_name = pedigree if self.verbose: print("Removing: %s %s" % (product_name, version_name)) encoded_libvirt_name = _encode_libvirt_pool_name( product_name, version_name) del pool_metadata[encoded_libvirt_name] def main_sync(args): (mirror_url, initial_path) = simplestreams.util.path_from_mirror_url( args.mirror_url, args.path) def policy(content, path): if initial_path.endswith('sjson') and not args.no_authentication: return simplestreams.util.read_signed( content, keyring=args.keyring) else: return content smirror = simplestreams.mirrors.UrlMirrorReader( mirror_url, policy=policy) filter_list = simplestreams.filters.get_filters( ['datatype=image-downloads', 'ftype=disk1.img'] + args.filters ) tmirror = LibvirtMirror(filter_list, verbose=args.verbose) tmirror.sync(smirror, initial_path) clean_extraneous_images() def libvirt_pool_name_to_useful_description_string(libvirt_pool_name): volume_metadata = pool_metadata[libvirt_pool_name] filters = ' '.join('='.join((key, volume_metadata[key])) for key in USEFUL_FIELD_NAMES) return ' '.join([filters, '(%s)' % volume_metadata['version_name']]) def main_query(args): result = query(args.filters) useful_result = sorted(libvirt_pool_name_to_useful_description_string(r) for r in result) print(*useful_result, sep="\n") def main_purge(args): purge_pool() def main(argv=None): # Workaround for https://bugzilla.redhat.com/show_bug.cgi?id=1063766 # (LP: #1228231) libvirt.registerErrorHandler(lambda _: None, None) system_arch = subprocess.check_output( ['dpkg', '--print-architecture']).decode().strip() parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='store_true') subparsers = parser.add_subparsers() sync_subparser = subparsers.add_parser('sync') sync_subparser.set_defaults(func=main_sync) sync_subparser.add_argument( '--path', default=None, help='sync from index or products file in mirror' ) sync_subparser.add_argument( '--keyring', help='keyring to be specified to gpg via --keyring', default='/usr/share/keyrings/ubuntu-cloudimage-keyring.gpg' ) sync_subparser.add_argument('--source', dest='mirror_url', default='https://cloud-images.ubuntu.com/releases/') sync_subparser.add_argument('--no-authentication', action='store_true') sync_subparser.add_argument('filters', nargs='*', metavar='filter', default=["arch=%s" % system_arch]) query_subparser = subparsers.add_parser('query') query_subparser.set_defaults(func=main_query) query_subparser.add_argument( 'filters', nargs='*', default=[], metavar='filter') purge_subparser = subparsers.add_parser('purge') purge_subparser.set_defaults(func=main_purge) args = parser.parse_args(argv) args.func(args) if __name__ == '__main__': main() uvtool-0~bzr99/uvtool/tests/__init__.py0000644000000000000000000000000012512767613016572 0ustar 00000000000000uvtool-0~bzr99/uvtool/tests/streams/0000755000000000000000000000000012512767613016151 5ustar 00000000000000uvtool-0~bzr99/uvtool/tests/test_kvm.py0000644000000000000000000000411112512767613016676 0ustar 00000000000000# Copyright (C) 2014 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import unittest import mock from uvtool.libvirt.kvm import main_ssh class TestKVM(unittest.TestCase): def check_ssh(self, args_hostname, args_login_name, expected_hostname, expected_login_name): parser = mock.Mock() args = mock.Mock() args.login_name = args_login_name args.name = args_hostname args.ssh_arguments = mock.sentinel.ssh_arguments with mock.patch('uvtool.libvirt.kvm.ssh') as ssh_mock: main_ssh(parser, args) ssh_mock.assert_called_with( expected_hostname, expected_login_name, mock.sentinel.ssh_arguments ) def test_ssh_default(self): # "uvt-kvm ssh foo" should use user 'ubuntu' self.check_ssh('foo', None, 'foo', 'ubuntu') def test_ssh_override_with_l_option(self): # "uvt-kvm ssh -l bar foo" should use user 'bar' self.check_ssh('foo', 'bar', 'foo', 'bar') def test_ssh_override_with_at_sign(self): # "uvt-kvm ssh bar@foo" should use user 'bar' self.check_ssh('bar@foo', None, 'foo', 'bar') def test_ssh_override_and_at_in_hostname(self): # "uvt-kvm ssh -l baz bar@foo" # In this obtuse case, the hostname has an '@' in it, so this should be # passed through. self.check_ssh('bar@foo', 'baz', 'bar@foo', 'baz') uvtool-0~bzr99/uvtool/tests/test_simplestreams.py0000644000000000000000000001715212512767613021002 0ustar 00000000000000# Copyright (C) 2014 Canonical Ltd. # Author: Robie Basak # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import unittest import mock import uvtool.libvirt.simplestreams as simplestreams # Some tests use more recent features of mock that are not available with mock # 0.7.2-1 as shipped with Ubuntu Precise, but for the next six months, we still # want backports to be possible. Skip tests on builds that don't have a recent # enough version of mock available. Ideally, this would be a test directly for # the version of mock required, but I cannot find an implementation of # NormalizedVersion as described in PEP-0386. As this is a temporary hack # anyway, this will do for now, since we know that the mock version on Ubuntu # Precise will never change. ON_PRECISE = mock.__version__ == '0.7.2' FAKE_VOLUME_PRODUCT_NAME = 'com.ubuntu.cloud:server:12.04:amd64' FAKE_VOLUME_VERSION_0 = '20131119' FAKE_VOLUME_VERSION_1 = '20131120' ENCODED_FAKE_VOLUME_PRODUCT_NAME_0 = simplestreams._encode_libvirt_pool_name( FAKE_VOLUME_PRODUCT_NAME, FAKE_VOLUME_VERSION_0) ENCODED_FAKE_VOLUME_PRODUCT_NAME_1 = simplestreams._encode_libvirt_pool_name( FAKE_VOLUME_PRODUCT_NAME, FAKE_VOLUME_VERSION_1) @unittest.skipIf(ON_PRECISE, 'mock version is too old') @mock.patch('uvtool.libvirt.simplestreams.uvtool.libvirt') @mock.patch('uvtool.libvirt.simplestreams.pool_metadata', new={}) @mock.patch('uvtool.libvirt.simplestreams.libvirt') class TestSimpleStreams(unittest.TestCase): def testSync(self, libvirt, uvtool_libvirt): uvtool_libvirt.have_volume_by_name.return_value = False uvtool_libvirt.get_all_domain_volume_names.return_value = [] uvtool_libvirt.volume_names_in_pool.return_value = [ ENCODED_FAKE_VOLUME_PRODUCT_NAME_0] simplestreams.main( 'sync ' '--no-authentication ' '--source=uvtool/tests/streams/fake_stream_0 ' '--path streams/v1/index.json ' 'release=precise arch=amd64 ' .split() ) # Check that we have mocked libvirt correctly, which means that # this test is working. We expect libvirt.open to have been called at # least once by uvtool.libvirt.simplestreams directly. This is more of # an assertion about the test being correct than part of the test # itself. libvirt.assert_has_calls(mock.call.open(u'qemu:///system')) # create_volume_from_fobj should have been called exactly once to # create the volume with the name that we expect self.assertEqual(uvtool_libvirt.create_volume_from_fobj.call_count, 1) self.assertEqual( uvtool_libvirt.create_volume_from_fobj.call_args[0][0], ENCODED_FAKE_VOLUME_PRODUCT_NAME_0 ) # Make sure the only calls to uvtool.libvirt were ones that we have # either whitelisted to be query-only (no side effects), or that we # are checking already. This makes sure, for example, that we aren't # deleting any volumes that we aren't expecting to delete. for call in uvtool_libvirt.mock_calls: name = call[0] self.assertIn(name, [ # side effects that we have checked already 'get_all_domain_volume_names', # whitelist of query functions that produce no side effects 'create_volume_from_fobj', 'get_libvirt_pool_object', 'have_volume_by_name', 'volume_names_in_pool', ]) def _testResync(self, libvirt, uvtool_libvirt, old_volume_delete_expected, volumes_in_use=None): uvtool_libvirt.have_volume_by_name.side_effect = ( lambda name, **kwargs: name == ENCODED_FAKE_VOLUME_PRODUCT_NAME_0) if volumes_in_use: uvtool_libvirt.get_all_domain_volume_names.return_value = list( volumes_in_use) else: uvtool_libvirt.get_all_domain_volume_names.return_value = [] uvtool_libvirt.volume_names_in_pool.return_value = [ ENCODED_FAKE_VOLUME_PRODUCT_NAME_0] simplestreams.main( 'sync ' '--no-authentication ' '--source=uvtool/tests/streams/fake_stream_0 ' '--path streams/v1/index.json ' 'release=precise arch=amd64 ' .split() ) uvtool_libvirt.reset_mock() uvtool_libvirt.volume_names_in_pool.return_value = [ ENCODED_FAKE_VOLUME_PRODUCT_NAME_0] simplestreams.main( 'sync ' '--no-authentication ' '--source=uvtool/tests/streams/fake_stream_1 ' '--path streams/v1/index.json ' 'release=precise arch=amd64 ' .split() ) # create_volume_from_fobj should have been called exactly once to # create the volume with the name that we expect self.assertEqual(uvtool_libvirt.create_volume_from_fobj.call_count, 1) self.assertEqual( uvtool_libvirt.create_volume_from_fobj.call_args[0][0], ENCODED_FAKE_VOLUME_PRODUCT_NAME_1 ) if old_volume_delete_expected: # delete_volume_by_name should have been called exactly once to # delete the old volume that now has a new version self.assertEqual( uvtool_libvirt.delete_volume_by_name.call_count, 1) self.assertEqual( uvtool_libvirt.delete_volume_by_name.call_args[0][0], ENCODED_FAKE_VOLUME_PRODUCT_NAME_0 ) else: # delete_volume_by_name should not have been called at all self.assertEqual( uvtool_libvirt.delete_volume_by_name.call_count, 0) # Make sure the only calls to uvtool.libvirt were ones that we have # either whitelisted to be query-only (no side effects), or that we # are checking already. This makes sure, for example, that we aren't # deleting any volumes that we aren't expecting to delete. for call in uvtool_libvirt.mock_calls: name = call[0] self.assertIn(name, [ # delete volume checked already 'delete_volume_by_name', #'get_libvirt_pool_object().storageVolLookupByName().delete', # side effects that we have checked already 'get_all_domain_volume_names', # whitelist of query functions that produce no side effects 'create_volume_from_fobj', 'get_libvirt_pool_object', 'have_volume_by_name', 'volume_names_in_pool', #'get_libvirt_pool_object().storageVolLookupByName', ]) def testResync(self, libvirt, uvtool_libvirt): self._testResync(libvirt, uvtool_libvirt, True) def testResyncWithDomainUsingOldVolume(self, libvirt, uvtool_libvirt): self._testResync( libvirt, uvtool_libvirt, False, ['foo.qcow', 'foo-ds.qcow', ENCODED_FAKE_VOLUME_PRODUCT_NAME_0] ) uvtool-0~bzr99/uvtool/tests/streams/Makefile0000644000000000000000000000044112512767613017610 0ustar 00000000000000fake_stream_1: fake_stream_1.stamp fake_stream_1.stamp: fake_stream_1.patch rm -rf fake_stream_1 cp -a fake_stream_0 fake_stream_1 patch -p1 -dfake_stream_1 < fake_stream_1.patch touch fake_stream_1.stamp clean: rm -Rf fake_stream_1 fake_stream_1.stamp .PHONY: clean fake_stream_1 uvtool-0~bzr99/uvtool/tests/streams/fake_stream_0/0000755000000000000000000000000012512767613020651 5ustar 00000000000000uvtool-0~bzr99/uvtool/tests/streams/fake_stream_1.patch0000644000000000000000000000413712512767613021700 0ustar 00000000000000diff -urN fake_stream_0/fake_image fake_stream_1/fake_image diff -urN fake_stream_0/fake_image_1 fake_stream_1/fake_image_1 --- fake_stream_0/fake_image_1 1970-01-01 01:00:00.000000000 +0100 +++ fake_stream_1/fake_image_1 2013-11-19 11:02:27.000000000 +0000 @@ -0,0 +1 @@ +fake_image_1 diff -urN fake_stream_0/streams/v1/com.ubuntu.cloud:released:download.json fake_stream_1/streams/v1/com.ubuntu.cloud:released:download.json --- fake_stream_0/streams/v1/com.ubuntu.cloud:released:download.json 2013-11-19 10:45:43.000000000 +0000 +++ fake_stream_1/streams/v1/com.ubuntu.cloud:released:download.json 2013-11-19 11:06:59.000000000 +0000 @@ -1,5 +1,5 @@ { - "updated": "Tue, 19 Nov 2013 10:31:23 +0000", + "updated": "Tue, 20 Nov 2013 10:31:23 +0000", "license": "http://www.canonical.com/intellectual-property-policy", "format": "products:1.0", "datatype": "image-downloads", @@ -21,6 +21,19 @@ }, "pubname": "ubuntu-precise-12.04-amd64-server-20131119", "label": "release" + }, + "20131120": { + "items": { + "disk1.img": { + "size": 13, + "path": "fake_stream_1", + "ftype": "disk1.img", + "sha256": "cc4dea38d5e5db5e60a919c4957842141a264116bb848577a5c1a7db6ca3459c", + "md5": "fe1904b716301338e715ecb8545481f8" + } + }, + "pubname": "ubuntu-precise-12.04-amd64-server-20131120", + "label": "release" } } } diff -urN fake_stream_0/streams/v1/index.json fake_stream_1/streams/v1/index.json --- fake_stream_0/streams/v1/index.json 2013-11-19 11:00:01.000000000 +0000 +++ fake_stream_1/streams/v1/index.json 2013-11-19 11:01:02.000000000 +0000 @@ -3,13 +3,13 @@ "com.ubuntu.maas:download": { "datatype": "image-downloads", "path": "streams/v1/com.ubuntu.cloud:released:download.json", - "updated": "Tue, 19 Nov 2013 10:31:23 +0000", + "updated": "Tue, 20 Nov 2013 10:31:23 +0000", "products": [ "com.ubuntu.cloud:server:12.04:amd64" ], "format": "products:1.0" } }, - "updated": "Tue, 19 Nov 2013 10:31:23 +0000", + "updated": "Tue, 20 Nov 2013 10:31:23 +0000", "format": "index:1.0" } uvtool-0~bzr99/uvtool/tests/streams/fake_stream_0/fake_image_00000644000000000000000000000001312512767613023055 0ustar 00000000000000fake_image uvtool-0~bzr99/uvtool/tests/streams/fake_stream_0/streams/0000755000000000000000000000000012512767613022327 5ustar 00000000000000uvtool-0~bzr99/uvtool/tests/streams/fake_stream_0/streams/v1/0000755000000000000000000000000012512767613022655 5ustar 00000000000000uvtool-0~bzr99/uvtool/tests/streams/fake_stream_0/streams/v1/com.ubuntu.cloud:released:download.json0000644000000000000000000000141012512767613032371 0ustar 00000000000000{ "updated": "Tue, 19 Nov 2013 10:31:23 +0000", "license": "http://www.canonical.com/intellectual-property-policy", "format": "products:1.0", "datatype": "image-downloads", "products": { "com.ubuntu.cloud:server:12.04:amd64": { "release": "precise", "version": "12.04", "arch": "amd64", "versions": { "20131119": { "items": { "disk1.img": { "size": 11, "path": "fake_stream_0", "ftype": "disk1.img", "sha256": "520e579da0a29a08f73aaa018eed12b6778460ea446f442dedaa8a950674afda", "md5": "dd70deb9c14b77a35f1a4fb9e1485969" } }, "pubname": "ubuntu-precise-12.04-amd64-server-20131119", "label": "release" } } } }, "content_id": "com.ubuntu.cloud:released:download" } uvtool-0~bzr99/uvtool/tests/streams/fake_stream_0/streams/v1/index.json0000644000000000000000000000056512512767613024665 0ustar 00000000000000{ "index": { "com.ubuntu.maas:download": { "datatype": "image-downloads", "path": "streams/v1/com.ubuntu.cloud:released:download.json", "updated": "Tue, 19 Nov 2013 10:31:23 +0000", "products": [ "com.ubuntu.cloud:server:12.04:amd64" ], "format": "products:1.0" } }, "updated": "Tue, 19 Nov 2013 10:31:23 +0000", "format": "index:1.0" }