diff --git a/COPYRIGHT b/COPYRIGHT index bb1ba6a42633148ebd53dde58d7392a8300a459e..94a9ed024d3859793618152ea559a168bbcbb5e2 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -1,32 +1,674 @@ -Copyright 2012, 2013 GRNET S.A. All rights reserved. - -Redistribution and use in source and binary forms, with or -without modification, are permitted provided that the following -conditions are met: - - 1. Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and -documentation are those of the authors and should not be -interpreted as representing official policies, either expressed -or implied, of GRNET S.A. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + 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 GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/ChangeLog b/ChangeLog index 852b0eeda8a73ff59d8137b1f953112e63da57be..89f87d94ce8418f7aaea135a04ef23849a0ad15f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +2014-09-12, v0.7rc2 + * Support all QEMU supported disk image formats as input media + * Detect if a Windows input media is sysprepped + * Support VirtIO driver installation in Windows + * Do a major code cleanup + * Fix bugs + 2014-06-10, v0.6.2 * Add support for Ubuntu 14.04 * Fix a bug in Windows image creation diff --git a/MANIFEST.in b/MANIFEST.in index 321ef58cd7636e4a8f64e1b85c0d6e19e77b5c8a..f984a3d027502c1a2a293f0031c48fc18e5bdf50 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,4 @@ include image_creator/help/*.rst -include README COPYRIGHT AUTHORS ChangeLog +include README.md COPYRIGHT AUTHORS ChangeLog recursive-include docs * prune docs/_build diff --git a/README b/README deleted file mode 100644 index 6d6dacbe069fd84765e7f34d37f1d1706c87b9f1..0000000000000000000000000000000000000000 --- a/README +++ /dev/null @@ -1,9 +0,0 @@ -snf-image-creator -================= - -snf-image-creator is a command line tool for creating OS images to be used with -synnefo. - -It comes in 2 variants: - * snf-image-creator: A user-friendly dialog-based program - * snf-mkimage: A non-interactive command line program diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2b746c5549fb78df685624f12b0965bc0ecad26c --- /dev/null +++ b/README.md @@ -0,0 +1,39 @@ +snf-image-creator +================= + +Overview +-------- + +This is snf-image-creator, a command-line tool for creating OS Images to be +used with Synnefo. + +It comes in two variants: +* snf-image-creator: A user-friendly dialog-based program +* snf-mkimage: A non-interactive command-line program + +Project Page +------------ + +Please see the [official Synnefo site](http://www.synnefo.org) and the +[latest snf-image-creator docs](http://www.synnefo.org/docs/snf-image-creator/latest/index.html) +for more information. + + +Copyright and license +===================== + +Copyright (C) 2011-2014 GRNET S.A. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. + diff --git a/docs/index.rst b/docs/index.rst index e9a4e3defebc3854d849d2d37d067ddbb84a59ed..14c1cfd26ca4eb87867eb8544fc26f24da196919 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -6,7 +6,12 @@ Welcome to snf-image-creator's documentation! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -snf-image-creator is an image creation tool for `Synnefo <https://code.grnet.gr/projects/synnefo>`_ +This is snf-image-creator, a command-line tool for creating OS Images to be +used with `Synnefo <http://www.synnefo.org/>`_. + +It comes in two variants: + * snf-image-creator: A user-friendly dialog-based program + * snf-mkimage: A non-interactive command-line program Contents: diff --git a/docs/install.rst b/docs/install.rst index a7f303169bcc545f0f6539df461bebdd8150fccc..61ceb679ceef30db701d265c0e10438de62df577 100644 --- a/docs/install.rst +++ b/docs/install.rst @@ -44,31 +44,37 @@ Add the following line to */etc/apt/sources.list*: deb http://apt.dev.grnet.gr wheezy/ +Add the apt-dev GPG key to the list of trusted keys: + +.. code-block:: console + + # curl https://dev.grnet.gr/files/apt-grnetdev.pub | apt-key add - + And resynchronize the package index files from their sources: .. code-block:: console - $ sudo apt-get update + # apt-get update You should be able to list the package by calling: .. code-block:: console - $ apt-cache showpkg snf-image-creator + # apt-cache showpkg snf-image-creator And install the package with this command: .. code-block:: console - $ apt-get install snf-image-creator + # apt-get install snf-image-creator Ubuntu ------ -For *Ubuntu 12.04 LTS*, *12.10* and *13.04* systems, you can use our official +For *Ubuntu 12.04 LTS* and *14.04 LTS* systems, you can use our official packages found in *grnet/synnefo* Lauchpad PPA. -Add the synnefo PPA in your system: +Add the Synnefo PPA in your system: .. code-block:: console @@ -77,7 +83,7 @@ Add the synnefo PPA in your system: If *apt-add-repository* is missing, first install: -*software-properties-common* (Ubuntu 12.10 & 13.04): +*software-properties-common* (Ubuntu 14.04): .. code-block:: console @@ -89,7 +95,7 @@ Or *python-software-properties* (Ubuntu 12.04): $ sudo apt-get install python-software-properties -After the synnefo repository is set up, you should be able to list +After the Synnefo repository is set up, you should be able to list snf-image-creator by calling: .. code-block:: console @@ -109,27 +115,27 @@ Install the package by issuing: Fedora ------ -For *Fedora 17* you can use our official packages hosted at the *synnefo* +For *Fedora 20* you can use our official packages hosted at the *synnefo* repository of the openSUSE Build Service. -Add the *synnefo* repository for *Fedora 17* to *yum*: +Add the *synnefo* repository for *Fedora 20* to *yum*: .. code-block:: console - $ cd /etc/yum.repos.d - $ wget http://download.opensuse.org/repositories/home:/GRNET:/synnefo/Fedora_17/home:GRNET:synnefo.repo + # cd /etc/yum.repos.d + # wget http://download.opensuse.org/repositories/home:/GRNET:/synnefo/Fedora_20/home:GRNET:synnefo.repo To list the *snf-image-creator* package use the following command: .. code-block:: console - $ yum info snf-image-creator + # yum info snf-image-creator Install the package by issuing: .. code-block:: console - $ yum install snf-image-creator + # yum install snf-image-creator CentOS ------ @@ -141,41 +147,41 @@ Add the *synnefo* repository for *CentOS 6* to the yum repositories list: .. code-block:: console - $ cd /etc/yum.repos.d - $ wget http://download.opensuse.org/repositories/home:/GRNET:/synnefo/CentOS_CentOS-6/home:GRNET:synnefo.repo + # cd /etc/yum.repos.d + # wget http://download.opensuse.org/repositories/home:/GRNET:/synnefo/CentOS_CentOS-6/home:GRNET:synnefo.repo Check the `Fedora <#fedora>`_ instructions on how to install the software. -OpenSUSE +openSUSE -------- -For *OpenSUSE 12.3* you can use our official packages hosted at the *synnefo* -repository of the OpenSUSE Build Service. +For *openSUSE 13.1* you can use our official packages hosted at the *Synnefo* +repository of the openSUSE Build Service. -Add the *Virtualization* repository for *OpenSUSE 12.3* to *YaST* with the +Add the *Virtualization* repository for *openSUSE 13.1* to *YaST* with the *Zypper* package manager: .. code-block:: console - $ zypper ar -f http://download.opensuse.org/repositories/Virtualization/openSUSE_12.3/Virtualization.repo + # zypper ar -f http://download.opensuse.org/repositories/Virtualization/openSUSE_13.1/Virtualization.repo -Add the *synnefo* repository: +Add the *Synnefo* repository: .. code-block:: console - $ zypper ar -f http://download.opensuse.org/repositories/home:/GRNET:/synnefo/openSUSE_12.3/home:GRNET:synnefo.repo + # zypper ar -f http://download.opensuse.org/repositories/home:/GRNET:/synnefo/openSUSE_13.1/home:GRNET:synnefo.repo To list the *snf-image-creator* package use the following command: .. code-block:: console - $ zypper se snf-image-creator + # zypper se snf-image-creator Install the package by issuing: .. code-block:: console - $ zypper in snf-image-creator + # zypper in snf-image-creator Arch Linux @@ -200,13 +206,13 @@ the *yaourt* package: $ tar -xvf package-query.tar.gz $ cd package-query $ makepkg -s - $ pacman -U package-query-<VERSION>-<ARCH>.pkg.tar.xz + $ su -c 'pacman -U package-query-<VERSION>-<ARCH>.pkg.tar.xz' $ cd .. $ wget https://aur.archlinux.org/packages/ya/yaourt/yaourt.tar.gz $ tar -xvf yaourt.tar.gz $ cd yaourt $ makepkg -s - $ pacman -U yaourt-<VERSION>-<ARCH>.pkg.tar.xz + $ su -c 'pacman -U yaourt-<VERSION>-<ARCH>.pkg.tar.xz' Install *snf-image-creator* using yaourt: @@ -282,7 +288,7 @@ kamaki Installation ------------------- Refer to `./kamaki documentation <http://docs.dev.grnet.gr/kamaki/latest/installation.html>`_ -for instructions. You may install kamaki from source inside the virtualenv +for instructions. You may install *./kamaki* from source inside the virtualenv you've created above or by using binary packages if they are available for your distribution. @@ -309,7 +315,7 @@ cloning its git repository: $ python ./setup.py install To do the latter, you'll need to have git (http://git-scm.com/) installed. -For ubuntu this can be done using: +For Ubuntu this can be done using: .. code-block:: console diff --git a/docs/overview.rst b/docs/overview.rst index 0d57e0ef6fab740d73b4f86172a6db353afe9e41..f15bb67657f980f52a4fd2c972aaeb57dafa8079 100644 --- a/docs/overview.rst +++ b/docs/overview.rst @@ -2,8 +2,12 @@ Overview ^^^^^^^^ snf-image-creator is a simple command-line tool for creating OS images. The -original media the image is created from, can be a block device, a regular -file that represents a hard disk or the host system itself. +original media, the image is created from, can be: + + * a block device, representing a hard disk + * a disk image file, representing a hard disk (supports all image file formats + supported by QEMU) + * the host system itself Snapshotting ============ @@ -22,7 +26,7 @@ Those operations will: * Shrink the image * Clear out sensitive user data (passwords, ssh keys, history files, etc.) * Prepare the guest OS for being deployed on a virtual environment (change - device names, remove persistent net rules, etc.) + device names, remove persistent net rules, install VirtIO drivers, etc.) Creation ======== diff --git a/docs/usage.rst b/docs/usage.rst index d7caa1f23cb69b80830367703e93bb9da60b3455..3baafed1e5960110811bdd61d2dba11a2afcb6fc 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -17,7 +17,7 @@ snf-mkimage receives the following options: .. code-block:: console - $ snf-mkimage --help + # snf-mkimage --help Usage: snf-mkimage [options] <input_media> Options: @@ -49,14 +49,16 @@ snf-mkimage receives the following options: --disable-sysprep=SYSPREP prevent SYSPREP operation from running on the input media + --install-virtio=DIR install VirtIO drivers hosted under DIR (Windows only) --print-sysprep-params - print the needed sysprep parameters for this input - media + print the defined system preparation parameters for + this input media --sysprep-param=SYSPREP_PARAMS - Add KEY=VALUE system preparation parameter + add KEY=VALUE system preparation parameter --no-sysprep don't perform any system preparation operation - --no-shrink don't shrink any partition --public register image with the cloud as public + --allow-unsupported proceed with the image creation even if the media is + not supported --tmpdir=DIR create large temporary image files under DIR Most input options are self-describing. If you want to save a local copy of @@ -65,10 +67,9 @@ image to the storage service of a cloud, provide valid cloud API access info (by either using a token and a URL with *-t* and *-a* respectively, or a cloud name with *-c*) and a remote filename using *-u*. If you also want to register the image with the compute service of the cloud, in addition to *-u* provide a -registration name using *-r*. All images are -registered as *private*. Only the user that registers the image can create -VM's out of it. If you want the image to be visible by other user too, use the -*--public* option. +registration name using *-r*. All images are registered as *private*. Only the +user that registers the image can create VM's out of it. If you want the image +to be visible by other user too, use the *--public* option. By default, before extracting the image, snf-mkimage will perform a number of system preparation operations on the snapshot of the media and will @@ -81,69 +82,74 @@ input media. The user can enable or disable specific *syspreps*, using *-{enable,disable}-sysprep* options. The user may specify those options multiple times. -Running *snf-mkimage* with *--print-sysprep* on a raw file that hosts a -debian system, we print the following output: +Running *snf-mkimage* with *--print-sysprep* on a raw file that hosts an +Ubuntu system, will print the following output: .. _sysprep: .. code-block:: console - $ snf-mkimage --print-syspreps ubuntu.raw - snf-image-creator 0.6 - ===================== - Examining source media `ubuntu_hd.raw' ... looks like an image file - Snapshotting media source ... done - Enabling recovery proc - Launching helper VM (may take a while) ... done - Inspecting Operating System ... ubuntu - Mounting the media read-only ... done - Collecting image metadata ... done - Umounting the media ... done - - Enabled system preparation operations: - cleanup-cache: - Remove all regular files under /var/cache - - cleanup-log: - Empty all files under /var/log - - cleanup-passwords: - Remove all passwords and lock all user accounts - - cleanup-tmp: - Remove all files under /tmp and /var/tmp - - cleanup-userdata: - Delete sensitive userdata - - fix-acpid: - Replace acpid powerdown action scripts to immediately shutdown the - system without checking if a GUI is running. - - remove-persistent-net-rules: - Remove udev rules that will keep network interface names persistent - after hardware changes and reboots. Those rules will be created again - the next time the image runs. - - remove-swap-entry: - Remove swap entry from /etc/fstab. If swap is the last partition - then the partition will be removed when shrinking is performed. If the - swap partition is not the last partition in the disk or if you are not - going to shrink the image you should probably disable this. - - use-persistent-block-device-names: - Scan fstab & grub configuration files and replace all non-persistent - device references with UUIDs. - - Disabled system preparation operations: - cleanup-mail: - Remove all files under /var/mail and /var/spool/mail - - remove-user-accounts: - Remove all user accounts with id greater than 1000 - - - cleaning up ... + # snf-mkimage --print-syspreps ubuntu.raw + + snf-image-creator 0.7 + =========================== + Examining source media `ubuntu.raw' ... looks like an image file + Snapshotting media source ... done + Enabling recovery proc + Launching helper VM (may take a while) ... done + Inspecting Operating System ... ubuntu + Collecting image metadata ... done + + Running OS inspection: + Checking if the media contains logical volumes (LVM)... no + + Enabled system preparation operations: + cleanup-tmp: + Remove all files under /tmp and /var/tmp + + remove-swap-entry: + Remove swap entry from /etc/fstab. If swap is the last partition + then the partition will be removed when shrinking is performed. If the + swap partition is not the last partition in the disk or if you are not + going to shrink the image you should probably disable this. + + cleanup-cache: + Remove all regular files under /var/cache + + cleanup-userdata: + Delete sensitive user data + + cleanup-passwords: + Remove all passwords and lock all user accounts + + cleanup-log: + Empty all files under /var/log + + remove-persistent-net-rules: + Remove udev rules that will keep network interface names persistent + after hardware changes and reboots. Those rules will be created again + the next time the image runs. + + use-persistent-block-device-names: + Scan fstab & grub configuration files and replace all non-persistent + device references with UUIDs. + + fix-acpid: + Replace acpid powerdown action scripts to immediately shutdown the + system without checking if a GUI is running. + + shrink: + Shrink the last file system and update the partition table + + Disabled system preparation operations: + remove-user-accounts: + Remove all user accounts with id greater than 1000 + + cleanup-mail: + Remove all files under /var/mail and /var/spool/mail + + + cleaning up ... If you want the image to have all normal user accounts and all mail files removed, you should use *--enable-sysprep* option like this: @@ -152,6 +158,15 @@ removed, you should use *--enable-sysprep* option like this: $ snf-mkimage --enable-sysprep cleanup-mail --enable-sysprep remove-user-accounts ... +Sysprep parameters are parameters used by some sysprep tasks. In most cases you +don't need to change their value. You can see the available sysprep parameters +and the default values they have by using the *--print-sysprep-params* option. +You can update their values by using the *--sysprep-param* option. + +If the media is a Windows image, you can install or update its VirtIO drivers +by using the *--install-virtio* option. With this option you can point to a +directory that hosts a set of extracted Windows VirtIO drivers. + Dialog-based version ==================== @@ -159,7 +174,7 @@ Dialog-based version .. code-block:: console - $ snf-image-creator --help + # snf-image-creator --help Usage: snf-image-creator [options] [<input_media>] Options: @@ -184,13 +199,14 @@ be given the choice to run *snf-image-creator* in *wizard* or *expert* mode. Wizard mode ----------- -When *snf-image-creator* runs in *wizard* mode, the user is just asked to provide the -following basic information: +When *snf-image-creator* runs in *wizard* mode, the user is just asked to +provide the following basic information: * Cloud: The cloud account to use to upload and register the resulting image * Name: A short name for the image (ex. "Slackware") * Description: An one-line description for the image (ex. "Slackware Linux 14.0 with KDE") + * VirtIO: A directory that hosts VirtIO drivers (for Windows images only) * Registration Type: Private or Public After confirming, the image will be extracted, uploaded to the storage service @@ -209,8 +225,8 @@ process. The main menu can be seen in the picture below: In the *Customize* sub-menu the user can control: + * The installation of VirtIO drivers (only for Windows images) * The system preparation operations that will be applied on the media - * Whether the image will be shrunk or not * The properties associated with the image * The configuration tasks that will run during image deployment @@ -229,12 +245,12 @@ Host bundling operation ======================= As a new feature in *v0.2*, snf-image-creator can create images out of the host -system that runs the program. This is done either by specifying / as input -media or by using the *Bundle Host* button in the media selection dialog of -snf-mkimage. During this operation, the files of the disk are copied into a -temporary image file, which means that the file system that will host the -temporary image needs to have a lot of free space (see `large temporary files`_ -for more information). +system that runs the program. This is done either by specifying */* as input +media or by using the *Bundle Host* button in the media selection dialog. +During this operation, the files of the disk are copied into a temporary image +file, which means that the file system that will host the temporary image needs +to have a lot of free space (see `large temporary files`_ for more +information). Creating a new image ==================== @@ -272,19 +288,19 @@ And install the Ubuntu system on this file: use LVM partitions. They are not supported by snf-image-creator. You will be able to boot your installed OS and make any changes you want -(e.g. install openssh-server) using the following command: +(e.g. install OpenSSH Server) using the following command: .. code-block:: console $ sudo kvm -m 1G -boot c -drive file=ubuntu.raw,format=raw,cache=none,if=virtio -After you're done, you may use *snf-image-creator* as root to create and upload the -image: +After you're done, you may use *snf-image-creator* as root to create and upload +the image: .. code-block:: console $ sudo -s - $ snf-image-creator ubuntu.raw + # snf-image-creator ubuntu.raw In the first screen you will be asked to choose if you want to run the program in *Wizard* or *Expert* mode. Choose *Wizard*. @@ -299,6 +315,21 @@ confirm the provided data. Choosing *YES* will create and upload the image to your cloud account. +Working with different image formats +==================================== + +*snf-image-creator* is able to work with the most popular disk image formats. +It has been successfully tested with: + +* Raw disk images +* VMDK (VMware) +* VHD (Microsoft Hyper-V) +* VDI (VirtualBox) +* qcow2 (QEMU) + +It can support any image format QEMU supports as long as it represents a +bootable hard drive. + Limitations =========== @@ -315,12 +346,12 @@ Logical Volumes --------------- The program cannot work on input media that contain LVM partitions inside -[#f1]_. The input media may only contain primary or logical partitions. +[#f2]_. The input media may only contain primary or logical partitions. Para-virtualized drivers ------------------------ -Most synnefo deployments uses the *VirtIO* framework. The disk I/O controller +Most Synnefo deployments uses the *VirtIO* framework. The disk I/O controller and the Ethernet cards on the VM instances are para-virtualized and need special *VirtIO* drivers. Those drivers are included in the Linux Kernel mainline since version 2.6.25 and are shipped with all the popular Linux @@ -331,18 +362,15 @@ ramdisk, otherwise the VM won't be able to boot. Many popular Linux distributions, like Ubuntu and Debian, will automatically create a generic initial ramdisk file that contains many different modules, including the VirtIO drivers. Others that target more experienced users, like -Slackware, won't do that [#f2]_. *snf-image-creator* cannot resolve this kind +Slackware, won't do that [#f3]_. *snf-image-creator* cannot resolve this kind of problems and it's left to the user to do so. Please refer to your distribution's documentation for more information on this. You can always check if a system can boot with para-virtualized disk controller by launching it with kvm using the *if=virtio* option (see the kvm command in the `Creating a new image`_ section). -For Windows and FreeBSD systems, the needed drivers need to be manually -downloaded and installed on the media before the image creation process takes -place. For *FreeBSD* the virtio drivers can be found -`here <http://people.freebsd.org/~kuriyama/virtio/>`_. For Windows the drivers -are hosted by the +For Windows the program supports installing VirtIO drivers. You may download +the latest drivers from the `Fedora Project <http://alt.fedoraproject.org/pub/alt/virtio-win/latest/images/>`_. Some caveats on image creation @@ -372,19 +400,20 @@ Large temporary files * During image shrinking, the input media snapshot file may reach the size of the original media. - * When bundling the host system, the temporary image file may became as large - as the rest of the disk files altogether. + * When bundling the host system, the temporary image file may became 10% + larger than rest of the disk files altogether. */tmp* directory is not a good place for hosting large files. In many systems -the contents of */tmp* are stored in volatile memory and the size they may occupy -is limited. By default, *snf-image-creator* will use a heuristic approach to -determine where to store large temporary files. It will examine the free space -under */var/tmp*, the user's home directory and */mnt* and will pick the one -with the most available space. The user may overwrite this behaviour and +the contents of */tmp* are stored in volatile memory and the size they may +occupy is limited. By default, *snf-image-creator* will use a heuristic +approach to determine where to store large temporary files. It will examine the +free space under */var/tmp*, the user's home directory and */mnt* and will pick +the one with the most available space. The user may overwrite this behavior and indicate a different directory using the *tmpdir* option. This option is supported by both *snf-image-creator* and *snf-mkimage*. .. rubric:: Footnotes -.. [#f1] http://sourceware.org/lvm2/ -.. [#f2] http://mirrors.slackware.com/slackware/slackware-14.0/README.initrd +.. [#f1] http://technet.microsoft.com/en-us/library/bb676673.aspx +.. [#f2] http://sourceware.org/lvm2/ +.. [#f3] http://mirrors.slackware.com/slackware/slackware-14.0/README.initrd diff --git a/image_creator/__init__.py b/image_creator/__init__.py index 06d6eccdad78229a40811e167d8cabf4249b2744..3d7fe8335fca437b4b325db4538baabb0bde0039 100644 --- a/image_creator/__init__.py +++ b/image_creator/__init__.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """Package for creating images to be used with Synnefo open source cloud software. diff --git a/image_creator/bundle_volume.py b/image_creator/bundle_volume.py index 772e5043d070abea089f0c92f21ac54c480c6444..51b7fd14529991a94d51be88b7d1f2bb3a170d88 100644 --- a/image_creator/bundle_volume.py +++ b/image_creator/bundle_volume.py @@ -1,39 +1,21 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. -"""This module hosts the code that performes the host bundling operation. By +"""This module hosts the code that performs the host bundling operation. By using the create_image method of the BundleVolume class the user can create an image out of the running system. """ @@ -115,7 +97,7 @@ class BundleVolume(object): yield FileSystemTableEntry(*entry) def _get_root_partition(self): - """Return the fstab entry accosiated with the root filesystem""" + """Return the fstab entry associated with the root file system""" for entry in self._read_fstable('/etc/fstab'): if entry.mpoint == '/': return entry.dev @@ -144,8 +126,8 @@ class BundleVolume(object): """Copy the partition table of the host system into the image""" # Copy the MBR and the space between the MBR and the first partition. - # In msdos partition tables Grub Stage 1.5 is located there. - # In gpt partition tables the Primary GPT Header is there. + # In MSDOS partition tables GRUB Stage 1.5 is located there. + # In GUID partition tables the Primary GPT Header is there. first_sector = self.disk.getPrimaryPartitions()[0].geometry.start dd('if=%s' % self.disk.device.path, 'of=%s' % image, @@ -286,7 +268,7 @@ class BundleVolume(object): try_fail_repeat(dmsetup, 'remove', dev.split('/dev/mapper/')[1]) def _mount(self, target, devs): - """Mount a list of filesystems in mountpoints relative to target""" + """Mount a list of file systems in mount points relative to target""" devs.sort(key=lambda d: d[1]) for dev, mpoint, options in devs: absmpoint = os.path.abspath(target + mpoint) @@ -299,7 +281,7 @@ class BundleVolume(object): mount(dev, absmpoint) def _umount_all(self, target): - """Unmount all filesystems that are mounted under the directory target + """Umount all file systems that are mounted under the target directory """ mpoints = [] for entry in self._read_fstable('/proc/mounts'): @@ -312,7 +294,7 @@ class BundleVolume(object): def _to_exclude(self): """Find which directories to exclude during the image copy. This is - accompliced by checking which directories serve as mount points for + accomplished by checking which directories serve as mount points for virtual file systems """ excluded = ['/tmp', '/var/tmp'] @@ -350,7 +332,7 @@ class BundleVolume(object): def _replace_uuids(self, target, new_uuid): """Replace UUID references in various files. This is needed after - copying system files of the host into a new filesystem + copying system files of the host into a new file system """ files = ['/etc/fstab', @@ -372,8 +354,8 @@ class BundleVolume(object): lines = src.readlines() with open(f, 'w') as dest: for line in lines: - for i, uuid in new_uuid.items(): - line = re.sub(orig[i], uuid, line) + for i, new in new_uuid.items(): + line = re.sub(orig[i], new, line) dest.write(line) def _create_filesystems(self, image, partitions): @@ -413,8 +395,8 @@ class BundleVolume(object): # Create the file systems for i, dev in mapped.iteritems(): fs = filesystem[i].fs - self.out.output('Creating %s filesystem on partition %d ... ' % - (fs, i), False) + self.out.output('Creating %s file system on partition %d ... ' + % (fs, i), False) get_command('mkfs.%s' % fs)(*(MKFS_OPTS[fs] + [dev])) # For ext[234] enable the default mount options @@ -455,10 +437,9 @@ class BundleVolume(object): rsync.archive().hard_links().xattrs().sparse().acls() rsync.run('/', target, 'host', 'temporary image') - # Create missing mountpoints. Since they are mountpoints, we - # cannot determine the ownership and the mode of the real - # directory. Make them inherit those properties from their - # parent dir + # Create missing mount points. We cannot determine the + # ownership and the mode of the real directory. Make them + # inherit those properties from their parent directory. for excl in excluded: dirname = os.path.dirname(excl) stat = os.stat(dirname) @@ -467,7 +448,7 @@ class BundleVolume(object): os.chown(target + excl, stat.st_uid, stat.st_gid) # /tmp and /var/tmp are special cases. We exclude then even if - # they aren't mountpoints. Restore their permissions. + # they aren't mount points. Restore their permissions. for excl in ('/tmp', '/var/tmp'): if self._is_mpoint(excl): os.chmod(target + excl, 041777) @@ -477,9 +458,9 @@ class BundleVolume(object): os.chmod(target + excl, stat.st_mode) os.chown(target + excl, stat.st_uid, stat.st_gid) - # We need to replace the old UUID referencies with the new - # ones in grub configuration files and /etc/fstab for file - # systems that have been recreated. + # We need to replace the old UUID references with the new ones + # in GRUB configuration files and /etc/fstab for file systems + # that have been recreated. self._replace_uuids(target, new_uuid) finally: @@ -513,7 +494,7 @@ class BundleVolume(object): ptable = GPTPartitionTable(image) size = ptable.shrink(size, old_size) else: - # Alighn to 2048 + # Align to 2048 end_sector = ((end_sector + 2047) // 2048) * 2048 size = (end_sector + 1) * self.disk.device.sectorSize diff --git a/image_creator/dialog_main.py b/image_creator/dialog_main.py index 2a56a1c2a0238a39c6d1516a7e16cc2dd1573d8f..2177aaf96b43d19fe4c28871128940eb08be8e7d 100644 --- a/image_creator/dialog_main.py +++ b/image_creator/dialog_main.py @@ -1,38 +1,20 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module is the entrance point for the dialog-based version of the snf-image-creator program. The main function will create a dialog where the @@ -42,11 +24,12 @@ user is asked if he wants to use the program in expert or wizard mode. import dialog import sys import os -import stat import textwrap import signal import optparse import types +import termios +import traceback from image_creator import __version__ as version from image_creator.util import FatalError @@ -57,11 +40,13 @@ from image_creator.output.composite import CompositeOutput from image_creator.disk import Disk from image_creator.dialog_wizard import start_wizard from image_creator.dialog_menu import main_menu -from image_creator.dialog_util import SMALL_WIDTH, WIDTH, confirm_exit, \ - Reset, update_background_title +from image_creator.dialog_util import WIDTH, confirm_exit, Reset, \ + update_background_title, select_file + +PROGNAME = os.path.basename(sys.argv[0]) -def create_image(d, media, out, tmp): +def create_image(d, media, out, tmp, snapshot): """Create an image out of `media'""" d.setBackgroundTitle('snf-image-creator') @@ -76,8 +61,10 @@ def create_image(d, media, out, tmp): signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) try: - snapshot = disk.snapshot() - image = disk.get_image(snapshot) + + device = disk.file if not snapshot else disk.snapshot() + + image = disk.get_image(device) out.output("Collecting image metadata ...") metadata = {} @@ -123,11 +110,11 @@ def create_image(d, media, out, tmp): msg = "snf-image-creator detected a %s system on the input media. " \ "Would you like to run a wizard to assist you through the " \ "image creation process?\n\nChoose <Wizard> to run the wizard," \ - " <Expert> to run the snf-image-creator in expert mode or " \ - "press ESC to quit the program." \ - % (image.ostype if image.ostype == image.distro or + " <Expert> to run snf-image-creator in expert mode or press " \ + "ESC to quit the program." \ + % (image.ostype.capitalize() if image.ostype == image.distro or image.distro == "unknown" else "%s (%s)" % - (image.ostype, image.distro)) + (image.ostype.capitalize(), image.distro.capitalize())) update_background_title(session) @@ -151,38 +138,6 @@ def create_image(d, media, out, tmp): return 0 -def select_file(d, media): - """Select a media file""" - if media == '/': - return '/' - - default = os.getcwd() + os.sep - while 1: - if media is not None: - if not os.path.exists(media): - d.msgbox("The file `%s' you choose does not exist." % media, - width=SMALL_WIDTH) - else: - mode = os.stat(media).st_mode - if not stat.S_ISDIR(mode): - break - default = media - - (code, media) = d.fselect(default, 10, 60, extra_button=1, - title="Please select an input media.", - extra_label="Bundle Host") - if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): - if confirm_exit(d, "You canceled the media selection dialog box."): - sys.exit(0) - else: - media = None - continue - elif code == d.DIALOG_EXTRA: - return '/' - - return media - - def _dialog_form(self, text, height=20, width=60, form_height=15, fields=[], **kwargs): """Display a form box. @@ -205,7 +160,7 @@ def _dialog_form(self, text, height=20, width=60, form_height=15, fields=[], item = field[1] item_len = field[2] cmd.extend((label, str(line), str(1), item, str(line), - str(label_len + 1), str(input_len), str(item_len))) + str(label_len + 1), str(input_len), str(item_len))) line += 1 code, output = self._perform(*(cmd,), **kwargs) @@ -216,9 +171,9 @@ def _dialog_form(self, text, height=20, width=60, form_height=15, fields=[], return (code, output.splitlines()) -def main(): +def dialog_main(media, logfile, tmpdir, snapshot): - # In OpenSUSE dialog is buggy under xterm + # In openSUSE dialog is buggy under xterm if os.environ['TERM'] == 'xterm': os.environ['TERM'] = 'linux' @@ -227,14 +182,12 @@ def main(): # Add extra button in dialog library dialog._common_args_syntax["extra_button"] = \ lambda enable: dialog._simple_option("--extra-button", enable) - dialog._common_args_syntax["extra_label"] = \ lambda string: ("--extra-label", string) # Allow yes-no label overwriting dialog._common_args_syntax["yes_label"] = \ lambda string: ("--yes-label", string) - dialog._common_args_syntax["no_label"] = \ lambda string: ("--no-label", string) @@ -242,61 +195,95 @@ def main(): if not hasattr(dialog, 'form'): d.form = types.MethodType(_dialog_form, d) + d.setBackgroundTitle('snf-image-creator') + + try: + while True: + media = select_file(d, init=media, ftype="br", bundle_host=True, + title="Please select an input media.") + if media is None: + if confirm_exit( + d, "You canceled the media selection dialog box."): + return 0 + continue + break + + log = SimpleOutput(False, logfile) if logfile is not None else Output() + while 1: + try: + out = CompositeOutput([log]) + out.output("Starting %s v%s ..." % (PROGNAME, version)) + return create_image(d, media, out, tmpdir, snapshot) + except Reset: + log.output("Resetting everything ...") + continue + except FatalError as error: + msg = textwrap.fill(str(error), width=WIDTH-4) + d.infobox(msg, width=WIDTH, title="Fatal Error") + return 1 + + +def main(): + """Entrance Point""" + if os.geteuid() != 0: + sys.stderr.write("Error: You must run %s as root\n" % PROGNAME) + sys.exit(2) + usage = "Usage: %prog [options] [<input_media>]" parser = optparse.OptionParser(version=version, usage=usage) parser.add_option("-l", "--logfile", type="string", dest="logfile", default=None, help="log all messages to FILE", metavar="FILE") + parser.add_option("--no-snapshot", dest="snapshot", default=True, + help="don't snapshot the input media. (THIS IS " + "DANGEROUS AS IT WILL ALTER THE ORIGINAL MEDIA!!!)", + action="store_false") parser.add_option("--tmpdir", type="string", dest="tmp", default=None, help="create large temporary image files under DIR", metavar="DIR") - options, args = parser.parse_args(sys.argv[1:]) + opts, args = parser.parse_args(sys.argv[1:]) if len(args) > 1: parser.error("Wrong number of arguments") - d.setBackgroundTitle('snf-image-creator') - - try: - if os.geteuid() != 0: - raise FatalError("You must run %s as root" % - parser.get_prog_name()) + media = args[0] if len(args) == 1 else None - if options.tmp is not None and not os.path.isdir(options.tmp): - raise FatalError("The directory `%s' specified with --tmpdir is " - "not valid" % options.tmp) + if opts.tmp is not None and not os.path.isdir(opts.tmp): + parser.error("Directory: `%s' specified with --tmpdir is not valid" + % opts.tmp) - logfile = None - if options.logfile is not None: - try: - logfile = open(options.logfile, 'w') - except IOError as e: - raise FatalError( - "Unable to open logfile `%s' for writing. Reason: %s" % - (options.logfile, e.strerror)) - - media = select_file(d, args[0] if len(args) == 1 else None) + try: + logfile = open(opts.logfile, 'w') if opts.logfile is not None else None + except IOError as error: + parser.error("Unable to open logfile `%s' for writing. Reason: %s" % + (opts.logfile, error.strerror)) + try: + # Save the terminal attributes + attr = termios.tcgetattr(sys.stdin.fileno()) try: - log = SimpleOutput(False, logfile) if logfile is not None \ - else Output() - while 1: - try: - out = CompositeOutput([log]) - out.output("Starting %s v%s ..." % - (parser.get_prog_name(), version)) - ret = create_image(d, media, out, options.tmp) - sys.exit(ret) - except Reset: - log.output("Resetting everything ...") - continue + ret = dialog_main(media, logfile, opts.tmp, opts.snapshot) finally: - if logfile is not None: - logfile.close() - except FatalError as e: - msg = textwrap.fill(str(e), width=WIDTH) - d.infobox(msg, width=WIDTH, title="Fatal Error") - sys.exit(1) + # Restore the terminal attributes. If an error occurs make sure + # that the terminal turns back to normal. + termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, attr) + except: + # Clear the screen + sys.stdout.write('\033[2J') # Erase Screen + sys.stdout.write('\033[H') # Cursor Home + sys.stdout.flush() + + exception = traceback.format_exc() + sys.stderr.write(exception) + if logfile is not None: + logfile.write(exception) + + sys.exit(3) + finally: + if logfile is not None: + logfile.close() + + sys.exit(ret) # vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/dialog_menu.py b/image_creator/dialog_menu.py index 4f24b1e008420faf53d9353665f82c4a374249e9..0731cb4700cf7ec50d566ae21e0efb073ecab918 100644 --- a/image_creator/dialog_menu.py +++ b/image_creator/dialog_menu.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module implements the "expert" mode of the dialog-based version of snf-image-creator. @@ -41,29 +23,31 @@ import os import textwrap import StringIO import json +import re +import time from image_creator import __version__ as version -from image_creator.util import MD5, FatalError +from image_creator.util import FatalError, virtio_versions from image_creator.output.dialog import GaugeOutput, InfoBoxOutput from image_creator.kamaki_wrapper import Kamaki, ClientError from image_creator.help import get_help_file from image_creator.dialog_util import SMALL_WIDTH, WIDTH, \ update_background_title, confirm_reset, confirm_exit, Reset, \ - extract_image, extract_metadata_string, add_cloud, edit_cloud + extract_image, add_cloud, edit_cloud, update_sysprep_param CONFIGURATION_TASKS = [ ("Partition table manipulation", ["FixPartitionTable"], - ["linux", "windows"]), + ["linux", "windows"]), ("File system resize", - ["FilesystemResizeUnmounted", "FilesystemResizeMounted"], - ["linux", "windows"]), + ["FilesystemResizeUnmounted", "FilesystemResizeMounted"], + ["linux", "windows"]), ("Swap partition configuration", ["AddSwap"], ["linux"]), ("SSH keys removal", ["DeleteSSHKeys"], ["linux"]), ("Temporal RDP disabling", ["DisableRemoteDesktopConnections"], - ["windows"]), + ["windows"]), ("SELinux relabeling at next boot", ["SELinuxAutorelabel"], ["linux"]), ("Hostname/Computer Name assignment", ["AssignHostname"], - ["windows", "linux"]), + ["windows", "linux"]), ("Password change", ["ChangePassword"], ["windows", "linux"]), ("File injection", ["EnforcePersonality"], ["windows", "linux"]) ] @@ -76,13 +60,14 @@ class MetadataMonitor(object): def __init__(self, session, meta): self.session = session self.meta = meta + self.old = {} def __enter__(self): self.old = {} for (k, v) in self.meta.items(): self.old[k] = v - def __exit__(self, type, value, traceback): + def __exit__(self, exc_type, exc_val, exc_tb): d = self.session['dialog'] altered = {} @@ -118,8 +103,6 @@ def upload_image(session): """Upload the image to the storage service""" d = session["dialog"] image = session['image'] - meta = session['metadata'] - size = image.size if "account" not in session: d.msgbox("You need to select a valid cloud before you can upload " @@ -129,8 +112,8 @@ def upload_image(session): while 1: if 'upload' in session: init = session['upload'] - elif 'OS' in meta: - init = "%s.diskdump" % meta['OS'] + elif 'OS' in session['metadata']: + init = "%s.diskdump" % session['metadata']['OS'] else: init = "" (code, answer) = d.inputbox("Please provide a filename:", init=init, @@ -166,16 +149,16 @@ def upload_image(session): kamaki.out = out try: if 'checksum' not in session: - md5 = MD5(out) - session['checksum'] = md5.compute(image.device, size) + session['checksum'] = image.md5() try: # Upload image file - with open(image.device, 'rb') as f: - session["pithos_uri"] = \ - kamaki.upload(f, size, filename, - "Calculating block hashes", - "Uploading missing blocks") + with image.raw_device() as raw: + with open(raw, 'rb') as f: + session["pithos_uri"] = \ + kamaki.upload(f, image.size, filename, + "Calculating block hashes", + "Uploading missing blocks") # Upload md5sum file out.output("Uploading md5sum file ...") md5str = "%s %s\n" % (session['checksum'], filename) @@ -222,9 +205,8 @@ def register_image(session): session['metadata'] else "" while 1: - fields = [ - ("Registration name:", name, 60), - ("Description (optional):", description, 80)] + fields = [("Registration name:", name, 60), + ("Description (optional):", description, 80)] (code, output) = d.form( "Please provide the following registration info:", height=11, @@ -241,14 +223,13 @@ def register_image(session): d.msgbox("Registration name cannot be empty", width=SMALL_WIDTH) continue - ret = d.yesno("Make the image public?\\nA public image is accessible " - "by every user of the service.", defaultno=1, - width=WIDTH) - if ret not in (0, 1): + answer = d.yesno("Make the image public?\\nA public image is " + "accessible by every user of the service.", + defaultno=1, width=WIDTH) + if answer not in (0, 1): continue - is_public = True if ret == 0 else False - + is_public = (answer == 0) break session['metadata']['DESCRIPTION'] = description @@ -283,8 +264,8 @@ def register_image(session): kamaki.share("%s.meta" % session['upload']) kamaki.share("%s.md5sum" % session['upload']) out.success('done') - except ClientError as e: - d.msgbox("Error in storage service client: %s" % e.message) + except ClientError as error: + d.msgbox("Error in storage service client: %s" % error.message) return False finally: out.remove(gauge) @@ -352,8 +333,8 @@ def delete_clouds(session): d.msgbox("Nothing selected!", width=SMALL_WIDTH) return False - if not d.yesno("Are you sure you want to remove the selected cloud " - "accounts?", width=WIDTH, defaultno=1): + if not d.yesno("Are you sure you want to remove the selected accounts?", + width=WIDTH, defaultno=1): for i in to_delete: Kamaki.remove_cloud(i) if 'cloud' in session and session['cloud'] == i: @@ -388,13 +369,14 @@ def kamaki_menu(session): if 'account' not in session and 'cloud' in session: cloud += " <invalid>" - upload = session["upload"] if "upload" in session else "<none>" - choices = [("Add/Edit", "Add/Edit cloud accounts"), ("Delete", "Delete existing cloud accounts"), ("Cloud", "Select cloud account to use: %s" % cloud), - ("Upload", "Upload image to the cloud"), - ("Register", "Register image with the cloud: %s" % upload)] + ("Upload", "Upload image to the cloud")] + + if 'upload' in session: + choices.append(("Register", "Register image with the cloud: %s" + % session['upload'])) (code, choice) = d.menu( text="Choose one of the following or press <Back> to go back.", @@ -471,9 +453,11 @@ def add_property(session): """Add a new property to the image""" d = session['dialog'] + regexp = re.compile('^[A-Za-z_]+$') + while 1: - (code, answer) = d.inputbox("Please provide a name for a new image" - " property:", width=WIDTH) + (code, answer) = d.inputbox("Please provide a case-insensitive name " + "for a new image property:", width=WIDTH) if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): return False @@ -482,11 +466,22 @@ def add_property(session): d.msgbox("A property name cannot be empty", width=SMALL_WIDTH) continue + if not re.match(regexp, name): + d.msgbox("Allowed characters for name: [a-zA-Z0-9_]", width=WIDTH) + continue + + # Image properties are case-insensitive + name = name.upper() + + if name in session['metadata']: + d.msgbox("Image property: `%s' already exists" % name, width=WIDTH) + continue + break while 1: (code, answer) = d.inputbox("Please provide a value for image " - "property %s" % name, width=WIDTH) + "property: `%s'" % name, width=WIDTH) if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): return False @@ -534,30 +529,37 @@ def modify_properties(session): continue (code, choice) = d.menu( - "In this menu you can edit existing image properties or add new " - "ones. Be careful! Most properties have special meaning and " - "alter the image deployment behaviour. Press <HELP> to see more " - "information about image properties. Press <BACK> when done.", - height=18, width=WIDTH, choices=choices, menu_height=10, - ok_label="Edit", extra_button=1, extra_label="Add", cancel="Back", - help_button=1, title="Image Properties") + "In this menu you can edit and delete existing image properties " + "or add new ones. Be careful! Most properties have special " + "meaning and alter the image deployment behavior. Press <HELP> to " + "see more information about image properties. Press <BACK> when " + "done.", height=18, width=WIDTH, choices=choices, menu_height=10, + ok_label="Edit/Del", extra_button=1, extra_label="Add", + cancel="Back", help_button=1, title="Image Properties") if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): return True # Edit button elif code == d.DIALOG_OK: - (code, answer) = d.inputbox("Please provide a new value for the " - "image property with name `%s':" % - choice, - init=session['metadata'][choice], - width=WIDTH) - if code not in (d.DIALOG_CANCEL, d.DIALOG_ESC): + (code, answer) = d.inputbox( + "Please provide a new value for `%s' image property or press " + "<Delete> to completely delete it." % choice, + init=session['metadata'][choice], width=WIDTH, extra_button=1, + extra_label="Delete") + if code == d.DIALOG_OK: value = answer.strip() if len(value) == 0: d.msgbox("Value cannot be empty!") continue else: session['metadata'][choice] = value + # Delete button + elif code == d.DIALOG_EXTRA: + if not d.yesno("Are you sure you want to delete `%s' image " + "property?" % choice, width=WIDTH): + del session['metadata'][choice] + d.msgbox("Image property: `%s' was deleted." % choice, + width=SMALL_WIDTH) # ADD button elif code == d.DIALOG_EXTRA: add_property(session) @@ -565,35 +567,6 @@ def modify_properties(session): show_properties_help(session) -def delete_properties(session): - """Delete an image property""" - d = session['dialog'] - - choices = [] - for (key, val) in session['metadata'].items(): - choices.append((key, "%s" % val, 0)) - - if len(choices) == 0: - d.msgbox("No available images properties to delete!", - width=SMALL_WIDTH) - return True - - (code, to_delete) = d.checklist("Choose which properties to delete:", - choices=choices, width=WIDTH) - to_delete = map(lambda x: x.strip('"'), to_delete) # needed for OpenSUSE - - # If the user exits with ESC or CANCEL, the returned tag list is empty. - for i in to_delete: - del session['metadata'][i] - - cnt = len(to_delete) - if cnt > 0: - d.msgbox("%d image properties were deleted." % cnt, width=SMALL_WIDTH) - return True - else: - return False - - def exclude_tasks(session): """Exclude specific tasks from running during image deployment""" d = session['dialog'] @@ -627,13 +600,14 @@ def exclude_tasks(session): index += 1 while 1: + text = "Please choose which configuration tasks you would like to " \ + "prevent from running during image deployment. " \ + "Press <No Config> to suppress any configuration. " \ + "Press <Help> for more help on the image deployment " \ + "configuration tasks." + (code, tags) = d.checklist( - text="Please choose which configuration tasks you would like to " - "prevent from running during image deployment. " - "Press <No Config> to supress any configuration. " - "Press <Help> for more help on the image deployment " - "configuration tasks.", - choices=choices, height=19, list_height=8, width=WIDTH, + text=text, choices=choices, height=19, list_height=8, width=WIDTH, help_button=1, extra_button=1, extra_label="No Config", title="Exclude Configuration Tasks") tags = map(lambda x: x.strip('"'), tags) # Needed for OpenSUSE @@ -671,77 +645,170 @@ def sysprep_params(session): d = session['dialog'] image = session['image'] - available = image.os.sysprep_params - needed = image.os.needed_sysprep_params + default = None + while 1: + choices = [] + for name, param in image.os.sysprep_params.items(): - if len(needed) == 0: - return True + # Don't show the hidden parameters + if param.hidden: + continue - def print_form(names, extra_button=False): - """print the dialog form providing sysprep_params""" - fields = [] - for name in names: - param = needed[name] - default = str(available[name]) if name in available else "" - fields.append(("%s: " % param.description, default, - SYSPREP_PARAM_MAXLEN)) - - kwargs = {} - if extra_button: - kwargs['extra_button'] = 1 - kwargs['extra_label'] = "Advanced" - - txt = "Please provide the following system preparation parameters:" - return d.form(txt, height=13, width=WIDTH, form_height=len(fields), - fields=fields, **kwargs) - - def check_params(names, values): - """check if the provided sysprep parameters have leagal values""" - for i in range(len(names)): - param = needed[names[i]] - try: - normalized = param.type(values[i]) - if param.validate(normalized): - image.os.sysprep_params[names[i]] = normalized - continue - except ValueError: - pass + value = str(param.value) + if len(value) == 0: + value = "<not_set>" + choices.append((name, value)) - d.msgbox("Invalid value for parameter: `%s'" % names[i], - width=SMALL_WIDTH) - return False - return True + if len(choices) == 0: + d.msgbox("No customization parameters available", width=WIDTH) + return True + + if default is None: + default = choices[0][0] + + (code, choice) = d.menu( + "In this menu you can see and update the value for parameters " + "used in the system preparation tasks. Press <Details> to see " + "more info about a specific configuration parameters and <Update> " + "to update its value. Press <Back> when done.", height=18, + width=WIDTH, choices=choices, menu_height=10, ok_label="Details", + extra_button=1, extra_label="Update", cancel="Back", + default_item=default, title="System Preparation Parameters") + + default = choice + + if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): + return True + elif code == d.DIALOG_OK: # Details button + d.msgbox(image.os.sysprep_params[choice].description, width=WIDTH) + else: # Update button + update_sysprep_param(session, choice) + + return True - simple_names = [k for k, v in needed.items() if v.default is None] - advanced_names = [k for k, v in needed.items() if v.default is not None] +def virtio(session): + """Display the state of the VirtIO drivers in the media""" + + d = session['dialog'] + image = session['image'] + + assert hasattr(image.os, 'virtio_state') + assert hasattr(image.os, 'install_virtio_drivers') + + default_item = image.os.virtio_state.keys()[0] while 1: - code, output = print_form(simple_names, extra_button=True) + choices = [] + for name, details in virtio_versions(image.os.virtio_state).items(): + choices.append((name, details)) + + (code, choice) = d.menu( + "In this menu you can see details about the installed VirtIO " + "drivers on the input media. Press <Info> to see more information " + "about a specific installed driver or <Update> to install one or " + "more new drivers.", height=16, width=WIDTH, choices=choices, + ok_label="Info", menu_height=len(choices), cancel="Back", + title="VirtIO Drivers", extra_button=1, extra_label="Update", + default_item=default_item) if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): - return False - if code == d.DIALOG_EXTRA: - while 1: - code, output = print_form(advanced_names) - if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): - break - if check_params(advanced_names, output): - break - continue + return True + elif code == d.DIALOG_OK: + default_item = choice + + # Create a string with the driver details and display it. + details = "" + for fname, driver in image.os.virtio_state[choice].items(): + details += "%s\n%s\n" % (fname, "=" * len(fname)) + name = "" + if 'DriverPackageDisplayName' in driver: + name = driver['DriverPackageDisplayName'] + provider = "" + if 'Provider' in driver: + provider = driver['Provider'] + date = "" + version = "" + if 'DriverVer' in driver: + version = driver['DriverVer'].split(',', 1) + date = version[0].strip() + version = version[1] if len(version) > 1 else "" + try: + date = time.strptime( + date, "%m/%d/%y").strftime('%d/%m/%Y', date) + except ValueError: + pass + dtype = "" + if 'DriverPackageType' in driver: + dtype = driver['DriverPackageType'] + dclass = "" + if 'Class' in driver: + dclass = driver['Class'] + + details += "Name: %s\n" % name.strip('\'"') + details += "Provider: %s\n" % provider.strip('\'"') + details += "Date: %s\n" % date + details += "Version: %s\n" % version + details += "Type: %s\n" % dtype + details += "Class: %s\n\n" % dclass + + if len(details): + d.scrollbox(details, width=WIDTH) + else: # Update button + title = "Please select a directory that hosts VirtIO drivers." + if not update_sysprep_param(session, "virtio", title=title): + continue + install_virtio_drivers(session) - if check_params(simple_names, output): - break + return True + + +def install_virtio_drivers(session): + """Installs new VirtIO drivers in the image""" + d = session['dialog'] + image = session['image'] + + assert hasattr(image.os, 'install_virtio_drivers') + + virtio = image.os.sysprep_params['virtio'].value + new_drivers = virtio_versions(image.os.compute_virtio_state(virtio)) + + msg = \ + "The following VirtIO drivers were discovered in the directory you "\ + "specified:\n\n" + for drv, drv_ver in new_drivers.items(): + msg += "%s: %s\n" % (drv, drv_ver) + msg += "\nPress <Install> to continue with the installation of the " \ + "aforementioned drivers or <Cancel> to return to the previous menu." + if d.yesno(msg, width=WIDTH, defaultno=1, height=11+len(new_drivers), + yes_label="Install", no_label="Cancel"): + return False + + title = "VirtIO Drivers Installation" + infobox = InfoBoxOutput(d, title) + try: + image.out.add(infobox) + try: + image.os.install_virtio_drivers() + infobox.finalize() + except FatalError as e: + d.msgbox("VirtIO Drivers Installation failed: %s" % e, title=title, + width=SMALL_WIDTH) + return False + finally: + image.out.remove(infobox) + finally: + infobox.cleanup() return True def sysprep(session): - """Perform various system preperation tasks on the image""" + """Perform various system preparation tasks on the image""" d = session['dialog'] image = session['image'] # Is the image already shrinked? - if 'shrinked' in session and session['shrinked']: + if image.os.shrinked: msg = "It seems you have shrinked the image. Running system " \ "preparation tasks on a shrinked image is dangerous." @@ -749,41 +816,45 @@ def sysprep(session): width=SMALL_WIDTH, defaultno=1): return - wrapper = textwrap.TextWrapper(width=WIDTH - 5) + wrapper = textwrap.TextWrapper(width=WIDTH-5) syspreps = image.os.list_syspreps() if len(syspreps) == 0: d.msgbox("No system preparation task available to run!", - title="System Preperation", width=SMALL_WIDTH) + title="System Preparation", width=SMALL_WIDTH) return while 1: choices = [] index = 0 - help_title = "System Preperation Tasks" + help_title = "System Preparation Tasks" sysprep_help = "%s\n%s\n\n" % (help_title, '=' * len(help_title)) - for sysprep in syspreps: - name, descr = image.os.sysprep_info(sysprep) - display_name = name.replace('-', ' ').capitalize() - sysprep_help += "%s\n" % display_name - sysprep_help += "%s\n" % ('-' * len(display_name)) + for task in syspreps: + name, descr, display = image.os.sysprep_info(task) + sysprep_help += "%s\n" % display + sysprep_help += "%s\n" % ('-' * len(display)) sysprep_help += "%s\n\n" % wrapper.fill(" ".join(descr.split())) - enabled = 1 if sysprep.enabled else 0 - choices.append((str(index + 1), display_name, enabled)) + enabled = 1 if image.os.sysprep_enabled(task) else 0 + choices.append((str(index + 1), display, enabled)) index += 1 (code, tags) = d.checklist( "Please choose which system preparation tasks you would like to " - "run on the image. Press <Help> to see details about the system " - "preparation tasks.", title="Run system preparation tasks", - choices=choices, width=70, ok_label="Run", help_button=1) + "run on the image. Press <Params> to view or modify the " + "customization parameters or <Help> to see details about the " + "system preparation tasks.", title="Run system preparation tasks", + choices=choices, width=70, ok_label="Run", help_button=1, + extra_button=1, extra_label="Params") + tags = map(lambda x: x.strip('"'), tags) # Needed for OpenSUSE if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): return False + elif code == d.DIALOG_EXTRA: + sysprep_params(session) elif code == d.DIALOG_HELP: d.scrollbox(sysprep_help, width=WIDTH) elif code == d.DIALOG_OK: @@ -794,12 +865,10 @@ def sysprep(session): else: image.os.disable_sysprep(syspreps[i]) - if len([s for s in image.os.list_syspreps() if s.enabled]) == 0: - d.msgbox("No system preperation task is selected!", - title="System Preperation", width=SMALL_WIDTH) - continue - - if not sysprep_params(session): + if len([s for s in image.os.list_syspreps() + if image.os.sysprep_enabled(s)]) == 0: + d.msgbox("No system preparation task is selected!", + title="System Preparation", width=SMALL_WIDTH) continue infobox = InfoBoxOutput(d, "Image Configuration") @@ -814,11 +883,12 @@ def sysprep(session): with MetadataMonitor(session, image.os.meta): try: image.os.do_sysprep() + update_background_title(session) infobox.finalize() - except FatalError as e: - title = "System Preparation" - d.msgbox("System Preparation failed: %s" % e, - title=title, width=SMALL_WIDTH) + except FatalError as error: + d.msgbox("System Preparation failed: %s" % error, + title="System Preparation", + width=SMALL_WIDTH) finally: image.out.remove(infobox) finally: @@ -827,59 +897,24 @@ def sysprep(session): return True -def shrink(session): - """Shrink the image""" - d = session['dialog'] - image = session['image'] - - shrinked = 'shrinked' in session and session['shrinked'] - - if shrinked: - d.msgbox("The image is already shrinked!", title="Image Shrinking", - width=SMALL_WIDTH) - return True - - msg = "This operation will shrink the last partition of the image to " \ - "reduce the total image size. If the last partition is a swap " \ - "partition, then this partition is removed and the partition " \ - "before that is shrinked. The removed swap partition will be " \ - "recreated during image deployment." - - if not d.yesno("%s\n\nDo you want to continue?" % msg, width=WIDTH, - height=12, title="Image Shrinking"): - with MetadataMonitor(session, image.meta): - infobox = InfoBoxOutput(d, "Image Shrinking", height=4) - image.out.add(infobox) - try: - image.shrink() - infobox.finalize() - finally: - image.out.remove(infobox) - - session['shrinked'] = True - update_background_title(session) - else: - return False - - return True - - def customization_menu(session): """Show image customization menu""" d = session['dialog'] + image = session['image'] - choices = [("Sysprep", "Run various image preparation tasks"), - ("Shrink", "Shrink image"), - ("View/Modify", "View/Modify image properties"), - ("Delete", "Delete image properties"), - ("Exclude", "Exclude various deployment tasks from running")] + choices = [] + if hasattr(image.os, "install_virtio_drivers"): + choices.append(("VirtIO", "Install or update the VirtIO drivers")) + choices.extend( + [("Sysprep", "Run various image preparation tasks"), + ("Properties", "View & Modify image properties"), + ("Exclude", "Exclude various deployment tasks from running")]) default_item = 0 - actions = {"Sysprep": sysprep, - "Shrink": shrink, - "View/Modify": modify_properties, - "Delete": delete_properties, + actions = {"VirtIO": virtio, + "Sysprep": sysprep, + "Properties": modify_properties, "Exclude": exclude_tasks} while 1: (code, choice) = d.menu( @@ -912,13 +947,13 @@ def main_menu(session): actions = {"Customize": customization_menu, "Register": kamaki_menu, "Extract": extract_image} + title = "Image Creator for Synnefo (snf-image-creator v%s)" % version while 1: (code, choice) = d.menu( text="Choose one of the following or press <Exit> to exit.", width=WIDTH, choices=choices, cancel="Exit", height=13, default_item=default_item, menu_height=len(choices), - title="Image Creator for synnefo (snf-image-creator version %s)" % - version) + title=title) if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): if confirm_exit(d): diff --git a/image_creator/dialog_util.py b/image_creator/dialog_util.py index af5e4254c5cd3eaf2903848465e68c393d9229e2..a757a963fbf687b9dacf260df10e5c657288e328 100644 --- a/image_creator/dialog_util.py +++ b/image_creator/dialog_util.py @@ -1,55 +1,105 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """Module providing useful functions for the dialog-based version of snf-image-creator. """ import os +import stat import re import json from image_creator.output.dialog import GaugeOutput -from image_creator.util import MD5 from image_creator.kamaki_wrapper import Kamaki SMALL_WIDTH = 60 WIDTH = 70 +def select_file(d, **kwargs): + """Select a file or directory. + + The following optional arguments can be applied: + + * init: Initial file path. If this path is valid this will be returned + + * ftype: Allowed file types. If the value of this argument is "br" only + block devices and regular files are valid. For a list of available + file types, see here: + http://libguestfs.org/guestfs.3.html#guestfs_readdir + + * title: The dialog box title. The default one is: "Please select a file" + + * bundle_host: This can be True or False. If this is True, an extra + "Bundle Host" button will be present if the file selection dialog. + """ + + type_check = {'b': stat.S_ISBLK, # Block special + 'c': stat.S_ISCHR, # Char special + 'd': stat.S_ISDIR, # Directory + 'f': stat.S_ISFIFO, # FIFO (named pipe) + 'l': stat.S_ISLNK, # Symbolic link + 'r': stat.S_ISREG, # Regular file + 's': stat.S_ISSOCK} # Socket + + fname = None if "init" not in kwargs else kwargs['init'] + ftype = set(t for t in kwargs['ftype']) if 'ftype' in kwargs else set('r') + title = kwargs['title'] if 'title' in kwargs else 'Please select a file.' + + bundle_host = kwargs['bundle_host'] if 'bundle_host' in kwargs else None + extra_button = 1 if bundle_host else 0 + + for t in ftype: + assert t in type_check, "Invalid ftype: %s" % t + + # This is a special case + if bundle_host and fname == os.sep: + return os.sep + + default = os.getcwd() + os.sep + + while 1: + if fname is not None: + if not os.path.exists(fname): + d.msgbox("The file `%s' you choose does not exist." % fname, + width=SMALL_WIDTH) + else: + mode = os.stat(fname).st_mode + for i in ftype: + if type_check[i](mode): + return fname + + if stat.S_ISDIR(mode): + default = fname + else: + d.msgbox("Invalid input.", width=SMALL_WIDTH) + + (code, fname) = d.fselect(default, 10, 60, extra_button=extra_button, + title=title, extra_label="Bundle Host") + if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): + return None + elif code == d.DIALOG_EXTRA: + return os.sep + + return fname + + def update_background_title(session): - """Update the backgroud title of the dialog page""" + """Update the background title of the dialog page""" d = session['dialog'] disk = session['disk'] image = session['image'] @@ -57,12 +107,11 @@ def update_background_title(session): MB = 2 ** 20 size = (image.size + MB - 1) // MB - shrinked = 'shrinked' in session and session['shrinked'] - postfix = " (shrinked)" if shrinked else '' + postfix = " (shrinked)" if image.os.shrinked else '' title = "OS: %s, Distro: %s, Size: %dMB%s, Source: %s" % \ - (image.ostype, image.distro, size, postfix, - os.path.abspath(disk.source)) + (image.ostype.capitalize(), image.distro.capitalize(), size, + postfix, os.path.abspath(disk.source)) d.setBackgroundTitle(title) @@ -148,8 +197,7 @@ def extract_image(session): out.add(gauge) try: if "checksum" not in session: - md5 = MD5(out) - session['checksum'] = md5.compute(image.device, image.size) + session['checksum'] = image.md5() # Extract image file image.dump(path) @@ -177,17 +225,17 @@ def extract_image(session): return True -def _check_cloud(session, name, description, url, token): +def _check_cloud(session, name, url, token): """Checks if the provided info for a cloud are valid""" d = session['dialog'] - regexp = re.compile('^[~@#$:\-\w]+$') + regexp = re.compile(r'^[~@#$:\-\w]+$') if not re.match(regexp, name): d.msgbox("Allowed characters for name: a-zA-Z0-9_~@#$:-", width=WIDTH) return False if len(url) == 0: - d.msgbox("Url cannot be empty!", width=WIDTH) + d.msgbox("URL cannot be empty!", width=WIDTH) return False if len(token) == 0: @@ -232,7 +280,7 @@ def add_cloud(session): url = url.strip() token = token.strip() - if _check_cloud(session, name, description, url, token): + if _check_cloud(session, name, url, token): if name in Kamaki.get_clouds().keys(): d.msgbox("A cloud with name `%s' already exists. If you want " "to edit the existing cloud account, use the edit " @@ -277,7 +325,7 @@ def edit_cloud(session, name): url = url.strip() token = token.strip() - if _check_cloud(session, name, description, url, token): + if _check_cloud(session, name, url, token): Kamaki.save_cloud(name, url, token, description) break @@ -285,4 +333,42 @@ def edit_cloud(session, name): return True + +def update_sysprep_param(session, name, title=None): + """Modify the value of a sysprep parameter""" + d = session['dialog'] + image = session['image'] + + param = image.os.sysprep_params[name] + + while 1: + if param.type in ("file", "dir"): + if not title: + title = "Please select a %s to use for the `%s' parameter" % \ + ('file' if param.type == 'file' else 'directory', name) + ftype = "br" if param.type == 'file' else 'd' + + value = select_file(d, ftype=ftype, title=title) + if value is None: + return False + else: + if not title: + title = "Please provide a new value for configuration " \ + "parameter: `%s'" % name + (code, answer) = d.inputbox( + title, width=WIDTH, init=str(param.value)) + + if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): + return False + + value = answer.strip() + + if param.set_value(value) is False: + d.msgbox("Error: %s" % param.error, width=WIDTH) + param.error = None + continue + break + + return True + # vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/dialog_wizard.py b/image_creator/dialog_wizard.py index ffabecf0b6f66a0efe81f65d4179baabed72ab96..2c4e5d62f611b0c2eba448fe9a7ba515ec0e897e 100644 --- a/image_creator/dialog_wizard.py +++ b/image_creator/dialog_wizard.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module implements the "wizard" mode of the dialog-based version of snf-image-creator. @@ -40,16 +22,16 @@ snf-image-creator. import time import StringIO import json +import re from image_creator.kamaki_wrapper import Kamaki, ClientError -from image_creator.util import MD5, FatalError +from image_creator.util import FatalError, virtio_versions from image_creator.output.cli import OutputWthProgress from image_creator.dialog_util import extract_image, update_background_title, \ - add_cloud, edit_cloud + add_cloud, edit_cloud, update_sysprep_param PAGE_WIDTH = 70 -PAGE_HEIGHT = 10 -SYSPREP_PARAM_MAXLEN = 20 +PAGE_HEIGHT = 12 class WizardExit(Exception): @@ -62,83 +44,97 @@ class WizardReloadPage(Exception): pass -class Wizard: +class Wizard(object): """Represents a dialog-based wizard The wizard is a collection of pages that have a "Next" and a "Back" button on them. The pages are used to collect user data. """ - def __init__(self, session): - self.session = session - self.pages = [] - self.session['wizard'] = {} - self.d = session['dialog'] + def __init__(self, dialog): + """Initialize the Wizard""" + self._pages = [] + self.dialog = dialog def add_page(self, page): """Add a new page to the wizard""" - self.pages.append(page) + self._pages.append(page) def run(self): """Run the wizard""" idx = 0 while True: try: - total = len(self.pages) - title = "(%d/%d) %s" % (idx + 1, total, self.pages[idx].title) - idx += self.pages[idx].run(self.session, title) + total = len(self._pages) + title = "(%d/%d) %s" % (idx + 1, total, self._pages[idx].title) + idx += self._pages[idx].show(self.dialog, title) except WizardExit: return False except WizardReloadPage: continue - if idx >= len(self.pages): + if idx >= len(self._pages): text = "All necessary information has been gathered:\n\n" - for page in self.pages: - text += " * %s\n" % page.info + for page in self._pages: + text += " * %s\n" % page text += "\nContinue with the image creation process?" - ret = self.d.yesno( - text, width=PAGE_WIDTH, height=8 + len(self.pages), + ret = self.dialog.yesno( + text, width=PAGE_WIDTH, height=8 + len(self._pages), ok_label="Yes", cancel="Back", extra_button=1, extra_label="Quit", title="Confirmation") - if ret == self.d.DIALOG_CANCEL: + if ret == self.dialog.DIALOG_CANCEL: idx -= 1 - elif ret == self.d.DIALOG_EXTRA: + elif ret == self.dialog.DIALOG_EXTRA: return False - elif ret == self.d.DIALOG_OK: + elif ret == self.dialog.DIALOG_OK: return True if idx < 0: return False + @property + def answers(self): + """Returns the answers the user provided""" + return dict((page.name, page.answer) for page in self._pages) + class WizardPage(object): """Represents a page in a wizard""" NEXT = 1 PREV = -1 - def __init__(self, name, display_name, text, **kargs): + def __init__(self, name, text, **kargs): self.name = name - self.display_name = display_name + self.answer = None self.text = text - - self.title = kargs['title'] if 'title' in kargs else "" + self.print_name = kargs['print_name'] if 'print_name' in kargs \ + else " ".join(re.findall('[A-Z][^A-Z]*', name)) + self.title = kargs['title'] if 'title' in kargs else self.print_name self.default = kargs['default'] if 'default' in kargs else "" self.extra = kargs['extra'] if 'extra' in kargs else None - self.extra_label = \ - kargs['extra_label'] if 'extra_label' in kargs else 'Extra' + self.validate = \ + kargs['validate'] if 'validate' in kargs else lambda x: x + self.display = kargs['display'] if 'display' in kargs else lambda x: x + + self.dargs = {} + self.dargs['ok_label'] = 'Next' + self.dargs['cancel'] = 'Back' + self.dargs['width'] = PAGE_WIDTH + self.dargs['height'] = PAGE_HEIGHT - self.info = "%s: <none>" % self.display_name + if 'extra' in kargs: + self.dargs['extra_button'] = 1 - validate = kargs['validate'] if 'validate' in kargs else lambda x: x - setattr(self, "validate", validate) + self.extra_label = kargs['extra_label'] if 'extra_label' in kargs \ + else lambda: "extra" - display = kargs['display'] if 'display' in kargs else lambda x: x - setattr(self, "display", display) + def __str__(self): + """Prints the answer""" + return "%s: %s" % (self.print_name, self.display(self.answer)) - def run(self, session, title): + def show(self, dialog, title): """Display this wizard page This function is used by the wizard program when accessing a page. @@ -146,95 +142,117 @@ class WizardPage(object): raise NotImplementedError -class WizardPageWthChoices(WizardPage): - """Represents a Wizard Page that allows the user to select something from - a list of choices. - - The available choices are created by a function passed to the class through - the choices variable. If the choices function returns an empty list, a - fallback funtion is executed if available. - """ - def __init__(self, name, display_name, text, choices, **kargs): - super(WizardPageWthChoices, self).__init__(name, display_name, text, - **kargs) - self.choices = choices - self.fallback = kargs['fallback'] if 'fallback' in kargs else None - - -class WizardRadioListPage(WizardPageWthChoices): - """Represent a Radio List in a wizard""" - - def run(self, session, title): - d = session['dialog'] - w = session['wizard'] - - choices = [] - for choice in self.choices(): - default = 1 if choice[0] == self.default else 0 - choices.append((choice[0], choice[1], default)) +class WizardInputPage(WizardPage): + """Represents an input field in a wizard""" - (code, answer) = d.radiolist( - self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back", - choices=choices, height=PAGE_HEIGHT, title=title) + def show(self, dialog, title): + """Display this wizard page""" + (code, answer) = dialog.inputbox(self.text(), init=self.default, + title=title, + extra_label=self.extra_label(), + **self.dargs) - if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): + if code in (dialog.DIALOG_CANCEL, dialog.DIALOG_ESC): return self.PREV - w[self.name] = self.validate(answer) - self.default = answer - self.info = "%s: %s" % (self.display_name, self.display(w[self.name])) + self.answer = self.validate(answer.strip()) + self.default = self.answer return self.NEXT -class WizardInputPage(WizardPage): - """Represents an input field in a wizard""" +class WizardInfoPage(WizardPage): + """Represents a Wizard Page that just displays some user-defined + information. - def run(self, session, title): - d = session['dialog'] - w = session['wizard'] + The user-defined information is created by the info function. + """ + def __init__(self, name, text, info, **kargs): + """Initialize the WizardInfoPage instance""" + super(WizardInfoPage, self).__init__(name, text, **kargs) + self.info = info - (code, answer) = d.inputbox( - self.text, init=self.default, width=PAGE_WIDTH, ok_label="Next", - cancel="Back", height=PAGE_HEIGHT, title=title) + def show(self, dialog, title): + """Display this wizard page""" - if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): - return self.PREV + text = "%s\n\n%s" % (self.text(), self.info()) - value = answer.strip() - self.default = value - w[self.name] = self.validate(value) - self.info = "%s: %s" % (self.display_name, self.display(w[self.name])) + ret = dialog.yesno(text, title=title, extra_label=self.extra_label(), + **self.dargs) + if ret in (dialog.DIALOG_CANCEL, dialog.DIALOG_ESC): + return self.PREV + elif ret == dialog.DIALOG_EXTRA: + self.extra() + raise WizardReloadPage + + # DIALOG_OK + self.answer = self.validate(None) return self.NEXT class WizardFormPage(WizardPage): """Represents a Form in a wizard""" - def __init__(self, name, display_name, text, fields, **kargs): - super(WizardFormPage, self).__init__(name, display_name, text, **kargs) + def __init__(self, name, text, fields, **kargs): + """Initialize the WizardFormPage instance""" + super(WizardFormPage, self).__init__(name, text, **kargs) self.fields = fields - def run(self, session, title): - d = session['dialog'] - w = session['wizard'] - + def show(self, dialog, title): + """Display this wizard page""" field_lenght = len(self.fields()) form_height = field_lenght if field_lenght < PAGE_HEIGHT - 4 \ else PAGE_HEIGHT - 4 - (code, output) = d.form( - self.text, width=PAGE_WIDTH, height=PAGE_HEIGHT, - form_height=form_height, ok_label="Next", cancel="Back", - fields=self.fields(), title=title) + (code, output) = dialog.form(self.text(), form_height=form_height, + fields=self.fields(), title=title, + extra_label=self.extra_label(), + default_item=self.default, **self.dargs) - if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): + if code in (dialog.DIALOG_CANCEL, dialog.DIALOG_ESC): return self.PREV - w[self.name] = self.validate(output) + self.answer = self.validate(output) self.default = output - self.info = "%s: %s" % (self.display_name, self.display(w[self.name])) + + return self.NEXT + + +class WizardPageWthChoices(WizardPage): + """Represents a Wizard Page that allows the user to select something from + a list of choices. + + The available choices are created by a function passed to the class through + the choices variable. If the choices function returns an empty list, a + fallback function is executed if available. + """ + def __init__(self, name, text, choices, **kargs): + """Initialize the WizardPageWthChoices instance""" + super(WizardPageWthChoices, self).__init__(name, text, **kargs) + self.choices = choices + self.fallback = kargs['fallback'] if 'fallback' in kargs else None + + +class WizardRadioListPage(WizardPageWthChoices): + """Represent a Radio List in a wizard""" + + def show(self, dialog, title): + """Display this wizard page""" + choices = [] + for choice in self.choices(): + default = 1 if choice[0] == self.default else 0 + choices.append((choice[0], choice[1], default)) + + (code, answer) = dialog.radiolist(self.text(), choices=choices, + extra_label=self.extra_label(), + title=title, **self.dargs) + + if code in (dialog.DIALOG_CANCEL, dialog.DIALOG_ESC): + return self.PREV + + self.answer = self.validate(answer) + self.default = answer return self.NEXT @@ -242,11 +260,8 @@ class WizardFormPage(WizardPage): class WizardMenuPage(WizardPageWthChoices): """Represents a menu dialog with available choices in a wizard""" - def run(self, session, title): - d = session['dialog'] - w = session['wizard'] - - extra_button = 1 if self.extra else 0 + def show(self, dialog, title): + """Display this wizard page""" choices = self.choices() @@ -259,21 +274,18 @@ class WizardMenuPage(WizardPageWthChoices): default_item = self.default if self.default else choices[0][0] - (code, choice) = d.menu( - self.text, width=PAGE_WIDTH, ok_label="Next", cancel="Back", - title=title, choices=choices, height=PAGE_HEIGHT, - default_item=default_item, extra_label=self.extra_label, - extra_button=extra_button) + (code, choice) = dialog.menu(self.text(), title=title, choices=choices, + extra_label=self.extra_label(), + default_item=default_item, **self.dargs) - if code in (d.DIALOG_CANCEL, d.DIALOG_ESC): + if code in (dialog.DIALOG_CANCEL, dialog.DIALOG_ESC): return self.PREV - elif code == d.DIALOG_EXTRA: + elif code == dialog.DIALOG_EXTRA: self.extra() raise WizardReloadPage + self.answer = self.validate(choice) self.default = choice - w[self.name] = self.validate(choice) - self.info = "%s: %s" % (self.display_name, self.display(w[self.name])) return self.NEXT @@ -281,12 +293,13 @@ class WizardMenuPage(WizardPageWthChoices): def start_wizard(session): """Run the image creation wizard""" - image = session['image'] - distro = image.distro - ostype = image.ostype + metadata = session['metadata'] + distro = session['image'].distro + ostype = session['image'].ostype # Create Cloud Wizard Page def cloud_choices(): + """Returns the available clouds""" choices = [] for (name, cloud) in Kamaki.get_clouds().items(): descr = cloud['description'] if 'description' in cloud else '' @@ -294,10 +307,8 @@ def start_wizard(session): return choices - def cloud_add(): - return add_cloud(session) - - def cloud_none_available(): + def no_clouds(): + """Fallback function when no cloud account exists""" if not session['dialog'].yesno( "No available clouds found. Would you like to add one now?", width=PAGE_WIDTH, defaultno=0): @@ -305,189 +316,208 @@ def start_wizard(session): return False def cloud_validate(cloud): + """Checks if a cloud is valid""" if not Kamaki.get_account(cloud): if not session['dialog'].yesno( "The cloud you have selected is not valid! Would you " "like to edit it now?", width=PAGE_WIDTH, defaultno=0): if edit_cloud(session, cloud): return cloud - raise WizardReloadPage - return cloud cloud = WizardMenuPage( - "Cloud", "Cloud", + "Cloud", lambda: "Please select a cloud account or press <Add> to add a new one:", - choices=cloud_choices, extra_label="Add", extra=cloud_add, - title="Clouds", validate=cloud_validate, fallback=cloud_none_available) + cloud_choices, extra_label=lambda: "Add", + extra=lambda: add_cloud(session), title="Clouds", + validate=cloud_validate, fallback=no_clouds) # Create Image Name Wizard Page - name = WizardInputPage( - "ImageName", "Image Name", "Please provide a name for the image:", - title="Image Name", default=ostype if distro == "unknown" else distro) + name = WizardInputPage("ImageName", lambda: + "Please provide a name for the image:", + default=ostype if distro == "unknown" else distro) # Create Image Description Wizard Page descr = WizardInputPage( - "ImageDescription", "Image Description", + "ImageDescription", lambda: "Please provide a description for the image:", - title="Image Description", default=session['metadata']['DESCRIPTION'] - if 'DESCRIPTION' in session['metadata'] else '') - - # Create Sysprep Params Wizard Page - needed = image.os.needed_sysprep_params - # Only show the parameters that don't have default values - param_names = [param for param in needed if needed[param].default is None] - - def sysprep_params_fields(): - fields = [] - available = image.os.sysprep_params - for name in param_names: - text = needed[name].description - default = str(available[name]) if name in available else "" - fields.append(("%s: " % text, default, SYSPREP_PARAM_MAXLEN)) - return fields - - def sysprep_params_validate(answer): - params = {} - for i in range(len(answer)): - try: - value = needed[param_names[i]].type(answer[i]) - if needed[param_names[i]].validate(value): - params[param_names[i]] = value - continue - except ValueError: - pass - - session['dialog'].msgbox("Invalid value for parameter `%s'" % - param_names[i]) - raise WizardReloadPage - return params - - def sysprep_params_display(params): - return ",".join(["%s=%s" % (key, val) for key, val in params.items()]) + default=metadata['DESCRIPTION'] if 'DESCRIPTION' in metadata else '') + + # Create VirtIO Installation Page + def display_installed_drivers(): + """Returns the installed VirtIO drivers""" + image = session['image'] + versions = virtio_versions(image.os.virtio_state) + + ret = "Installed Block Device Driver: %(netkvm)s\n" \ + "Installed Network Device Driver: %(viostor)s\n" % versions + + virtio = image.os.sysprep_params['virtio'].value + if virtio: + ret += "\nBlock Device Driver to be installed: %(netkvm)s\n" \ + "Network Device Driver to be installed: %(viostor)s\n" % \ + virtio_versions(image.os.compute_virtio_state(virtio)) + return ret + + def validate_virtio(_): + """Checks the state of the VirtIO drivers""" + image = session['image'] + netkvm = len(image.os.virtio_state['netkvm']) != 0 + viostor = len(image.os.virtio_state['viostor']) != 0 + drv_dir = image.os.sysprep_params['virtio'].value + + if netkvm is False or viostor is False: + new = image.os.compute_virtio_state(drv_dir) if drv_dir else None + new_viostor = len(new['viostor']) != 0 if new else False + new_netkvm = len(new['netkvm']) != 0 if new else False + + dialog = session['dialog'] + title = "VirtIO driver missing" + msg = "Image creation cannot proceed unless a VirtIO %s driver " \ + "is installed on the media!" + if not (viostor or new_viostor): + dialog.msgbox(msg % "Block Device", width=PAGE_WIDTH, + height=PAGE_HEIGHT, title=title) + raise WizardReloadPage + if not(netkvm or new_netkvm): + dialog.msgbox(msg % "Network Device", width=PAGE_WIDTH, + height=PAGE_HEIGHT, title=title) + raise WizardReloadPage - sysprep_params = WizardFormPage( - "SysprepParams", "Sysprep Parameters", - "Prease fill in the following system preparation parameters:", - title="System Preparation Parameters", fields=sysprep_params_fields, - display=sysprep_params_display, validate=sysprep_params_validate - ) if len(needed) != 0 else None + return drv_dir + + def virtio_text(): + if not session['image'].os.sysprep_params['virtio'].value: + return "Press <New> to update the image's VirtIO drivers." + else: + return "Press <Revert> to revert to the old state." + + def virtio_extra(): + if not session['image'].os.sysprep_params['virtio'].value: + title = "Please select a directory that hosts VirtIO drivers." + update_sysprep_param(session, 'virtio', title=title) + else: + session['image'].os.sysprep_params['virtio'].value = "" + + def virtio_extra_label(): + if not session['image'].os.sysprep_params['virtio'].value: + return "New" + else: + return "Revert" + + virtio = WizardInfoPage( + "virtio", virtio_text, display_installed_drivers, + title="VirtIO Drivers", extra_label=virtio_extra_label, + extra=virtio_extra, validate=validate_virtio, + print_name="VirtIO Drivers Path") # Create Image Registration Wizard Page def registration_choices(): + """Choices for the registration wizard page""" return [("Private", "Image is accessible only by this user"), ("Public", "Everyone can create VMs from this image")] - registration = WizardRadioListPage( - "ImageRegistration", "Registration Type", - "Please provide a registration type:", registration_choices, - title="Registration Type", default="Private") + registration = WizardRadioListPage("RegistrationType", lambda: + "Please provide a registration type:", + registration_choices, default="Private") - w = Wizard(session) + wizard = Wizard(session['dialog']) - w.add_page(cloud) - w.add_page(name) - w.add_page(descr) - if sysprep_params is not None: - w.add_page(sysprep_params) - w.add_page(registration) + wizard.add_page(cloud) + wizard.add_page(name) + wizard.add_page(descr) + if hasattr(session['image'].os, 'install_virtio_drivers'): + wizard.add_page(virtio) + wizard.add_page(registration) - if w.run(): - create_image(session) + if wizard.run(): + create_image(session, wizard.answers) else: return False return True -def create_image(session): +def create_image(session, answers): """Create an image using the information collected by the wizard""" - d = session['dialog'] image = session['image'] - wizard = session['wizard'] with_progress = OutputWthProgress(True) - out = image.out - out.add(with_progress) + image.out.add(with_progress) try: - out.clear() + image.out.clear() + + if 'virtio' in answers and image.os.sysprep_params['virtio'].value: + image.os.install_virtio_drivers() - #Sysprep - if 'SysprepParams' in wizard: - image.os.sysprep_params.update(wizard['SysprepParams']) + # Sysprep image.os.do_sysprep() metadata = image.os.meta - #Shrink - size = image.shrink() - session['shrinked'] = True update_background_title(session) metadata.update(image.meta) - metadata['DESCRIPTION'] = wizard['ImageDescription'] + metadata['DESCRIPTION'] = answers['ImageDescription'] - #MD5 - md5 = MD5(out) - session['checksum'] = md5.compute(image.device, size) + # MD5 + session['checksum'] = image.md5() - out.output() + image.out.output() try: - out.output("Uploading image to the cloud:") - account = Kamaki.get_account(wizard['Cloud']) - assert account, "Cloud: %s is not valid" % wizard['Cloud'] - kamaki = Kamaki(account, out) + image.out.output("Uploading image to the cloud:") + account = Kamaki.get_account(answers['Cloud']) + assert account, "Cloud: %s is not valid" % answers['Cloud'] + kamaki = Kamaki(account, image.out) - name = "%s-%s.diskdump" % (wizard['ImageName'], + name = "%s-%s.diskdump" % (answers['ImageName'], time.strftime("%Y%m%d%H%M")) - pithos_file = "" - with open(image.device, 'rb') as f: - pithos_file = kamaki.upload(f, size, name, - "(1/3) Calculating block hashes", - "(2/3) Uploading missing blocks") + with image.raw_device() as raw: + with open(raw, 'rb') as device: + remote = kamaki.upload(device, image.size, name, + "(1/3) Calculating block hashes", + "(2/3) Uploading image blocks") - out.output("(3/3) Uploading md5sum file ...", False) + image.out.output("(3/3) Uploading md5sum file ...", False) md5sumstr = '%s %s\n' % (session['checksum'], name) kamaki.upload(StringIO.StringIO(md5sumstr), size=len(md5sumstr), remote_path="%s.%s" % (name, 'md5sum')) - out.success('done') - out.output() - - is_public = True if wizard['ImageRegistration'] == "Public" else \ - False - out.output('Registering %s image with the cloud ...' % - wizard['ImageRegistration'].lower(), False) - result = kamaki.register(wizard['ImageName'], pithos_file, - metadata, is_public) - out.success('done') - out.output("Uploading metadata file ...", False) + image.out.success('done') + image.out.output() + + image.out.output('Registering %s image with the cloud ...' % + answers['RegistrationType'].lower(), False) + result = kamaki.register(answers['ImageName'], remote, metadata, + answers['RegistrationType'] == "Public") + image.out.success('done') + image.out.output("Uploading metadata file ...", False) metastring = unicode(json.dumps(result, ensure_ascii=False)) kamaki.upload(StringIO.StringIO(metastring), size=len(metastring), remote_path="%s.%s" % (name, 'meta')) - out.success('done') + image.out.success('done') - if is_public: - out.output("Sharing md5sum file ...", False) + if answers['RegistrationType'] == "Public": + image.out.output("Sharing md5sum file ...", False) kamaki.share("%s.md5sum" % name) - out.success('done') - out.output("Sharing metadata file ...", False) + image.out.success('done') + image.out.output("Sharing metadata file ...", False) kamaki.share("%s.meta" % name) - out.success('done') + image.out.success('done') - out.output() + image.out.output() - except ClientError as e: + except ClientError as error: raise FatalError("Storage service client: %d %s" % - (e.status, e.message)) + (error.status, error.message)) finally: - out.remove(with_progress) + image.out.remove(with_progress) text = "The %s image was successfully uploaded to the storage service " \ "and registered with the compute service of %s. Would you like " \ "to keep a local copy?" % \ - (wizard['Cloud'], wizard['ImageRegistration'].lower()) + (answers['RegistrationType'].lower(), answers['Cloud']) - if not d.yesno(text, width=PAGE_WIDTH): + if not session['dialog'].yesno(text, width=PAGE_WIDTH): extract_image(session) # vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/disk.py b/image_creator/disk.py index e4b6bc8913ed3e3664823ebd1f8eb6da0a0fdb03..0f1fdc46bd616d0a52a8ca2a317ec8a61bb9d514 100644 --- a/image_creator/disk.py +++ b/image_creator/disk.py @@ -1,44 +1,24 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """Module hosting the Disk class.""" -from image_creator.util import get_command -from image_creator.util import try_fail_repeat -from image_creator.util import free_space -from image_creator.util import FatalError +from image_creator.util import get_command, try_fail_repeat, free_space, \ + FatalError, create_snapshot from image_creator.bundle_volume import BundleVolume from image_creator.image import Image @@ -90,6 +70,7 @@ class Disk(object): """ self._cleanup_jobs = [] self._images = [] + self._file = None self.source = source self.out = output self.meta = {} @@ -115,15 +96,16 @@ class Disk(object): """Create a disk out of a directory""" if self.source == '/': bundle = BundleVolume(self.out, self.meta) - image = '%s/%s.diskdump' % (self.tmp, uuid.uuid4().hex) + image = '%s/%s.raw' % (self.tmp, uuid.uuid4().hex) def check_unlink(path): + """Unlinks file if exists""" if os.path.exists(path): os.unlink(path) self._add_cleanup(check_unlink, image) bundle.create_image(image) - return self._losetup(image) + return image raise FatalError("Using a directory as media source is supported") def cleanup(self): @@ -141,42 +123,67 @@ class Disk(object): job, args = self._cleanup_jobs.pop() job(*args) - def snapshot(self): - """Creates a snapshot of the original source media of the Disk - instance. - """ + @property + def file(self): + """Convert the source media into a file""" + + if self._file is not None: + return self._file self.out.output("Examining source media `%s' ..." % self.source, False) - sourcedev = self.source mode = os.stat(self.source).st_mode if stat.S_ISDIR(mode): self.out.success('looks like a directory') - return self._dir_to_disk() + self._file = self._dir_to_disk() elif stat.S_ISREG(mode): self.out.success('looks like an image file') - sourcedev = self._losetup(self.source) + self._file = self.source elif not stat.S_ISBLK(mode): raise FatalError("Invalid media source. Only block devices, " "regular files and directories are supported.") else: self.out.success('looks like a block device') + self._file = self.source + + return self._file + + def snapshot(self): + """Creates a snapshot of the original source media of the Disk + instance. + """ + + if self.source == '/': + self.out.warn("Snapshotting ignored for host bundling mode.") + return self.file + + # Examine media file + mode = os.stat(self.file).st_mode - # Take a snapshot and return it to the user self.out.output("Snapshotting media source ...", False) - size = blockdev('--getsz', sourcedev) + + # Create a qcow2 snapshot for image files + if not stat.S_ISBLK(mode): + snapshot = create_snapshot(self.file, self.tmp) + self._add_cleanup(os.unlink, snapshot) + self.out.success('done') + return snapshot + + # Create a device-mapper snapshot for block devices + size = int(blockdev('--getsz', self.file)) + cowfd, cow = tempfile.mkstemp(dir=self.tmp) os.close(cowfd) self._add_cleanup(os.unlink, cow) # Create cow sparse file - dd('if=/dev/null', 'of=%s' % cow, 'bs=512', 'seek=%d' % int(size)) + dd('if=/dev/null', 'of=%s' % cow, 'bs=512', 'seek=%d' % size) cowdev = self._losetup(cow) - snapshot = uuid.uuid4().hex + snapshot = 'snf-image-creator-snapshot-%s' % uuid.uuid4().hex tablefd, table = tempfile.mkstemp() try: try: - os.write(tablefd, "0 %d snapshot %s %s n 8" % - (int(size), sourcedev, cowdev)) + os.write(tablefd, "0 %d snapshot %s %s n 8\n" % + (size, self.file, cowdev)) finally: os.close(tablefd) diff --git a/image_creator/gpt.py b/image_creator/gpt.py index 82ae09ed3b7d00b75b0ffc0d52cb677e60257de7..c02312a2d6bd32789f63018a50378e4cfefa15ad 100644 --- a/image_creator/gpt.py +++ b/image_creator/gpt.py @@ -1,38 +1,20 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module provides the code for handling GUID partition tables""" @@ -277,7 +259,7 @@ class GPTPartitionTable(object): new_size = aligned if aligned <= old_size else \ size + len(self.part_entries) + BLOCKSIZE - assert new_size <= old_size, "The secodary GPT fits in the device" + assert new_size <= old_size, "The secondary GPT fits in the device" if new_size == self.size(): return new_size @@ -285,7 +267,7 @@ class GPTPartitionTable(object): lba_count = new_size // BLOCKSIZE # Correct MBR - #TODO: Check if the partition tables is hybrid + # TODO: Check if the partition tables is hybrid self.mbr.part[0].sector_count = (new_size // BLOCKSIZE) - 1 # Fix Primary header diff --git a/image_creator/help/__init__.py b/image_creator/help/__init__.py index 7f78d35bbf6c7c0f69769526769701199ade36f5..0669effb681caa728cecafb8f3a9be406c9e6a73 100644 --- a/image_creator/help/__init__.py +++ b/image_creator/help/__init__.py @@ -1,39 +1,21 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. -"""This package hosts the help files of the programe.""" +"""This package hosts the help files of the program.""" import sys import os diff --git a/image_creator/help/configuration_tasks.rst b/image_creator/help/configuration_tasks.rst index 1fc1fe0d2169365c3aaf5d1b02c46d6116543ee6..7b8f8c5fcd95e07a7c728e14c17aad4edbc5c09a 100644 --- a/image_creator/help/configuration_tasks.rst +++ b/image_creator/help/configuration_tasks.rst @@ -3,7 +3,7 @@ Configuration tasks performed during deployment Partition Table manipulation ---------------------------- -During image deployment the last partiton is enlarged to use all +During image deployment the last partition is enlarged to use all the available disk space. If SWAP property is present an extra swap partition is also added. @@ -20,16 +20,17 @@ fstab. SSH keys removal ---------------- -All SSH keys found in the image are removed. For debian instance, -where the key creation is not perfored automatically, the keys -are recreated by this task. +All SSH keys found in the image are removed. On Debian and Ubuntu +instances where the key creation is not performed automatically, +this task will also recreate the deleted keys. Temporary disable Remote Desktop (RDP) connections -------------------------------------------------- RDP connections are temporarily disabled during Windows configuration. This is done because when sysprep runs, there is a -small time interval where the new password is not applied yet thus -allowing RDP connections which raises some security conserns. +small time interval where the new password is not applied and +allowing RDP connections during this time would raise security +concerns. Perform SELinux file system relabeling -------------------------------------- @@ -50,5 +51,5 @@ the USERS property. File Injection -------------- -The files specified by the PERSONALITY image property are -injected into the instance's hard disk. +When this tasks runs, the files specified by the PERSONALITY +image property are injected into the instance's hard disk. diff --git a/image_creator/help/image_properties.rst b/image_creator/help/image_properties.rst index 8e65f2af9cb4e4fb741f60d447aeb16b9744eea0..5843d04b12ef26b2725847fb3911fd25406d54ab 100644 --- a/image_creator/help/image_properties.rst +++ b/image_creator/help/image_properties.rst @@ -8,7 +8,7 @@ Properties used during image deployment - ROOT_PARTITION=n The partition number of the root partition. - USERS="username1 username2..." - This is a space-seperated list of users, whose password will + This is a space-separated list of users, whose password will be reset during deployment. - SWAP=<n>:<size> If this property is present, a swap partition with given diff --git a/image_creator/image.py b/image_creator/image.py index aebd2c9ff3de734f76b0831598232af335340c8c..da3777df927ee34c828b19044972863e2514ebe9 100644 --- a/image_creator/image.py +++ b/image_creator/image.py @@ -1,44 +1,27 @@ # -*- coding: utf-8 -*- # -# Copyright 2013 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. -from image_creator.util import FatalError +from image_creator.util import FatalError, QemuNBD, image_info from image_creator.gpt import GPTPartitionTable from image_creator.os_type import os_cls import re import guestfs +import hashlib from sendfile import sendfile @@ -50,6 +33,7 @@ class Image(object): self.device = device self.out = output + self.info = image_info(device) self.meta = kargs['meta'] if 'meta' in kargs else {} self.sysprep_params = \ @@ -63,6 +47,9 @@ class Image(object): self.guestfs_enabled = False self.guestfs_version = self.g.version() + # This is needed if the image format is not raw + self.nbd = QemuNBD(device) + def check_guestfs_version(self, major, minor, release): """Checks if the version of the used libguestfs is smaller, equal or greater than the one specified by the major, minor and release triplet @@ -119,7 +106,7 @@ class Image(object): self.os.inspect() def set_unsupported(self, reason): - """Flag this image us ansupported""" + """Flag this image as unsupported""" self._unsupported = reason self.meta['UNSUPPORTED'] = reason @@ -136,13 +123,13 @@ class Image(object): self.out.warn("Guestfs is already enabled") return - # Before version 1.18.4 the behaviour of kill_subprocess was different + # Before version 1.18.4 the behavior of kill_subprocess was different # and you need to reset the guestfs handler to relaunch a previously - # shut down qemu backend + # shut down QEMU backend if self.check_guestfs_version(1, 18, 4) < 0: self.g = guestfs.GuestFS() - self.g.add_drive_opts(self.device, readonly=0, format="raw") + self.g.add_drive_opts(self.device, readonly=0) # Before version 1.17.14 the recovery process, which is a fork of the # original process that called libguestfs, did not close its inherited @@ -150,20 +137,26 @@ class Image(object): # process has opened pipes. Since the recovery process is an optional # feature of libguestfs, it's better to disable it. if self.check_guestfs_version(1, 17, 14) >= 0: - self.out.output("Enabling recovery proc") + self.out.output("Enabling recovery process ...", False) self.g.set_recovery_proc(1) + self.out.success('done') else: self.g.set_recovery_proc(0) - #self.g.set_trace(1) - #self.g.set_verbose(1) + # self.g.set_trace(1) + # self.g.set_verbose(1) self.out.output('Launching helper VM (may take a while) ...', False) # self.progressbar = self.out.Progress(100, "Launching helper VM", # "percent") # eh = self.g.set_event_callback(self.progress_callback, # guestfs.EVENT_PROGRESS) - self.g.launch() + try: + self.g.launch() + except RuntimeError as e: + raise FatalError( + "Launching libguestfs's helper VM failed! Reason: %s" % str(e)) + self.guestfs_enabled = True # self.g.delete_event_callback(eh) # self.progressbar.success('done') @@ -183,17 +176,22 @@ class Image(object): self.out.output("Shutting down helper VM ...", False) self.g.sync() - # guestfs_shutdown which is the prefered way to shutdown the backend + # guestfs_shutdown which is the preferred way to shutdown the backend # process was introduced in version 1.19.16 if self.check_guestfs_version(1, 19, 16) >= 0: self.g.shutdown() else: self.g.kill_subprocess() + # We will reset the guestfs handler if needed + if self.check_guestfs_version(1, 18, 4) < 0: + self.g.close() + self.guestfs_enabled = False self.out.success('done') - def _get_os(self): + @property + def os(self): """Return an OS class instance for this image""" if hasattr(self, "_os"): return self._os @@ -208,7 +206,30 @@ class Image(object): return self._os - os = property(_get_os) + def raw_device(self, readonly=True): + """Returns a context manager that exports the raw image device. If + readonly is true, the block device that is returned is read only. + """ + + if self.guestfs_enabled: + self.g.umount_all() + self.g.sync() + self.g.drop_caches(3) # drop everything + + # Self gets overwritten + img = self + + class RawImage: + """The RawImage context manager""" + def __enter__(self): + return img.device if img.info['format'] == 'raw' else \ + img.nbd.connect(readonly) + + def __exit__(self, exc_type, exc_value, traceback): + if img.info['format'] != 'raw': + img.nbd.disconnect() + + return RawImage() def destroy(self): """Destroy this Image instance.""" @@ -255,7 +276,7 @@ class Image(object): return last_partition - def shrink(self): + def shrink(self, silent=False): """Shrink the image. This is accomplished by shrinking the last file system of the @@ -286,10 +307,9 @@ class Image(object): MB = 2 ** 20 - self.out.output("Shrinking image (this may take a while) ...", False) - if self.is_unsupported(): - self.out.warn("Shrinking is disabled for unsupported images") + if not silent: + self.out.warn("Shrinking is disabled for unsupported images") return self.size sector_size = self.g.blockdev_getss(self.guestfs_device) @@ -317,7 +337,9 @@ class Image(object): break if not re.match("ext[234]", fstype): - self.out.warn("Don't know how to shrink %s partitions." % fstype) + if not silent: + self.out.warn( + "Don't know how to shrink %s partitions." % fstype) return self.size part_dev = "%s%d" % (self.guestfs_device, last_part['part_num']) @@ -381,12 +403,15 @@ class Image(object): assert (new_size <= self.size) if self.meta['PARTITION_TABLE'] == 'gpt': - ptable = GPTPartitionTable(self.device) - self.size = ptable.shrink(new_size, self.size) + with self.raw_device(readonly=False) as raw: + ptable = GPTPartitionTable(raw) + self.size = ptable.shrink(new_size, self.size) else: self.size = min(new_size + 2048 * sector_size, self.size) - self.out.success("new size is %dMB" % ((self.size + MB - 1) // MB)) + if not silent: + self.out.success("Image size is %dMB" % + ((self.size + MB - 1) // MB)) return self.size @@ -397,30 +422,57 @@ class Image(object): partition table. Empty space in the end of the device will be ignored. """ MB = 2 ** 20 - blocksize = 4 * MB # 4MB - size = self.size - progr_size = (size + MB - 1) // MB # in MB + blocksize = 2 ** 22 # 4MB + progr_size = (self.size + MB - 1) // MB # in MB progressbar = self.out.Progress(progr_size, "Dumping image file", 'mb') - with open(self.device, 'r') as src: - with open(outfile, "w") as dst: - left = size - offset = 0 - progressbar.next() + with self.raw_device() as raw: + with open(raw, 'rb') as src: + with open(outfile, "wb") as dst: + left = self.size + offset = 0 + progressbar.next() + while left > 0: + length = min(left, blocksize) + sent = sendfile(dst.fileno(), src.fileno(), offset, + length) + + # Workaround for python-sendfile API change. In + # python-sendfile 1.2.x (py-sendfile) the returning + # value of sendfile is a tuple, where in version 2.x + # (pysendfile) it is just a single integer. + if isinstance(sent, tuple): + sent = sent[1] + + offset += sent + left -= sent + progressbar.goto((self.size - left) // MB) + + progressbar.success('image file %s was successfully created' % outfile) + + def md5(self): + """Computes the MD5 checksum of the image""" + + MB = 2 ** 20 + blocksize = 2 ** 22 # 4MB + progr_size = ((self.size + MB - 1) // MB) # in MB + progressbar = self.out.Progress(progr_size, "Calculating md5sum", 'mb') + md5 = hashlib.md5() + + with self.raw_device() as raw: + with open(raw, "rb") as src: + left = self.size while left > 0: length = min(left, blocksize) - sent = sendfile(dst.fileno(), src.fileno(), offset, length) - - # Workaround for python-sendfile API change. In - # python-sendfile 1.2.x (py-sendfile) the returning value - # of sendfile is a tuple, where in version 2.x (pysendfile) - # it is just a sigle integer. - if isinstance(sent, tuple): - sent = sent[1] - - offset += sent - left -= sent - progressbar.goto((size - left) // MB) - progressbar.success('image file %s was successfully created' % outfile) + data = src.read(length) + md5.update(data) + left -= length + progressbar.goto((self.size - left) // MB) + + checksum = md5.hexdigest() + progressbar.success(checksum) + + return checksum + # vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/kamaki_wrapper.py b/image_creator/kamaki_wrapper.py index 07df8d9c6ee10dd48a1aa352427e353d1db2674e..4f548a04661c1cf3c5e9c9ff0a9d0257ced0122d 100644 --- a/image_creator/kamaki_wrapper.py +++ b/image_creator/kamaki_wrapper.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This modules provides the interface for working with the ./kamaki library. The library is used to upload images to and register them with a Synnefo @@ -87,7 +69,7 @@ class Kamaki(object): @staticmethod def get_cloud_by_name(name): - """Returns a dict with cloud info""" + """Returns a dictionary with cloud info""" return config.get('cloud', name) @staticmethod @@ -104,7 +86,7 @@ class Kamaki(object): @staticmethod def remove_cloud(name): - """Deletes an existing cloud from the Kamaki configuration file""" + """Deletes an existing cloud from the ./Kamaki configuration file""" config.remove_option('cloud', name) config.write() @@ -149,7 +131,7 @@ class Kamaki(object): self.account.token) def upload(self, file_obj, size=None, remote_path=None, hp=None, up=None): - """Upload a file to pithos""" + """Upload a file to Pithos+""" path = basename(file_obj.name) if remote_path is None else remote_path @@ -168,7 +150,7 @@ class Kamaki(object): self.CONTAINER, path) def register(self, name, location, metadata, public=False): - """Register an image with cyclades""" + """Register an image with Cyclades""" # Convert all metadata to strings str_metadata = {} @@ -184,7 +166,7 @@ class Kamaki(object): self.pithos.set_object_sharing(location, "*") def object_exists(self, location): - """Check if an object exists in pythos""" + """Check if an object exists in Pithos+""" try: self.pithos.get_object_info(location) diff --git a/image_creator/main.py b/image_creator/main.py index ccf51258860d6f9abbae5ca816cb185601e03d45..4dffc5c46c3a8e0165da1aee9ca1738eb8cc47a0 100644 --- a/image_creator/main.py +++ b/image_creator/main.py @@ -1,38 +1,20 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module is the entrance point for the non-interactive version of the snf-image-creator program. @@ -40,7 +22,7 @@ snf-image-creator program. from image_creator import __version__ as version from image_creator.disk import Disk -from image_creator.util import FatalError, MD5 +from image_creator.util import FatalError from image_creator.output.cli import SilentOutput, SimpleOutput, \ OutputWthProgress from image_creator.kamaki_wrapper import Kamaki, ClientError @@ -122,27 +104,33 @@ def parse_options(input_args): "input media", default=[], action="append", metavar="SYSPREP") + parser.add_option("--install-virtio", dest="virtio", type="string", + help="install VirtIO drivers hosted under DIR " + "(Windows only)", metavar="DIR") parser.add_option("--print-sysprep-params", dest="print_sysprep_params", - default=False, help="print the needed sysprep parameters" - " for this input media", action="store_true") + default=False, action="store_true", + help="print the defined system preparation parameters " + "for this input media") parser.add_option("--sysprep-param", dest="sysprep_params", default=[], - help="Add KEY=VALUE system preparation parameter", + help="add KEY=VALUE system preparation parameter", action="append") parser.add_option("--no-sysprep", dest="sysprep", default=True, help="don't perform any system preparation operation", action="store_false") - parser.add_option("--no-shrink", dest="shrink", default=True, - help="don't shrink any partition", action="store_false") + parser.add_option("--no-snapshot", dest="snapshot", default=True, + help="don't snapshot the input media. (THIS IS " + "DANGEROUS AS IT WILL ALTER THE ORIGINAL MEDIA!!!)", + action="store_false") parser.add_option("--public", dest="public", default=False, help="register image with the cloud as public", action="store_true") parser.add_option("--allow-unsupported", dest="allow_unsupported", - help="Proceed with the image creation even if the media " + help="proceed with the image creation even if the media " "is not supported", default=False, action="store_true") parser.add_option("--tmpdir", dest="tmp", type="string", default=None, @@ -188,9 +176,13 @@ def parse_options(input_args): try: key, value = p.split('=', 1) except ValueError: - raise FatalError("Sysprep parameter optiont: `%s' is not in " + raise FatalError("Sysprep parameter option: `%s' is not in " "KEY=VALUE format." % p) sysprep_params[key] = value + + if options.virtio is not None: + sysprep_params['virtio'] = options.virtio + options.sysprep_params = sysprep_params return options @@ -246,7 +238,7 @@ def image_creator(): account = Kamaki.get_account(options.cloud) if account is None: raise FatalError( - "Cloud: `$s' exists but is not valid!" % options.cloud) + "Cloud: `%s' exists but is not valid!" % options.cloud) else: kamaki = Kamaki(account, out) except ClientError as e: @@ -274,9 +266,10 @@ def image_creator(): signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) try: - snapshot = disk.snapshot() - - image = disk.get_image(snapshot, sysprep_params=options.sysprep_params) + # There is no need to snapshot the media if it was created by the Disk + # instance as a temporary object. + device = disk.file if not options.snapshot else disk.snapshot() + image = disk.get_image(device, sysprep_params=options.sysprep_params) if image.is_unsupported() and not options.allow_unsupported: raise FatalError( @@ -305,12 +298,14 @@ def image_creator(): if options.outfile is None and not options.upload: return 0 + if options.virtio is not None and \ + hasattr(image.os, 'install_virtio_drivers'): + image.os.install_virtio_drivers() + if options.sysprep: image.os.do_sysprep() metadata = image.os.meta - - size = options.shrink and image.shrink() or image.size metadata.update(image.meta) if image.is_unsupported(): @@ -319,8 +314,7 @@ def image_creator(): # Add command line metadata to the collected ones... metadata.update(options.metadata) - md5 = MD5(out) - checksum = md5.compute(image.device, size) + checksum = image.md5() metastring = unicode(json.dumps( {'properties': metadata, @@ -340,19 +334,17 @@ def image_creator(): os.path.basename(options.outfile))) out.success('done') - # Destroy the image instance. We only need the snapshot from now on - disk.destroy_image(image) - out.output() try: - uploaded_obj = "" if options.upload: out.output("Uploading image to the storage service:") - with open(snapshot, 'rb') as f: - uploaded_obj = kamaki.upload( - f, size, options.upload, - "(1/3) Calculating block hashes", - "(2/3) Uploading missing blocks") + with image.raw_device() as raw: + with open(raw, 'rb') as f: + remote = kamaki.upload( + f, image.size, options.upload, + "(1/3) Calculating block hashes", + "(2/3) Uploading missing blocks") + out.output("(3/3) Uploading md5sum file ...", False) md5sumstr = '%s %s\n' % (checksum, os.path.basename(options.upload)) @@ -366,7 +358,7 @@ def image_creator(): img_type = 'public' if options.public else 'private' out.output('Registering %s image with the compute service ...' % img_type, False) - result = kamaki.register(options.register, uploaded_obj, + result = kamaki.register(options.register, remote, metadata, options.public) out.success('done') out.output("Uploading metadata file ...", False) @@ -398,14 +390,9 @@ def image_creator(): def main(): try: - ret = image_creator() - sys.exit(ret) + sys.exit(image_creator()) except FatalError as e: colored = sys.stderr.isatty() - warning = \ - "The name of the executable has changed. If you want to use the " \ - "user-friendly dialog-based program try `snf-image-creator'" - SimpleOutput(colored).warn(warning) SimpleOutput(colored).error(e) sys.exit(1) diff --git a/image_creator/os_type/__init__.py b/image_creator/os_type/__init__.py index ce8413034d0601f554131f655d0fa45c4a21406d..2af3d044edcebf596b98a9c02c567f09c5980cdc 100644 --- a/image_creator/os_type/__init__.py +++ b/image_creator/os_type/__init__.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This package provides various classes for preparing different Operating Systems for image creation. @@ -46,17 +28,27 @@ from functools import wraps def os_cls(distro, osfamily): - """Given the distro name and the osfamily, return the appropriate class""" - module = None - classname = None + """Given the distro name and the osfamily, return the appropriate OSBase + derived class + """ + + # hyphens are not allowed in module names + canonicalize = lambda x: x.replace('-', '_').lower() + + distro = canonicalize(distro) + osfamily = canonicalize(osfamily) + try: module = __import__("image_creator.os_type.%s" % distro, fromlist=['image_creator.os_type']) classname = distro.capitalize() except ImportError: - module = __import__("image_creator.os_type.%s" % osfamily, - fromlist=['image_creator.os_type']) - classname = osfamily.capitalize() + try: + module = __import__("image_creator.os_type.%s" % osfamily, + fromlist=['image_creator.os_type']) + classname = osfamily.capitalize() + except ImportError: + raise FatalError("Unknown OS name: `%s'" % osfamily) return getattr(module, classname) @@ -72,12 +64,15 @@ def add_prefix(target): def sysprep(message, enabled=True, **kwargs): """Decorator for system preparation tasks""" def wrapper(method): - method.sysprep = True - method.enabled = enabled - method.executed = False + assert method.__name__.startswith('_'), \ + "Invalid sysprep name:` %s'. Should start with _" % method.__name__ + + method._sysprep = True + method._sysprep_enabled = enabled + method._sysprep_nomount = False for key, val in kwargs.items(): - setattr(method, key, val) + setattr(method, "_sysprep_%s" % key, val) @wraps(method) def inner(self, print_message=True): @@ -89,18 +84,98 @@ def sysprep(message, enabled=True, **kwargs): return wrapper -def add_sysprep_param(name, type, default, descr, validate=lambda x: True): +class SysprepParam(object): + """This class represents a system preparation parameter""" + + def __init__(self, type, default, description, **kargs): + + assert hasattr(self, "_check_%s" % type), "Invalid type: %s" % type + + self.type = type + self.default = default + self.description = description + self.value = default + self.error = None + self.check = kargs['check'] if 'check' in kargs else lambda x: x + self.hidden = kargs['hidden'] if 'hidden' in kargs else False + + def set_value(self, value): + """Update the value of the parameter""" + + check_type = getattr(self, "_check_%s" % self.type) + try: + self.value = self.check(check_type(value)) + except ValueError as e: + self.error = e.message + return False + return True + + def _check_posint(self, value): + """Check if the value is a positive integer""" + try: + value = int(value) + except ValueError: + raise ValueError("Invalid number") + + if value <= 0: + raise ValueError("Value is negative or zero") + + return value + + def _check_string(self, value): + """Check if a value is a string""" + return str(value) + + def _check_file(self, value): + """Check if the value is a valid filename""" + + value = str(value) + if len(value) == 0: + return "" + + import os + + def isblockdev(filename): + import stat + try: + return stat.S_ISBLK(os.stat(filename).st_mode) + except OSError: + return False + if os.path.isfile(value) or isblockdev(value): + return value + + raise ValueError("Invalid filename") + + def _check_dir(self, value): + """Check if the value is a valid directory""" + + value = str(value) + if len(value) == 0: + return "" + + import os + if os.path.isdir(value): + return value + + raise ValueError("Invalid dirname") + + +def add_sysprep_param(name, type, default, descr, **kargs): """Decorator for __init__ that adds the definition for a system preparation - parameter in an instance of a os_type class + parameter in an instance of an os_type class """ + extra = kargs + def wrapper(init): @wraps(init) def inner(self, *args, **kwargs): + + if not hasattr(self, 'sysprep_params'): + self.sysprep_params = {} + + self.sysprep_params[name] = \ + SysprepParam(type, default, descr, **extra) init(self, *args, **kwargs) - self.needed_sysprep_params[name] = \ - self.SysprepParam(type, default, descr, validate) - if default is not None: - self.sysprep_params[name] = default return inner return wrapper @@ -112,7 +187,7 @@ def del_sysprep_param(name): def wrapper(func): @wraps(func) def inner(self, *args, **kwargs): - del self.needed_sysprep_params[name] + del self.sysprep_params[name] func(self, *args, **kwargs) return inner return wrapper @@ -121,21 +196,33 @@ def del_sysprep_param(name): class OSBase(object): """Basic operating system class""" - SysprepParam = namedtuple('SysprepParam', - ['type', 'default', 'description', 'validate']) - def __init__(self, image, **kargs): self.image = image self.root = image.root self.out = image.out - self.needed_sysprep_params = {} - self.sysprep_params = \ - kargs['sysprep_params'] if 'sysprep_params' in kargs else {} + # Could be defined in a decorator + if not hasattr(self, 'sysprep_params'): + self.sysprep_params = {} + + if 'sysprep_params' in kargs: + for key, val in kargs['sysprep_params'].items(): + if key not in self.sysprep_params: + self.out.warn("Ignoring invalid `%s' parameter." % key) + continue + param = self.sysprep_params[key] + if not param.set_value(val): + raise FatalError("Invalid value for sysprep parameter: " + "`%s'. Reason: %s" % (key, param.error)) self.meta = {} - self.mounted = False + self.shrinked = False + + # This will host the error if mount fails + self._mount_error = "" + self._mount_warnings = [] + self._mounted = False # Many guestfs compilations don't support scrub self._scrub_support = True @@ -144,6 +231,37 @@ class OSBase(object): except RuntimeError: self._scrub_support = False + # Create a list of available syspreps + self._sysprep_tasks = {} + for name in dir(self): + obj = getattr(self, name) + if not hasattr(obj, '_sysprep'): + continue + self._sysprep_tasks[name] = obj._sysprep_enabled + + self._cleanup_jobs = {} + + def _add_cleanup(self, namespace, job, *args): + """Add a new job in a cleanup list""" + + if namespace not in self._cleanup_jobs: + self._cleanup_jobs[namespace] = [] + + self._cleanup_jobs[namespace].append((job, args)) + + def _cleanup(self, namespace): + """Run the cleanup tasks that are defined under a specific namespace""" + + if namespace not in self._cleanup_jobs: + self.out.warn("Cleanup namespace: `%s' is not defined", namespace) + return + + while len(self._cleanup_jobs[namespace]): + job, args = self._cleanup_jobs[namespace].pop() + job(*args) + + del self._cleanup_jobs[namespace] + def inspect(self): """Inspect the media to check if it is supported""" @@ -151,76 +269,80 @@ class OSBase(object): return self.out.output('Running OS inspection:') - try: - if not self.mount(readonly=True): - raise FatalError("Unable to mount the media read-only") + with self.mount(readonly=True, silent=True): self._do_inspect() - finally: - self.umount() - self.out.output() def collect_metadata(self): """Collect metadata about the OS""" - try: - if not self.mount(readonly=True): - raise FatalError("Unable to mount the media read-only") - self.out.output('Collecting image metadata ...', False) + self.out.output('Collecting image metadata ...', False) + + with self.mount(readonly=True, silent=True): self._do_collect_metadata() - self.out.success('done') - finally: - self.umount() + self.out.success('done') self.out.output() def list_syspreps(self): """Returns a list of sysprep objects""" - objs = [getattr(self, name) for name in dir(self) - if not name.startswith('_')] - - return [x for x in objs if self._is_sysprep(x) and x.executed is False] + return [getattr(self, name) for name in self._sysprep_tasks] def sysprep_info(self, obj): """Returns information about a sysprep object""" - assert self._is_sysprep(obj), "Object is not a sysprep" + assert hasattr(obj, '_sysprep'), "Object is not a sysprep" - SysprepInfo = namedtuple("SysprepInfo", "name description") + SysprepInfo = namedtuple("SysprepInfo", "name description display") - return SysprepInfo(obj.__name__.replace('_', '-'), - textwrap.dedent(obj.__doc__)) + name = obj.__name__.replace('_', '-')[1:] + description = textwrap.dedent(obj.__doc__) + display = getattr(obj, '_sysprep_display', + name.replace('-', ' ').capitalize()) + + return SysprepInfo(name, description, display) def get_sysprep_by_name(self, name): """Returns the sysprep object with the given name""" error_msg = "Syprep operation %s does not exist for %s" % \ (name, self.__class__.__name__) - method_name = name.replace('-', '_') - method = None - try: + method_name = '_' + name.replace('-', '_') + + if hasattr(self, method_name): method = getattr(self, method_name) - except AttributeError: - raise FatalError(error_msg) - if not self._is_sysprep(method): - raise FatalError(error_msg) + if hasattr(method, '_sysprep'): + return method - return method + raise FatalError(error_msg) def enable_sysprep(self, obj): """Enable a system preparation operation""" - setattr(obj.im_func, 'enabled', True) + assert hasattr(obj, '_sysprep'), "Object is not a sysprep" + assert obj.__name__ in self._sysprep_tasks, "Sysprep already executed" + + self._sysprep_tasks[obj.__name__] = True def disable_sysprep(self, obj): """Disable a system preparation operation""" - setattr(obj.im_func, 'enabled', False) + assert hasattr(obj, '_sysprep'), "Object is not a sysprep" + assert obj.__name__ in self._sysprep_tasks, "Sysprep already executed" + + self._sysprep_tasks[obj.__name__] = False + + def sysprep_enabled(self, obj): + """Returns True if this system praparation operation is enabled""" + assert hasattr(obj, '_sysprep'), "Object is not a sysprep" + assert obj.__name__ in self._sysprep_tasks, "Sysprep already executed" + + return self._sysprep_tasks[obj.__name__] def print_syspreps(self): """Print enabled and disabled system preparation operations.""" syspreps = self.list_syspreps() - enabled = [sysprep for sysprep in syspreps if sysprep.enabled] - disabled = [sysprep for sysprep in syspreps if not sysprep.enabled] + enabled = [s for s in syspreps if self.sysprep_enabled(s)] + disabled = [s for s in syspreps if not self.sysprep_enabled(s)] wrapper = textwrap.TextWrapper() wrapper.subsequent_indent = '\t' @@ -232,7 +354,7 @@ class OSBase(object): self.out.output("(none)") else: for sysprep in enabled: - name = sysprep.__name__.replace('_', '-') + name = sysprep.__name__.replace('_', '-')[1:] descr = wrapper.fill(textwrap.dedent(sysprep.__doc__)) self.out.output(' %s:\n%s\n' % (name, descr)) @@ -241,24 +363,34 @@ class OSBase(object): self.out.output("(none)") else: for sysprep in disabled: - name = sysprep.__name__.replace('_', '-') + name = sysprep.__name__.replace('_', '-')[1:] descr = wrapper.fill(textwrap.dedent(sysprep.__doc__)) self.out.output(' %s:\n%s\n' % (name, descr)) def print_sysprep_params(self): """Print the system preparation parameter the user may use""" - self.out.output("Needed system preparation parameters:") + self.out.output("System preparation parameters:") + self.out.output() - if len(self.needed_sysprep_params) == 0: + public_params = [(n, p) for n, p in self.sysprep_params.items() + if not p.hidden] + if len(public_params) == 0: self.out.output("(none)") return - for name, param in self.needed_sysprep_params.items(): - self.out.output("\t%s [%s]: %s" % - (param.description, name, - self.sysprep_params[name] if name in - self.sysprep_params else "(none)")) + wrapper = textwrap.TextWrapper() + wrapper.subsequent_indent = " " + wrapper.width = 72 + + for name, param in public_params: + if param.hidden: + continue + self.out.output("NAME: %s" % name) + self.out.output("VALUE: %s" % param.value) + self.out.output( + wrapper.fill("DESCRIPTION: %s" % param.description)) + self.out.output() def do_sysprep(self): """Prepare system for image creation.""" @@ -270,51 +402,97 @@ class OSBase(object): "System preparation is disabled for unsupported media") return - try: - if not self.mount(readonly=False): - raise FatalError("Unable to mount the media read-write") + enabled = [s for s in self.list_syspreps() if self.sysprep_enabled(s)] + size = len(enabled) + cnt = 0 - enabled = [task for task in self.list_syspreps() if task.enabled] + def exec_sysprep(cnt, size, task): + self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False) + task() + del self._sysprep_tasks[task.__name__] - size = len(enabled) - cnt = 0 - for task in enabled: + with self.mount(): + for task in [t for t in enabled if t._sysprep_nomount is False]: cnt += 1 - self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False) - task() - setattr(task.im_func, 'executed', True) - finally: - self.umount() - - self.out.output() + exec_sysprep(cnt, size, task) - def mount(self, readonly=False): - """Mount image.""" + for task in [t for t in enabled if t._sysprep_nomount]: + cnt += 1 + exec_sysprep(cnt, size, task) - if getattr(self, "mounted", False): - return True - - mount_type = 'read-only' if readonly else 'read-write' - self.out.output("Mounting the media %s ..." % mount_type, False) - - if not self._do_mount(readonly): - return False - - self.mounted = True - self.out.success('done') - return True - - def umount(self): - """Umount all mounted filesystems.""" + self.out.output() - self.out.output("Umounting the media ...", False) - self.image.g.umount_all() - self.mounted = False - self.out.success('done') + @sysprep('Shrinking image (may take a while)', nomount=True) + def _shrink(self): + """Shrink the last file system and update the partition table""" + self.image.shrink() + self.shrinked = True + + @property + def ismounted(self): + return self._mounted + + def mount(self, readonly=False, silent=False, fatal=True): + """Returns a context manager for mounting an image""" + + parent = self + output = lambda msg='', nl=True: None if silent else self.out.output + success = lambda msg='', nl=True: None if silent else self.out.success + warn = lambda msg='', nl=True: None if silent else self.out.warn + + class Mount: + """The Mount context manager""" + def __enter__(self): + mount_type = 'read-only' if readonly else 'read-write' + output("Mounting the media %s ..." % mount_type, False) + + parent._mount_error = "" + del parent._mount_warnings[:] + + try: + parent._mounted = parent._do_mount(readonly) + except: + parent.image.g.umount_all() + raise + + if not parent.ismounted: + msg = "Unable to mount the media %s. Reason: %s" % \ + (mount_type, parent._mount_error) + if fatal: + raise FatalError(msg) + else: + warn(msg) + + for warning in parent._mount_warnings: + warn(warning) + + if parent.ismounted: + success('done') + + def __exit__(self, exc_type, exc_value, traceback): + output("Umounting the media ...", False) + parent.image.g.umount_all() + parent._mounted = False + success('done') + + return Mount() + + def check_version(self, major, minor): + """Checks the OS version against the one specified by the major, minor + tuple. + + Returns: + < 0 if the OS version is smaller than the specified one + = 0 if they are equal + > 0 if it is greater + """ + guestfs = self.image.g + for a, b in ((guestfs.inspect_get_major_version(self.root), major), + (guestfs.inspect_get_minor_version(self.root), minor)): + if a != b: + return a - b - def _is_sysprep(self, obj): - """Checks if an object is a sysprep""" - return getattr(obj, 'sysprep', False) and callable(obj) + return 0 @add_prefix def _ls(self, directory): @@ -331,12 +509,11 @@ class OSBase(object): The following options are allowed: - * maxdepth: If defined the action will not be performed on - files that are below this level of directories under the - directory parameter. + * maxdepth: If defined, the action will not be performed on files that + are below this level of directories under the directory parameter. - * ftype: The action will only be performed on files of this - type. For a list of all allowed filetypes, see here: + * ftype: The action will only be performed on files of this type. For a + list of all allowed file types, see here: http://libguestfs.org/guestfs.3.html#guestfs_readdir * exclude: Exclude all files that follow this pattern. @@ -374,6 +551,7 @@ class OSBase(object): def _do_inspect(self): """helper method for inspect""" + self.out.warn("No inspection method available") pass def _do_collect_metadata(self): @@ -399,7 +577,7 @@ class OSBase(object): self.image.g.mount_options( 'ro' if readonly else 'rw', self.root, '/') except RuntimeError as msg: - self.out.warn("unable to mount the root partition: %s" % msg) + self._mount_error = str(msg) return False return True diff --git a/image_creator/os_type/freebsd.py b/image_creator/os_type/freebsd.py index 145be3e4080e13964efe4f5d899acfbb16df6a12..08c734f12420c04d7a856332d689fc9f6ce42c7e 100644 --- a/image_creator/os_type/freebsd.py +++ b/image_creator/os_type/freebsd.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code for FreeBSD.""" @@ -41,10 +23,10 @@ import re class Freebsd(Unix): - """OS class for FreeBSD Unix-like os""" + """OS class for FreeBSD Unix-like operating system""" @sysprep("Cleaning up passwords & locking all user accounts") - def cleanup_password(self): + def _cleanup_password(self): """Remove all passwords and lock all user accounts""" master_passwd = [] @@ -73,7 +55,7 @@ class Freebsd(Unix): super(Freebsd, self)._do_collect_metadata() self.meta["USERS"] = " ".join(self._get_passworded_users()) - #The original product name key is long and ugly + # The original product name key is long and ugly self.meta['DESCRIPTION'] = \ self.meta['DESCRIPTION'].split('#')[0].strip() @@ -120,9 +102,9 @@ class Freebsd(Unix): critical_mpoints = ('/', '/etc', '/root', '/home', '/var') - # libguestfs can't handle correct freebsd partitions on a GUID - # Partition Table. We have to do the translation to linux device names - # ourselves + # Older libguestfs versions can't handle correct FreeBSD partitions on + # a GUID Partition Table. We have to do the translation to Linux device + # names ourselves guid_device = re.compile(r'^/dev/((?:ada)|(?:vtbd))(\d+)p(\d+)$') mopts = "ufstype=ufs2,%s" % ('ro' if readonly else 'rw') @@ -136,10 +118,10 @@ class Freebsd(Unix): self.image.g.mount_vfs(mopts, 'ufs', dev, mp) except RuntimeError as msg: if mp in critical_mpoints: - self.out.warn('unable to mount %s. Reason: %s' % (mp, msg)) + self._mount_error = str(msg) return False else: - self.out.warn('%s (ignored)' % msg) + self._mount_warnings.append('%s (ignored)' % msg) return True diff --git a/image_creator/os_type/hurd.py b/image_creator/os_type/hurd.py index 2f3e82c968fac6de179c7f9aeb80a48ec7969525..eedbe6643b08fab010c6284b3a11b1076c93d3d6 100644 --- a/image_creator/os_type/hurd.py +++ b/image_creator/os_type/hurd.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code for GNU Hurd.""" diff --git a/image_creator/os_type/linux.py b/image_creator/os_type/linux.py index 53e8a5a8ba79416f97ae693cae1dc23f613dc6a6..c5b82a0d8df0c385447a64eaa5b4a87af032fee2 100644 --- a/image_creator/os_type/linux.py +++ b/image_creator/os_type/linux.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code for Linux""" @@ -49,7 +31,7 @@ class Linux(Unix): self._persistent = re.compile('/dev/[hsv]d[a-z][1-9]*') @sysprep('Removing user accounts with id greater that 1000', enabled=False) - def remove_user_accounts(self): + def _remove_user_accounts(self): """Remove all user accounts with id greater than 1000""" if 'USERS' not in self.meta: @@ -102,7 +84,7 @@ class Linux(Unix): self.image.g.rm_rf(home) @sysprep('Cleaning up password & locking all user accounts') - def cleanup_passwords(self): + def _cleanup_passwords(self): """Remove all passwords and lock all user accounts""" shadow = [] @@ -120,7 +102,7 @@ class Linux(Unix): self.image.g.rm_rf('/etc/shadow-') @sysprep('Fixing acpid powerdown action') - def fix_acpid(self): + def _fix_acpid(self): """Replace acpid powerdown action scripts to immediately shutdown the system without checking if a GUI is running. """ @@ -170,15 +152,15 @@ class Linux(Unix): elif event.strip() == ".*": self.out.warn("Found action `.*'. Don't know how to handle " "this. Please edit `%s' image file manually to " - "make the system immediatelly shutdown when an " - "power button acpi event occures." % + "make the system immediately shutdown when an " + "power button ACPI event occurs." % action.strip().split()[0]) return self.out.warn("No acpi power button event found!") @sysprep('Removing persistent network interface names') - def remove_persistent_net_rules(self): + def _remove_persistent_net_rules(self): """Remove udev rules that will keep network interface names persistent after hardware changes and reboots. Those rules will be created again the next time the image runs. @@ -189,7 +171,7 @@ class Linux(Unix): self.image.g.rm(rule_file) @sysprep('Removing swap entry from fstab') - def remove_swap_entry(self): + def _remove_swap_entry(self): """Remove swap entry from /etc/fstab. If swap is the last partition then the partition will be removed when shrinking is performed. If the swap partition is not the last partition in the disk or if you are not @@ -209,7 +191,7 @@ class Linux(Unix): self.image.g.write('/etc/fstab', new_fstab) @sysprep('Replacing fstab & grub non-persistent device references') - def use_persistent_block_device_names(self): + def _use_persistent_block_device_names(self): """Scan fstab & grub configuration files and replace all non-persistent device references with UUIDs. """ @@ -221,7 +203,7 @@ class Linux(Unix): self._persistent_grub1(persistent_root) def _persistent_grub1(self, new_root): - """Replaces non-persistent device name occurencies with persistent + """Replaces non-persistent device name occurrences with persistent ones in GRUB1 configuration files. """ if self.image.g.is_file('/boot/grub/menu.lst'): @@ -247,7 +229,7 @@ class Linux(Unix): self.image.g.aug_close() def _persistent_fstab(self): - """Replaces non-persistent device name occurencies in /etc/fstab with + """Replaces non-persistent device name occurrences in /etc/fstab with persistent ones. """ mpoints = self.image.g.mountpoints() diff --git a/image_creator/os_type/netbsd.py b/image_creator/os_type/netbsd.py index f8c7863259433e3b187ed87b4b5103e12a6042a1..002c5c838a2aa15ddc9e8d1663724b76c5a41730 100644 --- a/image_creator/os_type/netbsd.py +++ b/image_creator/os_type/netbsd.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code for NetBSD.""" diff --git a/image_creator/os_type/rhel.py b/image_creator/os_type/rhel.py new file mode 100644 index 0000000000000000000000000000000000000000..5d37a37df50d4d4a5f0f5778dff0a84acca4530e --- /dev/null +++ b/image_creator/os_type/rhel.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011-2014 GRNET S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +"""This module hosts OS-specific code for Red Hat Enterprise Linux""" + +from image_creator.os_type.linux import Linux + + +class Rhel(Linux): + "OS class for Red Hat Enterprise Linux""" + + def _do_collect_metadata(self): + """Collect metadata about the OS""" + super(Rhel, self)._do_collect_metadata() + + # Check if the image is Oracle Linux + oracle = '/etc/oracle-release' + if self.image.g.is_file(oracle): + self.meta['OS'] = 'oraclelinux' + self.meta['DESCRIPTION'] = self.image.g.head_n(1, oracle)[0] + + +# vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/os_type/slackware.py b/image_creator/os_type/slackware.py index 91c4a37195c732c0ad34b5cc97d662ec6a7101f5..6914e023b0ce25b9f65b7170f77869ad28cc80ae 100644 --- a/image_creator/os_type/slackware.py +++ b/image_creator/os_type/slackware.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code for Slackware Linux""" @@ -41,10 +23,10 @@ from image_creator.os_type.linux import Linux, sysprep class Slackware(Linux): """OS class for Slackware Linux""" @sysprep("Emptying all files under /var/log") - def cleanup_log(self): + def _cleanup_log(self): """Empty all files under /var/log""" - # In slackware the metadata about installed packages are + # In Slackware the metadata about installed packages are # stored in /var/log/packages. Clearing all /var/log files # will destroy the package management system. self._foreach_file('/var/log', self.image.g.truncate, ftype='r', diff --git a/image_creator/os_type/ubuntu.py b/image_creator/os_type/ubuntu.py index 0647c6fab48c4555f23311d0df01b992e6dce0ee..570fd32eaba52f5d5843e43cf823599c6cb7b968 100644 --- a/image_creator/os_type/ubuntu.py +++ b/image_creator/os_type/ubuntu.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code for Ubuntu Linux""" diff --git a/image_creator/os_type/unix.py b/image_creator/os_type/unix.py index f29c752dd6687285fd1e4d577e1e75bf228426dd..27fa2a8b2bf8feedb365e92f5ff8f66f5d7cbd94 100644 --- a/image_creator/os_type/unix.py +++ b/image_creator/os_type/unix.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts OS-specific code common to all Unix-like OSs.""" @@ -42,7 +24,9 @@ class Unix(OSBase): """OS class for Unix""" sensitive_userdata = [ '.history', + '.sh_history', '.bash_history', + '.zsh_history', '.gnupg', '.ssh', '.kamakirc', @@ -79,34 +63,34 @@ class Unix(OSBase): self.image.g.mount_options(mopts, dev, mp) except RuntimeError as msg: if mp in critical_mpoints: - self.out.warn('unable to mount %s. Reason: %s' % (mp, msg)) + self._mount_error = str(msg) return False else: - self.out.warn('%s (ignored)' % msg) + self._mount_warnings.append('%s (ignored)' % msg) return True @sysprep('Removing files under /var/cache') - def cleanup_cache(self): + def _cleanup_cache(self): """Remove all regular files under /var/cache""" self._foreach_file('/var/cache', self.image.g.rm, ftype='r') @sysprep('Removing files under /tmp and /var/tmp') - def cleanup_tmp(self): + def _cleanup_tmp(self): """Remove all files under /tmp and /var/tmp""" self._foreach_file('/tmp', self.image.g.rm_rf, maxdepth=1) self._foreach_file('/var/tmp', self.image.g.rm_rf, maxdepth=1) @sysprep('Emptying all files under /var/log') - def cleanup_log(self): + def _cleanup_log(self): """Empty all files under /var/log""" self._foreach_file('/var/log', self.image.g.truncate, ftype='r') @sysprep('Removing files under /var/mail & /var/spool/mail', enabled=False) - def cleanup_mail(self): + def _cleanup_mail(self): """Remove all files under /var/mail and /var/spool/mail""" self._foreach_file('/var/spool/mail', self.image.g.rm_rf, maxdepth=1) @@ -114,8 +98,8 @@ class Unix(OSBase): self._foreach_file('/var/mail', self.image.g.rm_rf, maxdepth=1) @sysprep('Removing sensitive user data') - def cleanup_userdata(self): - """Delete sensitive userdata""" + def _cleanup_userdata(self): + """Delete sensitive user data""" homedirs = ['/root'] if self.image.g.is_dir('/home/'): diff --git a/image_creator/os_type/unsupported.py b/image_creator/os_type/unsupported.py index 9b27b7bea17fd4125fe389fdf68edcae308fcbee..93b711f92ef8c16f42aa97f4a1fdaab4f388b9ef 100644 --- a/image_creator/os_type/unsupported.py +++ b/image_creator/os_type/unsupported.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2013 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module hosts code to handle unknown OSs.""" @@ -48,8 +30,8 @@ class Unsupported(OSBase): self.out.warn("Unable to collect metadata for unsupported media") def _do_mount(self, readonly): - """Mount partitions in corrent order""" - self.out.warn('not supported on this media.') + """Mount partitions in correct order""" + self._mount_error = "not supported on this media" return False # vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/os_type/windows.py b/image_creator/os_type/windows.py deleted file mode 100644 index f585dbdb88e7d92ae429d1aae10e3070206c83d4..0000000000000000000000000000000000000000 --- a/image_creator/os_type/windows.py +++ /dev/null @@ -1,857 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2012 GRNET S.A. All rights reserved. -# -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: -# -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. -# -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. - -"""This module hosts OS-specific code common for the various Microsoft -Windows OSs.""" - -from image_creator.os_type import OSBase, sysprep, add_sysprep_param -from image_creator.util import FatalError, get_kvm_binary -from image_creator.winexe import WinEXE, WinexeTimeout - -import hivex -import tempfile -import os -import signal -import time -import random -import string -import subprocess -import struct -import re - -# For more info see: http://technet.microsoft.com/en-us/library/jj612867.aspx -KMS_CLIENT_SETUP_KEYS = { - "Windows 8.1 Professional": "GCRJD-8NW9H-F2CDX-CCM8D-9D6T9", - "Windows 8.1 Professional N": "HMCNV-VVBFX-7HMBH-CTY9B-B4FXY", - "Windows 8.1 Enterprise": "MHF9N-XY6XB-WVXMC-BTDCT-MKKG7", - "Windows 8.1 Enterprise N": "TT4HM-HN7YT-62K67-RGRQJ-JFFXW", - "Windows Server 2012 R2 Server Standard": "D2N9P-3P6X9-2R39C-7RTCD-MDVJX", - "Windows Server 2012 R2 Datacenter": "W3GGN-FT8W3-Y4M27-J84CP-Q3VJ9", - "Windows Server 2012 R2 Essentials": "KNC87-3J2TX-XB4WP-VCPJV-M4FWM", - "Windows 8 Professional": "NG4HW-VH26C-733KW-K6F98-J8CK4", - "Windows 8 Professional N": "XCVCF-2NXM9-723PB-MHCB7-2RYQQ", - "Windows 8 Enterprise": "32JNW-9KQ84-P47T8-D8GGY-CWCK7", - "Windows 8 Enterprise N": "JMNMF-RHW7P-DMY6X-RF3DR-X2BQT", - "Windows Server 2012 Core": "BN3D2-R7TKB-3YPBD-8DRP2-27GG4", - "Windows Server 2012 Core N": "8N2M2-HWPGY-7PGT9-HGDD8-GVGGY", - "Windows Server 2012 Core Single Language": - "2WN2H-YGCQR-KFX6K-CD6TF-84YXQ", - "Windows Server 2012 Core Country Specific": - "4K36P-JN4VD-GDC6V-KDT89-DYFKP", - "Windows Server 2012 Server Standard": "XC9B7-NBPP2-83J2H-RHMBY-92BT4", - "Windows Server 2012 Standard Core": "XC9B7-NBPP2-83J2H-RHMBY-92BT4", - "Windows Server 2012 MultiPoint Standard": "HM7DN-YVMH3-46JC3-XYTG7-CYQJJ", - "Windows Server 2012 MultiPoint Premium": "XNH6W-2V9GX-RGJ4K-Y8X6F-QGJ2G", - "Windows Server 2012 Datacenter": "48HP8-DN98B-MYWDG-T2DCC-8W83P", - "Windows Server 2012 Datacenter Core": "48HP8-DN98B-MYWDG-T2DCC-8W83P", - "Windows 7 Professional": "FJ82H-XT6CR-J8D7P-XQJJ2-GPDD4", - "Windows 7 Professional N": "MRPKT-YTG23-K7D7T-X2JMM-QY7MG", - "Windows 7 Professional E": "W82YF-2Q76Y-63HXB-FGJG9-GF7QX", - "Windows 7 Enterprise": "33PXH-7Y6KF-2VJC9-XBBR8-HVTHH", - "Windows 7 Enterprise N": "YDRBP-3D83W-TY26F-D46B2-XCKRJ", - "Windows 7 Enterprise E": "C29WB-22CC8-VJ326-GHFJW-H9DH4", - "Windows Server 2008 R2 Web": "6TPJF-RBVHG-WBW2R-86QPH-6RTM4", - "Windows Server 2008 R2 HPC edition": "TT8MH-CG224-D3D7Q-498W2-9QCTX", - "Windows Server 2008 R2 Standard": "YC6KT-GKW9T-YTKYR-T4X34-R7VHC", - "Windows Server 2008 R2 Enterprise": "489J6-VHDMP-X63PK-3K798-CPX3Y", - "Windows Server 2008 R2 Datacenter": "74YFP-3QFB3-KQT8W-PMXWJ-7M648", - "Windows Server 2008 R2 for Itanium-based Systems": - "GT63C-RJFQ3-4GMB6-BRFB9-CB83V", - "Windows Vista Business": "YFKBB-PQJJV-G996G-VWGXY-2V3X8", - "Windows Vista Business N": "HMBQG-8H2RH-C77VX-27R82-VMQBT", - "Windows Vista Enterprise": "VKK3X-68KWM-X2YGT-QR4M6-4BWMV", - "Windows Vista Enterprise N": "VTC42-BM838-43QHV-84HX6-XJXKV", - "Windows Web Server 2008": "WYR28-R7TFJ-3X2YQ-YCY4H-M249D", - "Windows Server 2008 Standard": "TM24T-X9RMF-VWXK6-X8JC9-BFGM2", - "Windows Server 2008 Standard without Hyper-V": - "W7VD6-7JFBR-RX26B-YKQ3Y-6FFFJ", - "Windows Server 2008 Enterprise": - "YQGMW-MPWTJ-34KDK-48M3W-X4Q6V", - "Windows Server 2008 Enterprise without Hyper-V": - "39BXF-X8Q23-P2WWT-38T2F-G3FPG", - "Windows Server 2008 HPC": "RCTX3-KWVHP-BR6TB-RB6DM-6X7HP", - "Windows Server 2008 Datacenter": "7M67G-PC374-GR742-YH8V4-TCBY3", - "Windows Server 2008 Datacenter without Hyper-V": - "22XQ2-VRXRG-P8D42-K34TD-G3QQC", - "Windows Server 2008 for Itanium-Based Systems": - "4DWFP-JF3DJ-B7DTH-78FJB-PDRHK"} - -_POSINT = lambda x: type(x) == int and x >= 0 - - -class Windows(OSBase): - """OS class for Windows""" - @add_sysprep_param( - 'shutdown_timeout', int, 120, "Shutdown Timeout (seconds)", _POSINT) - @add_sysprep_param( - 'boot_timeout', int, 300, "Boot Timeout (seconds)", _POSINT) - @add_sysprep_param( - 'connection_retries', int, 5, "Connection Retries", _POSINT) - @add_sysprep_param( - 'smp', int, 1, "Number of CPUs for the helper VM", _POSINT) - @add_sysprep_param( - 'mem', int, 1024, "Virtual RAM size for the helper VM (MiB)", _POSINT) - @add_sysprep_param('password', str, None, 'Image Administrator Password') - def __init__(self, image, **kargs): - super(Windows, self).__init__(image, **kargs) - - # The commit with the following message was added in - # libguestfs 1.17.18 and was backported in version 1.16.11: - # - # When a Windows guest doesn't have a HKLM\SYSTEM\MountedDevices node, - # inspection fails. However inspection should not completely fail just - # because we cannot get the drive letter mapping from a guest. - # - # Since Microsoft Sysprep removes the aforementioned key, image - # creation for windows can only be supported if the installed guestfs - # version is 1.17.18 or higher - if self.image.check_guestfs_version(1, 17, 18) < 0 and \ - (self.image.check_guestfs_version(1, 17, 0) >= 0 or - self.image.check_guestfs_version(1, 16, 11) < 0): - raise FatalError( - 'For windows support libguestfs 1.16.11 or above is required') - - # Check if winexe is installed - if not WinEXE.is_installed(): - raise FatalError( - "For windows support `Winexe' needs to be installed") - - device = self.image.g.part_to_dev(self.root) - - self.last_part_num = self.image.g.part_list(device)[-1]['part_num'] - self.last_drive = None - self.system_drive = None - - for drive, part in self.image.g.inspect_get_drive_mappings(self.root): - if part == "%s%d" % (device, self.last_part_num): - self.last_drive = drive - if part == self.root: - self.system_drive = drive - - assert self.system_drive - - self.product_name = self.image.g.inspect_get_product_name(self.root) - self.syspreped = False - - @sysprep('Disabling IPv6 privacy extensions') - def disable_ipv6_privacy_extensions(self): - """Disable IPv6 privacy extensions""" - - self._guest_exec('netsh interface ipv6 set global ' - 'randomizeidentifiers=disabled store=persistent') - - @sysprep('Disabling Teredo interface') - def disable_teredo(self): - """Disable Teredo interface""" - - self._guest_exec('netsh interface teredo set state disabled') - - @sysprep('Disabling ISATAP Adapters') - def disable_isatap(self): - """Disable ISATAP Adapters""" - - self._guest_exec('netsh interface isa set state disabled') - - @sysprep('Enabling ping responses') - def enable_pings(self): - """Enable ping responses""" - - self._guest_exec('netsh firewall set icmpsetting 8') - - @sysprep('Disabling hibernation support') - def disable_hibernation(self): - """Disable hibernation support and remove the hibernation file""" - - self._guest_exec(r'powercfg.exe /hibernate off') - - @sysprep('Setting the system clock to UTC') - def utc(self): - """Set the hardware clock to UTC""" - - path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation' - self._guest_exec( - r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path) - - @sysprep('Clearing the event logs') - def clear_logs(self): - """Clear all the event logs""" - - self._guest_exec( - "cmd /q /c for /f \"tokens=*\" %l in ('wevtutil el') do " - "wevtutil cl \"%l\"") - - @sysprep('Executing Sysprep on the image (may take more that 10 min)') - def microsoft_sysprep(self): - """Run the Microsoft System Preparation Tool. This will remove - system-specific data and will make the image ready to be deployed. - After this no other task may run. - """ - - self._guest_exec(r'C:\Windows\system32\sysprep\sysprep ' - r'/quiet /generalize /oobe /shutdown') - self.syspreped = True - - @sysprep('Converting the image into a KMS client', enabled=False) - def kms_client_setup(self): - """Install the appropriate KMS client setup key to the image to convert - it to a KMS client. Computers that are running volume licensing - editions of Windows 8, Windows Server 2012, Windows 7, Windows Server - 2008 R2, Windows Vista, and Windows Server 2008 are by default KMS - clients with no additional configuration needed. - """ - try: - setup_key = KMS_CLIENT_SETUP_KEYS[self.product_name] - except KeyError: - self.out.warn( - "Don't know the KMS client setup key for product: `%s'" % - self.product_name) - return - - self._guest_exec( - r"cscript \Windows\system32\slmgr.vbs /ipk %s" % setup_key) - - @sysprep('Shrinking the last filesystem') - def shrink(self): - """Shrink the last filesystem. Make sure the filesystem is defragged""" - - # Query for the maximum number of reclaimable bytes - cmd = ( - r'cmd /Q /V:ON /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' + - r'ECHO SELECT DISK 0 > %SCRIPT% & ' + - 'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num + - r'ECHO SHRINK QUERYMAX >> %SCRIPT% & ' + - r'ECHO EXIT >> %SCRIPT% & ' + - r'DISKPART /S %SCRIPT% & ' + - r'IF NOT !ERRORLEVEL! EQU 0 EXIT /B 1 & ' + - r'DEL /Q %SCRIPT%"') - - stdout, stderr, rc = self._guest_exec(cmd) - - querymax = None - for line in stdout.splitlines(): - # diskpart will return something like this: - # - # The maximum number of reclaimable bytes is: xxxx MB - # - if line.find('reclaimable') >= 0: - answer = line.split(':')[1].strip() - m = re.search('(\d+) MB', answer) - if m: - querymax = m.group(1) - else: - FatalError( - "Unexpected output for `shrink querymax' command: %s" % - line) - - if querymax is None: - FatalError("Error in shrinking! " - "Couldn't find the max number of reclaimable bytes!") - - querymax = int(querymax) - # From ntfsresize: - # Practically the smallest shrunken size generally is at around - # "used space" + (20-200 MB). Please also take into account that - # Windows might need about 50-100 MB free space left to boot safely. - # I'll give 100MB extra space just to be sure - querymax -= 100 - - if querymax < 0: - self.out.warn("Not enough available space to shrink the image!") - return - - self.out.output("\tReclaiming %dMB ..." % querymax) - - cmd = ( - r'cmd /Q /V:ON /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' + - r'ECHO SELECT DISK 0 > %SCRIPT% & ' + - 'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num + - 'ECHO SHRINK DESIRED=%d >> %%SCRIPT%% & ' % querymax + - r'ECHO EXIT >> %SCRIPT% & ' + - r'DISKPART /S %SCRIPT% & ' + - r'IF NOT !ERRORLEVEL! EQU 0 EXIT /B 1 & ' + - r'DEL /Q %SCRIPT%"') - - stdout, stderr, rc = self._guest_exec(cmd, False) - - if rc != 0: - FatalError("Shrinking failed. Please make sure the media is " - "defraged with a command like this: " - "`Defrag.exe /U /X /W'") - for line in stdout.splitlines(): - if line.find('shrunk') >= 0: - self.out.output(line) - - def do_sysprep(self): - """Prepare system for image creation.""" - - if getattr(self, 'syspreped', False): - raise FatalError("Image is already syspreped!") - - txt = "System preparation parameter: `%s' is needed but missing!" - for name, param in self.needed_sysprep_params.items(): - if name not in self.sysprep_params: - raise FatalError(txt % name) - - self.mount(readonly=False) - try: - disabled_uac = self._update_uac_remote_setting(1) - token = self._enable_os_monitor() - - # disable the firewalls - firewall_states = self._update_firewalls(0, 0, 0) - - # Delete the pagefile. It will be recreated when the system boots - systemroot = self.image.g.inspect_get_windows_systemroot(self.root) - try: - pagefile = "%s/pagefile.sys" % systemroot - self.image.g.rm_rf(self.image.g.case_sensitive_path(pagefile)) - except RuntimeError: - pass - - finally: - self.umount() - - self.image.disable_guestfs() - - vm = None - monitor = None - try: - self.out.output("Starting windows VM ...", False) - monitorfd, monitor = tempfile.mkstemp() - os.close(monitorfd) - vm = _VM(self.image.device, monitor, self.sysprep_params) - self.out.success("started (console on VNC display: %d)" % - vm.display) - - self.out.output("Waiting for OS to boot ...", False) - self._wait_vm_boot(vm, monitor, token) - self.out.success('done') - - self.out.output("Checking connectivity to the VM ...", False) - self._check_connectivity() - self.out.success('done') - - self.out.output("Disabling automatic logon ...", False) - self._disable_autologon() - self.out.success('done') - - self.out.output('Preparing system for image creation:') - - tasks = self.list_syspreps() - enabled = [task for task in tasks if task.enabled] - size = len(enabled) - - # Make sure shrink runs in the end, before ms sysprep - enabled = [task for task in enabled if - self.sysprep_info(task).name != 'shrink'] - - if len(enabled) != size: - enabled.append(self.shrink) - - # Make sure the ms sysprep is the last task to run if it is enabled - enabled = [task for task in enabled if - self.sysprep_info(task).name != 'microsoft-sysprep'] - - ms_sysprep_enabled = False - if len(enabled) != size: - enabled.append(self.microsoft_sysprep) - ms_sysprep_enabled = True - - cnt = 0 - for task in enabled: - cnt += 1 - self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False) - task() - setattr(task.im_func, 'executed', True) - - self.out.output("Sending shut down command ...", False) - if not ms_sysprep_enabled: - self._shutdown() - self.out.success("done") - - self.out.output("Waiting for windows to shut down ...", False) - vm.wait(self.sysprep_params['shutdown_timeout']) - self.out.success("done") - finally: - if monitor is not None: - os.unlink(monitor) - - try: - if vm is not None: - self.out.output("Destroying windows VM ...", False) - vm.destroy() - self.out.success("done") - finally: - self.image.enable_guestfs() - - self.mount(readonly=False) - try: - if disabled_uac: - self._update_uac_remote_setting(0) - - self._update_firewalls(*firewall_states) - finally: - self.umount() - - def _shutdown(self): - """Shuts down the windows VM""" - self._guest_exec(r'shutdown /s /t 5') - - def _wait_vm_boot(self, vm, fname, msg): - """Wait until a message appears on a file or the vm process dies""" - - for _ in range(self.sysprep_params['boot_timeout']): - time.sleep(1) - with open(fname) as f: - for line in f: - if line.startswith(msg): - return True - if not vm.isalive(): - raise FatalError("Windows VM died unexpectedly!") - - raise FatalError("Windows VM booting timed out!") - - def _disable_autologon(self): - """Disable automatic logon on the windows image""" - - winlogon = \ - r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"' - - self._guest_exec('REG DELETE %s /v DefaultUserName /f' % winlogon) - self._guest_exec('REG DELETE %s /v DefaultPassword /f' % winlogon) - self._guest_exec('REG DELETE %s /v AutoAdminLogon /f' % winlogon) - - def _registry_file_path(self, regfile): - """Retrieves the case sensitive path to a registry file""" - - systemroot = self.image.g.inspect_get_windows_systemroot(self.root) - path = "%s/system32/config/%s" % (systemroot, regfile) - try: - path = self.image.g.case_sensitive_path(path) - except RuntimeError as error: - raise FatalError("Unable to retrieve registry file: %s. Reason: %s" - % (regfile, str(error))) - return path - - def _enable_os_monitor(self): - """Add a script in the registry that will send a random string to the - first serial port when the windows image finishes booting. - """ - - token = "".join(random.choice(string.ascii_letters) for x in range(16)) - - path = self._registry_file_path('SOFTWARE') - softwarefd, software = tempfile.mkstemp() - try: - os.close(softwarefd) - self.image.g.download(path, software) - - h = hivex.Hivex(software, write=True) - - # Enable automatic logon. - # This is needed because we need to execute a script that we add in - # the RunOnce registry entry and those programs only get executed - # when a user logs on. There is a RunServicesOnce registry entry - # whose keys get executed in the background when the logon dialog - # box first appears, but they seem to only work with services and - # not arbitrary command line expressions :-( - # - # Instructions on how to turn on automatic logon in Windows can be - # found here: http://support.microsoft.com/kb/324737 - # - # Warning: Registry change will not work if the “Logon Banner†is - # defined on the server either by a Group Policy object (GPO) or by - # a local policy. - - winlogon = h.root() - for child in ('Microsoft', 'Windows NT', 'CurrentVersion', - 'Winlogon'): - winlogon = h.node_get_child(winlogon, child) - - h.node_set_value( - winlogon, - {'key': 'DefaultUserName', 't': 1, - 'value': "Administrator".encode('utf-16le')}) - h.node_set_value( - winlogon, - {'key': 'DefaultPassword', 't': 1, - 'value': self.sysprep_params['password'].encode('utf-16le')}) - h.node_set_value( - winlogon, - {'key': 'AutoAdminLogon', 't': 1, - 'value': "1".encode('utf-16le')}) - - key = h.root() - for child in ('Microsoft', 'Windows', 'CurrentVersion'): - key = h.node_get_child(key, child) - - runonce = h.node_get_child(key, "RunOnce") - if runonce is None: - runonce = h.node_add_child(key, "RunOnce") - - value = ( - r'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ' - r'-ExecutionPolicy RemoteSigned ' - r'"&{$port=new-Object System.IO.Ports.SerialPort COM1,9600,' - r'None,8,one;$port.open();$port.WriteLine(\"' + token + r'\");' - r'$port.Close()}"').encode('utf-16le') - - h.node_set_value(runonce, - {'key': "BootMonitor", 't': 1, 'value': value}) - - value = ( - r'REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion' - r'\policies\system /v LocalAccountTokenFilterPolicy' - r' /t REG_DWORD /d 1 /f').encode('utf-16le') - - h.node_set_value(runonce, - {'key': "UpdateRegistry", 't': 1, 'value': value}) - - h.commit(None) - - self.image.g.upload(software, path) - finally: - os.unlink(software) - - return token - - def _update_firewalls(self, domain, public, standard): - """Enables or disables the firewall for the Domain, the Public and the - Standard profile. Returns a triplete with the old values. - - 1 will enable a firewall and 0 will disable it - """ - - if domain not in (0, 1): - raise ValueError("Valid values for domain parameter are 0 and 1") - - if public not in (0, 1): - raise ValueError("Valid values for public parameter are 0 and 1") - - if standard not in (0, 1): - raise ValueError("Valid values for standard parameter are 0 and 1") - - path = self._registry_file_path("SYSTEM") - systemfd, system = tempfile.mkstemp() - try: - os.close(systemfd) - self.image.g.download(path, system) - - h = hivex.Hivex(system, write=True) - - select = h.node_get_child(h.root(), 'Select') - current_value = h.node_get_value(select, 'Current') - - # expecting a little endian dword - assert h.value_type(current_value)[1] == 4 - current = "%03d" % h.value_dword(current_value) - - firewall_policy = h.root() - for child in ('ControlSet%s' % current, 'services', 'SharedAccess', - 'Parameters', 'FirewallPolicy'): - firewall_policy = h.node_get_child(firewall_policy, child) - - old_values = [] - new_values = [domain, public, standard] - for profile in ('Domain', 'Public', 'Standard'): - node = h.node_get_child(firewall_policy, '%sProfile' % profile) - - old_value = h.node_get_value(node, 'EnableFirewall') - - # expecting a little endian dword - assert h.value_type(old_value)[1] == 4 - old_values.append(h.value_dword(old_value)) - - h.node_set_value( - node, {'key': 'EnableFirewall', 't': 4L, - 'value': struct.pack("<I", new_values.pop(0))}) - - h.commit(None) - self.image.g.upload(system, path) - - finally: - os.unlink(system) - - return old_values - - def _update_uac_remote_setting(self, value): - """Updates the registry key value: - [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies - \System]"LocalAccountTokenFilterPolicy" - - value = 1 will disable the UAC remote restrictions - value = 0 will enable the UAC remote restrictions - - For more info see here: http://support.microsoft.com/kb/951016 - - Returns: - True if the key is changed - False if the key is unchanged - """ - - if value not in (0, 1): - raise ValueError("Valid values for value parameter are 0 and 1") - - path = self._registry_file_path('SOFTWARE') - softwarefd, software = tempfile.mkstemp() - try: - os.close(softwarefd) - self.image.g.download(path, software) - - h = hivex.Hivex(software, write=True) - - key = h.root() - for child in ('Microsoft', 'Windows', 'CurrentVersion', 'Policies', - 'System'): - key = h.node_get_child(key, child) - - policy = None - for val in h.node_values(key): - if h.value_key(val) == "LocalAccountTokenFilterPolicy": - policy = val - - if policy is not None: - dword = h.value_dword(policy) - if dword == value: - return False - elif value == 0: - return False - - new_value = {'key': "LocalAccountTokenFilterPolicy", 't': 4L, - 'value': struct.pack("<I", value)} - - h.node_set_value(key, new_value) - h.commit(None) - - self.image.g.upload(software, path) - - finally: - os.unlink(software) - - return True - - def _do_collect_metadata(self): - """Collect metadata about the OS""" - super(Windows, self)._do_collect_metadata() - self.meta["USERS"] = " ".join(self._get_users()) - - def _get_users(self): - """Returns a list of users found in the images""" - samfd, sam = tempfile.mkstemp() - try: - os.close(samfd) - self.image.g.download(self._registry_file_path('SAM'), sam) - - h = hivex.Hivex(sam) - - # Navigate to /SAM/Domains/Account/Users - users_node = h.root() - for child in ('SAM', 'Domains', 'Account', 'Users'): - users_node = h.node_get_child(users_node, child) - - # Navigate to /SAM/Domains/Account/Users/Names - names_node = h.node_get_child(users_node, 'Names') - - # HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\%RID% - # HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\Names\%Username% - # - # The RID (relative identifier) of each user is stored as the type! - # (not the value) of the default key of the node under Names whose - # name is the user's username. Under the RID node, there in a F - # value that contains information about this user account. - # - # See sam.h of the chntpw project on how to translate the F value - # of an account in the registry. Bytes 56 & 57 are the account type - # and status flags. The first bit is the 'account disabled' bit - disabled = lambda f: int(f[56].encode('hex'), 16) & 0x01 - - users = [] - for user_node in h.node_children(names_node): - username = h.node_name(user_node) - rid = h.value_type(h.node_get_value(user_node, ""))[0] - # if RID is 500 (=0x1f4), the corresponding node name under - # Users is '000001F4' - key = ("%8.x" % rid).replace(' ', '0').upper() - rid_node = h.node_get_child(users_node, key) - f_value = h.value_value(h.node_get_value(rid_node, 'F'))[1] - - if disabled(f_value): - self.out.warn("Found disabled `%s' account!" % username) - continue - - users.append(username) - - finally: - os.unlink(sam) - - # Filter out the guest account - return users - - def _check_connectivity(self): - """Check if winexe works on the Windows VM""" - - retries = self.sysprep_params['connection_retries'] - # If the connection_retries parameter is set to 0 disable the - # connectivity check - if retries == 0: - return True - - passwd = self.sysprep_params['password'] - winexe = WinEXE('Administrator', passwd, 'localhost') - winexe.uninstall().debug(9) - - for i in range(retries): - (stdout, stderr, rc) = winexe.run('cmd /C') - if rc == 0: - return True - log = tempfile.NamedTemporaryFile(delete=False) - try: - log.file.write(stdout) - finally: - log.close() - self.out.output("failed! See: `%s' for the full output" % log.name) - if i < retries - 1: - self.out.output("retrying ...", False) - - raise FatalError("Connection to the Windows VM failed after %d retries" - % retries) - - def _guest_exec(self, command, fatal=True): - """Execute a command on a windows VM""" - - passwd = self.sysprep_params['password'] - - winexe = WinEXE('Administrator', passwd, 'localhost') - winexe.runas('Administrator', passwd).uninstall() - - try: - (stdout, stderr, rc) = winexe.run(command) - except WinexeTimeout: - FatalError("Command: `%s' timeout out." % command) - - if rc != 0 and fatal: - reason = stderr if len(stderr) else stdout - self.out.output("Command: `%s' failed (rc=%d). Reason: %s" % - (command, rc, reason)) - raise FatalError("Command: `%s' failed (rc=%d). Reason: %s" % - (command, rc, reason)) - - return (stdout, stderr, rc) - - -class _VM(object): - """Windows Virtual Machine""" - def __init__(self, disk, serial, params): - """Create _VM instance - - disk: VM's hard disk - serial: File to save the output of the serial port - """ - - self.disk = disk - self.serial = serial - self.params = params - - def random_mac(): - """creates a random mac address""" - mac = [0x00, 0x16, 0x3e, - random.randint(0x00, 0x7f), - random.randint(0x00, 0xff), - random.randint(0x00, 0xff)] - - return ':'.join(['%02x' % x for x in mac]) - - # Use ganeti's VNC port range for a random vnc port - self.display = random.randint(11000, 14999) - 5900 - - kvm, needed_args = get_kvm_binary() - - if kvm is None: - FatalError("Can't find the kvm binary") - - args = [kvm] - args.extend(needed_args) - - args.extend([ - '-smp', str(self.params['smp']), '-m', str(self.params['mem']), - '-drive', 'file=%s,format=raw,cache=unsafe,if=virtio' % self.disk, - '-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0', - '-device', 'virtio-net-pci,mac=%s,netdev=netdev0' % random_mac(), - '-vnc', ':%d' % self.display, '-serial', 'file:%s' % self.serial, - '-monitor', 'stdio']) - - self.process = subprocess.Popen(args, stdin=subprocess.PIPE, - stdout=subprocess.PIPE) - - def isalive(self): - """Check if the VM is still alive""" - return self.process.poll() is None - - def destroy(self): - """Destroy the VM""" - - if not self.isalive(): - return - - def handler(signum, frame): - self.process.terminate() - time.sleep(1) - if self.isalive(): - self.process.kill() - self.process.wait() - raise FatalError("VM destroy timed-out") - - signal.signal(signal.SIGALRM, handler) - - signal.alarm(self.params['shutdown_timeout']) - self.process.communicate(input="system_powerdown\n") - signal.alarm(0) - - def wait(self, timeout=0): - """Wait for the VM to terminate""" - - def handler(signum, frame): - self.destroy() - raise FatalError("VM wait timed-out.") - - signal.signal(signal.SIGALRM, handler) - - signal.alarm(timeout) - stdout, stderr = self.process.communicate() - signal.alarm(0) - - return (stdout, stderr, self.process.poll()) - -# vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/os_type/windows/__init__.py b/image_creator/os_type/windows/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f1ab16919b7cc49f142ba75ce6a674add58d84f3 --- /dev/null +++ b/image_creator/os_type/windows/__init__.py @@ -0,0 +1,1033 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011-2014 GRNET S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +"""This package hosts OS-specific code common for the various Microsoft +Windows OSs.""" + +from image_creator.os_type import OSBase, sysprep, add_sysprep_param +from image_creator.util import FatalError +from image_creator.os_type.windows.vm import VM, RANDOM_TOKEN as TOKEN +from image_creator.os_type.windows.registry import Registry +from image_creator.os_type.windows.winexe import WinEXE +from image_creator.os_type.windows import powershell + +import tempfile +import re +import os +import uuid +import time +from collections import namedtuple + +# For more info see: http://technet.microsoft.com/en-us/library/jj612867.aspx +KMS_CLIENT_SETUP_KEYS = { + "Windows 8.1 Professional": "GCRJD-8NW9H-F2CDX-CCM8D-9D6T9", + "Windows 8.1 Professional N": "HMCNV-VVBFX-7HMBH-CTY9B-B4FXY", + "Windows 8.1 Enterprise": "MHF9N-XY6XB-WVXMC-BTDCT-MKKG7", + "Windows 8.1 Enterprise N": "TT4HM-HN7YT-62K67-RGRQJ-JFFXW", + "Windows Server 2012 R2 Server Standard": "D2N9P-3P6X9-2R39C-7RTCD-MDVJX", + "Windows Server 2012 R2 Datacenter": "W3GGN-FT8W3-Y4M27-J84CP-Q3VJ9", + "Windows Server 2012 R2 Essentials": "KNC87-3J2TX-XB4WP-VCPJV-M4FWM", + "Windows 8 Professional": "NG4HW-VH26C-733KW-K6F98-J8CK4", + "Windows 8 Professional N": "XCVCF-2NXM9-723PB-MHCB7-2RYQQ", + "Windows 8 Enterprise": "32JNW-9KQ84-P47T8-D8GGY-CWCK7", + "Windows 8 Enterprise N": "JMNMF-RHW7P-DMY6X-RF3DR-X2BQT", + "Windows Server 2012 Core": "BN3D2-R7TKB-3YPBD-8DRP2-27GG4", + "Windows Server 2012 Core N": "8N2M2-HWPGY-7PGT9-HGDD8-GVGGY", + "Windows Server 2012 Core Single Language": + "2WN2H-YGCQR-KFX6K-CD6TF-84YXQ", + "Windows Server 2012 Core Country Specific": + "4K36P-JN4VD-GDC6V-KDT89-DYFKP", + "Windows Server 2012 Server Standard": "XC9B7-NBPP2-83J2H-RHMBY-92BT4", + "Windows Server 2012 Standard Core": "XC9B7-NBPP2-83J2H-RHMBY-92BT4", + "Windows Server 2012 MultiPoint Standard": "HM7DN-YVMH3-46JC3-XYTG7-CYQJJ", + "Windows Server 2012 MultiPoint Premium": "XNH6W-2V9GX-RGJ4K-Y8X6F-QGJ2G", + "Windows Server 2012 Datacenter": "48HP8-DN98B-MYWDG-T2DCC-8W83P", + "Windows Server 2012 Datacenter Core": "48HP8-DN98B-MYWDG-T2DCC-8W83P", + "Windows 7 Professional": "FJ82H-XT6CR-J8D7P-XQJJ2-GPDD4", + "Windows 7 Professional N": "MRPKT-YTG23-K7D7T-X2JMM-QY7MG", + "Windows 7 Professional E": "W82YF-2Q76Y-63HXB-FGJG9-GF7QX", + "Windows 7 Enterprise": "33PXH-7Y6KF-2VJC9-XBBR8-HVTHH", + "Windows 7 Enterprise N": "YDRBP-3D83W-TY26F-D46B2-XCKRJ", + "Windows 7 Enterprise E": "C29WB-22CC8-VJ326-GHFJW-H9DH4", + "Windows Server 2008 R2 Web": "6TPJF-RBVHG-WBW2R-86QPH-6RTM4", + "Windows Server 2008 R2 HPC edition": "TT8MH-CG224-D3D7Q-498W2-9QCTX", + "Windows Server 2008 R2 Standard": "YC6KT-GKW9T-YTKYR-T4X34-R7VHC", + "Windows Server 2008 R2 Enterprise": "489J6-VHDMP-X63PK-3K798-CPX3Y", + "Windows Server 2008 R2 Datacenter": "74YFP-3QFB3-KQT8W-PMXWJ-7M648", + "Windows Server 2008 R2 for Itanium-based Systems": + "GT63C-RJFQ3-4GMB6-BRFB9-CB83V", + "Windows Vista Business": "YFKBB-PQJJV-G996G-VWGXY-2V3X8", + "Windows Vista Business N": "HMBQG-8H2RH-C77VX-27R82-VMQBT", + "Windows Vista Enterprise": "VKK3X-68KWM-X2YGT-QR4M6-4BWMV", + "Windows Vista Enterprise N": "VTC42-BM838-43QHV-84HX6-XJXKV", + "Windows Web Server 2008": "WYR28-R7TFJ-3X2YQ-YCY4H-M249D", + "Windows Server 2008 Standard": "TM24T-X9RMF-VWXK6-X8JC9-BFGM2", + "Windows Server 2008 Standard without Hyper-V": + "W7VD6-7JFBR-RX26B-YKQ3Y-6FFFJ", + "Windows Server 2008 Enterprise": "YQGMW-MPWTJ-34KDK-48M3W-X4Q6V", + "Windows Server 2008 Enterprise without Hyper-V": + "39BXF-X8Q23-P2WWT-38T2F-G3FPG", + "Windows Server 2008 HPC": "RCTX3-KWVHP-BR6TB-RB6DM-6X7HP", + "Windows Server 2008 Datacenter": "7M67G-PC374-GR742-YH8V4-TCBY3", + "Windows Server 2008 Datacenter without Hyper-V": + "22XQ2-VRXRG-P8D42-K34TD-G3QQC", + "Windows Server 2008 for Itanium-Based Systems": + "4DWFP-JF3DJ-B7DTH-78FJB-PDRHK"} + +# The PCI Device ID for VirtIO devices. 1af4 is the Vendor ID for Red Hat, Inc +VIRTIO_DEVICE_ID = re.compile(r'pci\\ven_1af4&dev_100[0-5]') +VIRTIO = ( # id Name + "netkvm", # 1000 Virtio network device + "viostor", # 1001 Virtio block device + "balloon", # 1002 Virtio memory balloon + "vioser", # 1003 Virtio console + "vioscsi", # 1004 Virtio SCSI + "viorng") # 1005 Virtio RNG + +# The Administrator's Relative ID +ADMIN_RID = 500 + + +def parse_inf(inf): + """Parse the content of a Windows INF file and fetch all information found + in the Version section, the target OS as well as the VirtIO drivers it + defines. + + For more info check here: + http://msdn.microsoft.com/en-us/library/windows/hardware/ff549520 + """ + + driver = None + target_os = set() + + sections = {} + current = {} + + prev_line = "" + for line in iter(inf): + # Strip comments + line = prev_line + line.split(';')[0].strip() + prev_line = "" + + if not len(line): + continue + + # Does the directive span more lines? + if line[-1] == "\\": + prev_line = line + continue + + # Does the line denote a section? + if line.startswith('[') and line.endswith(']'): + section = line[1:-1].strip().lower() + if section not in sections: + current = {} + sections[section] = current + else: + current = sections[section] + continue + + # We only care about param = value lines + if line.find('=') > 0: + param, value = line.split('=', 1) + current[param.strip()] = value.strip() + + models = [] + if 'manufacturer' in sections: + for value in sections['manufacturer'].values(): + value = value.split(',') + if len(value) == 0: + continue + + # %strkey%=models-section-name [,TargetOSVersion] ... + models.append(value[0].strip().lower()) + for i in range(len(value) - 1): + target_os.add(value[i+1].strip().lower()) + + if len(models): + # [models-section-name] | [models-section-name.TargetOSVersion] + models_section_name = \ + re.compile('^(' + "|".join(models) + ')(\\..+)?$') + for model in [s for s in sections if models_section_name.match(s)]: + for value in sections[model].values(): + value = value.split(',') + if len(value) == 1: + continue + # The second value in a device-description entry is always the + # hardware ID: + # install-section-name[,hw-id][,compatible-id...] + hw_id = value[1].strip().lower() + # If this matches a VirtIO device, then this is a VirtIO driver + id_match = VIRTIO_DEVICE_ID.match(hw_id) + if id_match: + driver = VIRTIO[int(id_match.group(0)[-1])] + + if 'version' in sections and 'strings' in sections: + # Replace all strkey tokens with their actual value + for key, val in sections['version'].items(): + if val.startswith('%') and val.endswith('%'): + strkey = val[1:-1] + if strkey in sections['strings']: + sections['version'][key] = sections['strings'][strkey] + + if len(target_os) == 0: + target_os.add('ntx86') + + version = sections['version'] if 'version' in sections else {} + + return driver, target_os, version + + +def virtio_dir_check(dirname): + """Check if the needed virtio driver files are present in the dirname + directory + """ + if not dirname: + return "" # value not set + + # Check files in a case insensitive manner + files = set(os.listdir(dirname)) + + for inf in [f for f in files if f.lower().endswith('.inf')]: + with open(os.path.join(dirname, inf)) as content: + driver, _, _ = parse_inf(content) + if driver: + return dirname + + raise ValueError("Could not find any VirtIO driver in this directory. " + "Please select another one.") + + +DESCR = { + "boot_timeout": + "Time in seconds to wait for the Windows customization VM to boot.", + "shutdown_timeout": + "Time in seconds to wait for the Windows customization VM to shut down " + "after the initial command is given.", + "connection_retries": + "Number of times to try to connect to the Windows customization VM after " + "it has booted, before giving up.", + "smp": "Number of CPUs to use for the Windows customization VM.", + "mem": "Virtual RAM size in MiB for the Windows customization VM.", + "virtio": "Directory hosting the Windows virtio drivers.", + "virtio_timeout": + "Time in seconds to wait for the installation of the VirtIO drivers."} + + +class Windows(OSBase): + """OS class for Windows""" + @add_sysprep_param('mem', "posint", 1024, DESCR['mem']) + @add_sysprep_param('smp', "posint", 1, DESCR['smp']) + @add_sysprep_param( + 'connection_retries', "posint", 5, DESCR['connection_retries']) + @add_sysprep_param( + 'shutdown_timeout', "posint", 120, DESCR['shutdown_timeout']) + @add_sysprep_param('boot_timeout', "posint", 300, DESCR['boot_timeout']) + @add_sysprep_param('virtio', 'dir', "", DESCR['virtio'], + check=virtio_dir_check, hidden=True) + @add_sysprep_param( + 'virtio_timeout', 'posint', 900, DESCR['virtio_timeout']) + def __init__(self, image, **kargs): + super(Windows, self).__init__(image, **kargs) + + # The commit with the following message was added in + # libguestfs 1.17.18 and was backported in version 1.16.11: + # + # When a Windows guest doesn't have a HKLM\SYSTEM\MountedDevices node, + # inspection fails. However inspection should not completely fail just + # because we cannot get the drive letter mapping from a guest. + # + # Since Microsoft Sysprep removes the aforementioned key, image + # creation for windows can only be supported if the installed guestfs + # version is 1.17.18 or higher + if self.image.check_guestfs_version(1, 17, 18) < 0 and \ + (self.image.check_guestfs_version(1, 17, 0) >= 0 or + self.image.check_guestfs_version(1, 16, 11) < 0): + raise FatalError( + 'For windows support libguestfs 1.16.11 or above is required') + + device = self.image.g.part_to_dev(self.root) + + self.last_part_num = self.image.g.part_list(device)[-1]['part_num'] + + self.product_name = self.image.g.inspect_get_product_name(self.root) + self.systemroot = self.image.g.inspect_get_windows_systemroot( + self.root) + + self.registry = Registry(self.image) + + with self.mount(readonly=True, silent=True): + self.out.output("Checking media state ...", False) + + # Enumerate the windows users + (self.usernames, + self.active_users, + self.admins) = self.registry.enum_users() + assert ADMIN_RID in self.usernames, "Administrator account missing" + + # If the image is already sysprepped we cannot further customize it + self.sysprepped = self.registry.get_setup_state() > 0 + + self.virtio_state = self.compute_virtio_state() + + arch = self.image.g.inspect_get_arch(self.root) + if arch == 'x86_64': + arch = 'amd64' + elif arch == 'i386': + arch = 'x86' + major = self.image.g.inspect_get_major_version(self.root) + minor = self.image.g.inspect_get_minor_version(self.root) + # This is the OS version as defined in INF files to check if a + # driver is valid for this OS. + self.windows_version = "nt%s.%s.%s" % (arch, major, minor) + self.out.success("done") + + # If the image is sysprepped no driver mappings will be present. + self.systemdrive = None + for drive, root in self.image.g.inspect_get_drive_mappings(self.root): + if root == self.root: + self.systemdrive = drive + + active_admins = [u for u in self.admins if u in self.active_users] + if ADMIN_RID in self.active_users or len(active_admins) == 0: + admin = ADMIN_RID + else: + active_admins.sort() + admin = active_admins[0] + + self.vm = VM( + self.image.device, self.sysprep_params, + namedtuple('User', 'rid name')(admin, self.usernames[admin])) + + @sysprep('Disabling IPv6 privacy extensions', + display="Disable IPv6 privacy extensions") + def _disable_ipv6_privacy_extensions(self): + """Disable IPv6 privacy extensions""" + + self.vm.rexec('netsh interface ipv6 set global ' + 'randomizeidentifiers=disabled store=persistent') + + @sysprep('Disabling Teredo interface', display="Disable Teredo") + def _disable_teredo(self): + """Disable Teredo interface""" + + self.vm.rexec('netsh interface teredo set state disabled') + + @sysprep('Disabling ISATAP Adapters', display="Disable ISATAP") + def _disable_isatap(self): + """Disable ISATAP Adapters""" + + self.vm.rexec('netsh interface isa set state disabled') + + @sysprep('Enabling ping responses') + def _enable_pings(self): + """Enable ping responses""" + + self.vm.rexec('netsh firewall set icmpsetting 8') + + @sysprep('Setting the system clock to UTC', display="UTC") + def _utc(self): + """Set the hardware clock to UTC""" + + path = r'HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation' + self.vm.rexec( + r'REG ADD %s /v RealTimeIsUniversal /t REG_DWORD /d 1 /f' % path) + + @sysprep('Clearing the event logs') + def _clear_logs(self): + """Clear all the event logs""" + + self.vm.rexec( + "cmd /q /c for /f \"tokens=*\" %l in ('wevtutil el') do " + "wevtutil cl \"%l\"") + + @sysprep('Executing Sysprep on the image (may take more that 10 min)', + display="Microsoft Sysprep") + def _microsoft_sysprep(self): + """Run the Microsoft System Preparation Tool. This will remove + system-specific data and will make the image ready to be deployed. + After this no other task may run. + """ + + self.vm.rexec(r'C:\Windows\system32\sysprep\sysprep ' + r'/quiet /generalize /oobe /shutdown', uninstall=True) + self.sysprepped = True + + @sysprep('Converting the image into a KMS client', enabled=False, + display="KMS client setup") + def _kms_client_setup(self): + """Install the appropriate KMS client setup key to the image to convert + it to a KMS client. Computers that are running volume licensing + editions of Windows 8, Windows Server 2012, Windows 7, Windows Server + 2008 R2, Windows Vista, and Windows Server 2008 are by default KMS + clients with no additional configuration needed. + """ + try: + setup_key = KMS_CLIENT_SETUP_KEYS[self.product_name] + except KeyError: + self.out.warn( + "Don't know the KMS client setup key for product: `%s'" % + self.product_name) + return + + self.vm.rexec( + r"cscript \Windows\system32\slmgr.vbs /ipk %s" % setup_key) + + @sysprep('Shrinking file system on the last partition') + def _shrink(self): + """Shrink the last file system. Please make sure the file system is + defragged. + """ + + # Query for the maximum number of reclaimable bytes + cmd = ( + r'cmd /Q /V:ON /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' + + r'ECHO SELECT DISK 0 > %SCRIPT% & ' + + 'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num + + r'ECHO SHRINK QUERYMAX >> %SCRIPT% & ' + + r'ECHO EXIT >> %SCRIPT% & ' + + r'DISKPART /S %SCRIPT% & ' + + r'IF NOT !ERRORLEVEL! EQU 0 EXIT /B 1 & ' + + r'DEL /Q %SCRIPT%"') + + stdout, stderr, rc = self.vm.rexec(cmd) + + querymax = None + for line in stdout.splitlines(): + # diskpart will return something like this: + # + # The maximum number of reclaimable bytes is: xxxx MB + # + if line.find('reclaimable') >= 0: + answer = line.split(':')[1].strip() + m = re.search(r'(\d+)\s*([KMGT]?)B', answer, re.IGNORECASE) + if m: + querymax = m.group(1) + unit = m.group(2) + else: + raise FatalError("Unexpected output for `shrink querymax' " + "command: %s" % line) + + if querymax is None: + raise FatalError("Error in shrinking! Couldn't find the max " + "number of reclaimable bytes!\n" + "Command output: %s" % stdout) + + querymax = int(querymax) + if querymax == 0: + self.out.warn("Unable to reclaim any space. The media is full.") + return + + # Not sure if we should use 1000 or 1024 here + if len(unit) == 0: # Bytes + querymax /= 1000 * 1000 + elif unit == 'K': + querymax /= 1000 + elif unit == 'G': + querymax *= 1000 + elif unit == 'T': + querymax *= 1000*1000 + + # From ntfsresize: + # Practically the smallest shrunken size generally is at around + # "used space" + (20-200 MB). Please also take into account that + # Windows might need about 50-100 MB free space left to boot safely. + # I'll give 100MB extra space just to be sure + querymax -= 100 + + if querymax < 0: + self.out.warn("Not enough available space to shrink the image!") + return + + self.out.output("\tReclaiming %dMB ..." % querymax) + + cmd = ( + r'cmd /Q /V:ON /C "SET SCRIPT=%TEMP%\QUERYMAX_%RANDOM%.TXT & ' + + r'ECHO SELECT DISK 0 > %SCRIPT% & ' + + 'ECHO SELECT PARTITION %d >> %%SCRIPT%% & ' % self.last_part_num + + 'ECHO SHRINK DESIRED=%d >> %%SCRIPT%% & ' % querymax + + r'ECHO EXIT >> %SCRIPT% & ' + + r'DISKPART /S %SCRIPT% & ' + + r'IF NOT !ERRORLEVEL! EQU 0 EXIT /B 1 & ' + + r'DEL /Q %SCRIPT%"') + + stdout, stderr, rc = self.vm.rexec(cmd, fatal=False) + + if rc != 0: + raise FatalError( + "Shrinking failed. Please make sure the media is defragged.") + + for line in stdout.splitlines(): + if line.find('shrunk') >= 0: + self.out.output(" %s" % line) + + self.shrinked = True + + def do_sysprep(self): + """Prepare system for image creation.""" + + self.out.output('Preparing system for image creation:') + + # Check if winexe is installed + if not WinEXE.is_installed(): + raise FatalError( + "Winexe not found! In order to be able to customize a Windows " + "image you need to have Winexe installed.") + + if self.sysprepped: + raise FatalError( + "Microsoft's System Preparation Tool has ran on the media. " + "Further image customization is not possible.") + + if len(self.virtio_state['viostor']) == 0: + raise FatalError( + "The media has no VirtIO SCSI controller driver installed. " + "Further image customization is not possible.") + + if len(self.virtio_state['netkvm']) == 0: + raise FatalError( + "The media has no VirtIO Ethernet Adapter driver installed. " + "Further image customization is not possible.") + + timeout = self.sysprep_params['boot_timeout'].value + shutdown_timeout = self.sysprep_params['shutdown_timeout'].value + + self.out.output("Preparing media for boot ...", False) + + with self.mount(readonly=False, silent=True): + + if not self.registry.reset_account(self.vm.admin.rid): + self._add_cleanup('sysprep', self.registry.reset_account, + self.vm.admin.rid, False) + + if self.registry.update_uac(0): + self._add_cleanup('sysprep', self.registry.update_uac, 1) + + if self.registry.update_uac_remote_setting(1): + self._add_cleanup('sysprep', + self.registry.update_uac_remote_setting, 0) + + # disable the firewalls + self._add_cleanup('sysprep', self.registry.update_firewalls, + *self.registry.update_firewalls(0, 0, 0)) + + v_val = self.registry.reset_passwd(self.vm.admin.rid) + + self._add_boot_scripts() + + # Delete the pagefile. It will be recreated when the system boots + try: + pagefile = "%s/pagefile.sys" % self.systemroot + self.image.g.rm_rf(self.image.g.case_sensitive_path(pagefile)) + except RuntimeError: + pass + + self.out.success('done') + + self.image.disable_guestfs() + booted = False + try: + self.out.output("Starting windows VM ...", False) + self.vm.start() + try: + self.out.success("started (console on VNC display: %d)" % + self.vm.display) + + self.out.output("Waiting for OS to boot ...", False) + if not self.vm.wait_on_serial(timeout): + raise FatalError("Windows VM booting timed out!") + self.out.success('done') + booted = True + + # Since the password is reset when logging in, sleep a little + # bit before checking the connectivity, to avoid race + # conditions + time.sleep(5) + + self.out.output("Checking connectivity to the VM ...", False) + self._check_connectivity() + # self.out.success('done') + + # self.out.output("Disabling automatic logon ...", False) + self._disable_autologon() + self.out.success('done') + + self._exec_sysprep_tasks() + + self.out.output("Waiting for windows to shut down ...", False) + (_, stderr, rc) = self.vm.wait(shutdown_timeout) + if rc != 0 or "terminating on signal" in stderr: + raise FatalError("Windows VM died unexpectedly!\n\n" + "(rc=%d)\n%s" % (rc, stderr)) + self.out.success("done") + finally: + # if the VM is not already dead here, a Fatal Error will have + # already been raised. There is no reason to make the command + # fatal. + self.vm.stop(shutdown_timeout if booted else 1, fatal=False) + finally: + self.image.enable_guestfs() + + self.out.output("Reverting media boot preparations ...", False) + with self.mount(readonly=False, silent=True, fatal=False): + + if not self.ismounted: + self.out.warn("The boot changes cannot be reverted. " + "The snapshot may be in a corrupted state.") + else: + if not self.sysprepped: + # Reset the old password + self.registry.reset_passwd(self.vm.admin.rid, v_val) + + self._cleanup('sysprep') + self.out.success("done") + + self.image.shrink(silent=True) + + def _exec_sysprep_tasks(self): + """This function hosts the actual code for executing the enabled + sysprep tasks. At the end of this method the VM is shut down if needed. + """ + tasks = self.list_syspreps() + enabled = [t for t in tasks if self.sysprep_enabled(t)] + size = len(enabled) + + # Make sure shrink runs in the end, before ms sysprep + enabled = [t for t in enabled if self.sysprep_info(t).name != 'shrink'] + if len(enabled) != size: + enabled.append(self._shrink) + + # Make sure the ms sysprep is the last task to run if it is enabled + enabled = [t for t in enabled + if self.sysprep_info(t).name != 'microsoft-sysprep'] + + if len(enabled) != size: + enabled.append(self._microsoft_sysprep) + + cnt = 0 + for task in enabled: + cnt += 1 + self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False) + task() + del self._sysprep_tasks[task.__name__] + + self.out.output("Sending shut down command ...", False) + if not self.sysprepped: + self._shutdown() + self.out.success("done") + + def _shutdown(self): + """Shuts down the windows VM""" + self.vm.rexec(r'shutdown /s /t 5', uninstall=True) + + def _disable_autologon(self): + """Disable automatic logon on the windows image""" + + winlogon = \ + r'"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"' + + self.vm.rexec('REG DELETE %s /v DefaultUserName /f' % winlogon) + self.vm.rexec('REG DELETE %s /v DefaultPassword /f' % winlogon) + self.vm.rexec('REG DELETE %s /v AutoAdminLogon /f' % winlogon) + + def _add_boot_scripts(self): + """Add various scripts in the registry that will be executed during the + next boot. + """ + + commands = {} + + # Disable hibernation. This is not needed for a VM + commands['hibernate'] = r'powercfg.exe /hibernate off' + # This script will send a random string to the first serial port. This + # can be used to determine when the OS has booted. + commands['BootMonitor'] = "cmd /q /a /c echo " + TOKEN + " > COM1" + + # This will update the password of the admin user to self.vm.password + commands["UpdatePassword"] = "net user %s %s" % \ + (self.vm.admin.name, self.vm.password) + + # This is previously done with hivex when we executed + # self.registry.update_uac_remote_setting(1). + # Although the command above works on all windows version and the + # UAC remote restrictions are disabled, on Windows 2012 the registry + # value seems corrupted after we run the command. Maybe this has to do + # with a bug or a limitation in hivex. As a workaround we re-update the + # value from within Windows. + commands["UpdateRegistry"] = \ + (r'REG ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion' + r'\policies\system /v LocalAccountTokenFilterPolicy' + r' /t REG_DWORD /d 1 /f') + + self.registry.runonce(commands) + + # Enable automatic logon. + # This is needed in order for the scripts we added in the RunOnce + # registry entry to get executed, since the RunOnce commands only get + # executed when a user logs on. There is a RunServicesOnce registry + # entry whose keys get executed in the background when the logon dialog + # box first appears, but they seem to only work with services and not + # arbitrary command line expressions :-( + # + # Instructions on how to turn on automatic logon in Windows can be + # found here: http://support.microsoft.com/kb/324737 + # + # Warning: Registry change will not work if the “Logon Banner†is + # defined on the server either by a Group Policy object (GPO) or by a + # local policy. + + self.registry.enable_autologon(self.vm.admin.name) + + def _do_collect_metadata(self): + """Collect metadata about the OS""" + super(Windows, self)._do_collect_metadata() + + # We only care for active users + self.meta["USERS"] = \ + " ".join([self.usernames[a] for a in self.active_users]) + + def _check_connectivity(self): + """Check if winexe works on the Windows VM""" + + retries = self.sysprep_params['connection_retries'].value + timeout = [5] + for i in xrange(1, retries - 1): + timeout.insert(0, timeout[0] * 2) + + # If the connection_retries parameter is set to 0 disable the + # connectivity check + if retries == 0: + return True + + for i in xrange(retries): + (stdout, stderr, rc) = self.vm.rexec('cmd /C', fatal=False, + debug=True) + if rc == 0: + return True + + log = tempfile.NamedTemporaryFile(delete=False) + try: + log.file.write("STDOUT:\n%s\n" % stdout) + log.file.write("STDERR:\n%s\n" % stderr) + finally: + log.close() + self.out.output("failed! See: `%s' for the full output" % log.name) + if i < retries - 1: + wait = timeout.pop() + self.out.output("retrying in %d seconds ..." % wait, False) + time.sleep(wait) + + raise FatalError("Connection to the Windows VM failed after %d retries" + % retries) + + def compute_virtio_state(self, directory=None): + """Returns information about the VirtIO drivers found either in a + directory or the media itself if the directory is None. + """ + state = {} + for driver in VIRTIO: + state[driver] = {} + + def oem_files(): + """Parse oem*.inf files under the %SystemRoot%/Inf directory""" + path = self.image.g.case_sensitive_path("%s/inf" % self.systemroot) + oem = re.compile(r'^oem\d+\.inf', flags=re.IGNORECASE) + for name in [f['name'] for f in self.image.g.readdir(path)]: + if not oem.match(name): + continue + yield name, \ + self.image.g.cat("%s/%s" % (path, name)).splitlines() + + def local_files(): + """Parse *.inf files under a local directory""" + assert os.path.isdir(directory) + inf = re.compile(r'^.+\.inf', flags=re.IGNORECASE) + for name in os.listdir(directory): + fullpath = os.path.join(directory, name) + if inf.match(name) and os.path.isfile(fullpath): + with open(fullpath, 'r') as content: + yield name, content + + for name, txt in oem_files() if directory is None else local_files(): + driver, target, content = parse_inf(txt) + + if driver: + content['TargetOSVersions'] = target + state[driver][name] = content + + return state + + def _fetch_virtio_drivers(self, dirname): + """Examines a directory for VirtIO drivers and returns only the drivers + that are suitable for this media. + """ + collection = self.compute_virtio_state(dirname) + + files = set([f.lower() for f in os.listdir(dirname) + if os.path.isfile(dirname + os.sep + f)]) + + num = 0 + for drv_type, drvs in collection.items(): + for inf, content in drvs.items(): + valid = True + found_match = False + # Check if the driver is suitable for the input media + for target in content['TargetOSVersions']: + if len(target) > len(self.windows_version): + match = target.startswith(self.windows_version) + else: + match = self.windows_version.startswith(target) + if match: + found_match = True + + if not found_match: # Wrong Target + self.out.warn( + 'Ignoring %s. Driver not targeted for this OS.' % inf) + valid = False + elif 'CatalogFile' not in content: + self.out.warn( + 'Ignoring %s. CatalogFile entry missing.' % inf) + valid = False + elif content['CatalogFile'].lower() not in files: + self.out.warn('Ignoring %s. Catalog File not found.' % inf) + valid = False + + if not valid: + del collection[drv_type][inf] + continue + + num += 1 + if len(drvs) == 0: + del collection[drv_type] + + self.out.output('Found %d valid driver%s' % + (num, "s" if num != 1 else "")) + return collection + + def install_virtio_drivers(self, upgrade=True): + """Install new VirtIO drivers in the input media. If upgrade is True, + then the old drivers found in the media will be removed. + """ + + dirname = self.sysprep_params['virtio'].value + if not dirname: + raise FatalError('No directory hosting the VirtIO drivers defined') + + self.out.output('Installing VirtIO drivers:') + + valid_drvs = self._fetch_virtio_drivers(dirname) + if not len(valid_drvs): + self.out.warn('No suitable driver found to install!') + return + + try: + self._upload_virtio_drivers(dirname, valid_drvs, upgrade) + self._boot_virtio_vm() + finally: + with self.mount(readonly=False, silent=True, fatal=False): + if not self.ismounted: + self.out.warn("The boot changes cannot be reverted. " + "The image may be in a corrupted state.") + else: + self._cleanup('virtio') + + self.out.output("VirtIO drivers were successfully installed") + self.out.output() + + def _upload_virtio_drivers(self, dirname, drvs, delete_old=True): + """Upload the VirtIO drivers and installation scripts to the media. + """ + with self.mount(readonly=False, silent=True): + # Reset Password + self._add_cleanup('virtio', self.registry.reset_passwd, + self.vm.admin.rid, + self.registry.reset_passwd(self.vm.admin.rid)) + + # Enable admin account (if needed) + self._add_cleanup('virtio', self.registry.reset_account, + self.vm.admin.rid, + self.registry.reset_account(self.vm.admin.rid)) + + if self.registry.update_uac(0): + self._add_cleanup('virtio', self.registry.update_uac, 1) + + # We disable this with powershell scripts + self.registry.enable_autologon(self.vm.admin.name) + + # Disable first logon animation (if needed) + self._add_cleanup('virtio', + self.registry.reset_first_logon_animation, + self.registry.reset_first_logon_animation(False)) + + tmp = uuid.uuid4().hex + self.image.g.mkdir_p("%s/%s" % (self.systemroot, tmp)) + + # This is a hack. We create a function here and pass it to + # _add_cleanup because self.image.g may change and the _add_cleanup + # will cache it which is wrong. For older versions of the guestfs + # library we recreate the g handler in enable_guestfs() and the + # program will crash if cleanup retains an older value for the + # guestfs handler. + def remove_tmp(): + self.image.g.rm_rf("%s/%s" % (self.systemroot, tmp)) + + self._add_cleanup('virtio', remove_tmp) + + for fname in os.listdir(dirname): + full_path = os.path.join(dirname, fname) + if os.path.isfile(full_path): + self.image.g.upload( + full_path, "%s/%s/%s" % (self.systemroot, tmp, fname)) + + drvs_install = powershell.DRVINST_HEAD + + for dtype in drvs: + drvs_install += "".join( + [powershell.ADD_CERTIFICATE % d['CatalogFile'] + for d in drvs[dtype].values()]) + cmd = powershell.ADD_DRIVER if dtype != 'viostor' \ + else powershell.INSTALL_DRIVER + drvs_install += "".join([cmd % i for i in drvs[dtype]]) + + if delete_old: + # Add code to remove the old drivers + for dtype in drvs: + for oem in self.virtio_state[dtype]: + drvs_install += powershell.REMOVE_DRIVER % oem + + if self.check_version(6, 1) <= 0: + self._install_viostor_driver(dirname) + old = self.registry.update_devices_dirs("%SystemRoot%\\" + tmp) + self._add_cleanup( + 'virtio', self.registry.update_devices_dirs, old, False) + drvs_install += powershell.DISABLE_AUTOLOGON + else: + # In newer windows, in order to reduce the boot process the + # boot drivers are cached. To be able to boot with viostor, we + # need to reboot in safe mode. + drvs_install += powershell.SAFEBOOT + + drvs_install += powershell.DRVINST_TAIL + + target = "%s/%s/InstallDrivers.ps1" % (self.systemroot, tmp) + self.image.g.write(target, drvs_install.replace('\n', '\r\n')) + + # The -windowstyle option was introduced in PowerShell V2. We need + # to have at least Windows NT 6.1 (Windows 7 or Windows 2008R2) to + # make this work. + hidden_support = self.check_version(6, 1) >= 0 + cmd = ( + '%(drive)s:%(root)s\\System32\\WindowsPowerShell\\v1.0\\' + 'powershell.exe -ExecutionPolicy RemoteSigned %(hidden)s ' + '-File %(drive)s:%(root)s\\%(tmp)s\\InstallDrivers.ps1 ' + '%(drive)s:%(root)s\\%(tmp)s' % + {'root': self.systemroot.replace('/', '\\'), + 'drive': self.systemdrive, + 'tmp': tmp, + 'hidden': '-windowstyle hidden' if hidden_support else ""}) + + # The value name of RunOnce keys can be prefixed with an asterisk + # (*) to force the program to run even in Safe mode. + self.registry.runonce({'*InstallDrivers': cmd}) + + def _boot_virtio_vm(self): + """Boot the media and install the VirtIO drivers""" + + old_windows = self.check_version(6, 1) <= 0 + self.image.disable_guestfs() + try: + timeout = self.sysprep_params['boot_timeout'].value + shutdown_timeout = self.sysprep_params['shutdown_timeout'].value + virtio_timeout = self.sysprep_params['virtio_timeout'].value + self.out.output("Starting Windows VM ...", False) + booted = False + try: + if old_windows: + self.vm.start() + else: + self.vm.interface = 'ide' + self.vm.start(extra_disk=('/dev/null', 'virtio')) + self.vm.interface = 'virtio' + + self.out.success("started (console on VNC display: %d)" % + self.vm.display) + self.out.output("Waiting for Windows to boot ...", False) + if not self.vm.wait_on_serial(timeout): + raise FatalError("Windows VM booting timed out!") + self.out.success('done') + booted = True + self.out.output("Installing new drivers ...", False) + if not self.vm.wait_on_serial(virtio_timeout): + raise FatalError("Windows VirtIO installation timed out!") + self.out.success('done') + self.out.output('Shutting down ...', False) + (_, stderr, rc) = self.vm.wait(shutdown_timeout) + if rc != 0 or "terminating on signal" in stderr: + raise FatalError("Windows VM died unexpectedly!\n\n" + "(rc=%d)\n%s" % (rc, stderr)) + self.out.success('done') + finally: + self.vm.stop(shutdown_timeout if booted else 1, fatal=False) + finally: + self.image.enable_guestfs() + + with self.mount(readonly=True, silent=True): + self.virtio_state = self.compute_virtio_state() + viostor_service_found = self.registry.check_viostor_service() + + if not (len(self.virtio_state['viostor']) and viostor_service_found): + raise FatalError("viostor was not successfully installed") + + if self.check_version(6, 1) > 0: + # Hopefully restart in safe mode. Newer windows will not boot from + # a viostor device unless we initially start them in safe mode + try: + self.out.output('Rebooting Windows VM in safe mode ...', False) + self.vm.start() + (_, stderr, rc) = self.vm.wait(timeout + shutdown_timeout) + if rc != 0 or "terminating on signal" in stderr: + raise FatalError("Windows VM died unexpectedly!\n\n" + "(rc=%d)\n%s" % (rc, stderr)) + self.out.success('done') + finally: + self.vm.stop(1, fatal=True) + + def _install_viostor_driver(self, dirname): + """Quick and dirty installation of the VirtIO SCSI controller driver. + It is done to make the image boot from the VirtIO disk. + + http://rwmj.wordpress.com/2010/04/30/ + tip-install-a-device-driver-in-a-windows-vm/ + """ + + drivers_path = "%s/system32/drivers" % self.systemroot + + try: + drivers_path = self.image.g.case_sensitive_path(drivers_path) + except RuntimeError as err: + raise FatalError("Unable to browse to directory: %s. Reason: %s" % + (drivers_path, str(err))) + viostor = dirname + os.sep + 'viostor.sys' + try: + self.image.g.upload(viostor, drivers_path + '/viostor.sys') + except RuntimeError as err: + raise FatalError("Unable to upload file %s to %s. Reason: %s" % + (viostor, drivers_path, str(err))) + + self.registry.add_viostor() + +# vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/os_type/windows/powershell.py b/image_creator/os_type/windows/powershell.py new file mode 100644 index 0000000000000000000000000000000000000000..81585b965a28ab7d0eb892ddf0225ebaba2d93f9 --- /dev/null +++ b/image_creator/os_type/windows/powershell.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2014 GRNET S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +"""This module hosts Windows PowerShell scripts that need to be injected into +the windows image""" + +# Just a random 16 character long token +from image_creator.os_type.windows.vm import RANDOM_TOKEN + +COM1_WRITE = r""" +$port=new-Object System.IO.Ports.SerialPort COM1,9600,None,8,one +$port.open() +$port.WriteLine('""" + RANDOM_TOKEN + """') +$port.Close() + +""" + +# Installs drivers found in a directory +DRVINST_HEAD = r""" +#requires -version 2 + +Param([string]$dirName=$(throw "You need to provide a directory name")) + +if (!(Test-Path -PathType Container "$dirName")) { + Write-Error -Category InvalidArgument "Invalid Directory: $dirName" + Exit +} + +""" + COM1_WRITE + r""" + +function Cat2Cert +{ + $catFile = Get-Item $args[0] + $cert = (Get-AuthenticodeSignature $catFile.FullName).SignerCertificate + $certFile = "$dirName" + "\" + $catFile.BaseName + ".cer" + [System.IO.File]::WriteAllBytes($certFile, $cert.Export("Cert")) + return $certFile +} + +# This is not needed on VMs +powercfg.exe /hibernate off +""" + +ADD_CERTIFICATE = r""" +CertUtil -addstore TrustedPublisher "$(Cat2Cert "$dirName\%s")" +""" + +ADD_DRIVER = r""" +PnPUtil -a "$dirName\%s" +""" + +INSTALL_DRIVER = r""" +PnPUtil -i -a "$dirName\%s" +""" + +REMOVE_DRIVER = r""" +PnPUtil -f -d %s +""" + +DRVINST_TAIL = COM1_WRITE + """ +shutdown /s /t 0 +""" + +DISABLE_AUTOLOGON = r""" +Remove-ItemProperty -Path ` + 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\' ` + DefaultUserName +Remove-ItemProperty -Path ` + 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\' ` + DefaultPassword +Remove-ItemProperty -Path ` + 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\' ` + AutoAdminLogon +""" + +# Reboots system in safe mode +SAFEBOOT = r""" +bcdedit /set safeboot minimal + +$winlogon = 'HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' +New-ItemProperty ` + -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce ` + -Name *1snf-image-creator-safeboot -PropertyType String ` + -Value 'bcdedit /deletevalue safeboot' + +New-ItemProperty ` + -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce ` + -Name *2snf-image-creator-safeboot -PropertyType String ` + -Value "reg delete `"$winlogon`" /v DefaultUserName /f" +New-ItemProperty ` + -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce ` + -Name *3snf-image-creator-safeboot -PropertyType String ` + -Value "reg delete `"$winlogon`" /v DefaultPassword /f" +New-ItemProperty ` + -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce ` + -Name *4snf-image-creator-safeboot -PropertyType String ` + -Value "reg delete `"$winlogon`" /v AutoAdminLogon /f" + +New-ItemProperty ` + -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce ` + -Name *5snf-image-creator-safeboot -PropertyType String ` + -Value 'shutdown /s /t 5' +""" + +# vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/os_type/windows/registry.py b/image_creator/os_type/windows/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..e8650c5024465828c2ddac1a52432d68c5771ae9 --- /dev/null +++ b/image_creator/os_type/windows/registry.py @@ -0,0 +1,635 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011-2014 GRNET S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +"""This package hosts code for accessing the windows registry""" + +from image_creator.util import FatalError + +import hivex +import tempfile +import os +import struct + +# The Administrators group RID +ADMINS = 0x00000220 + +# http://technet.microsoft.com/en-us/library/hh824815.aspx +WINDOWS_SETUP_STATES = ( + "IMAGE_STATE_COMPLETE", + "IMAGE_STATE_UNDEPLOYABLE", + "IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE", + "IMAGE_STATE_GENERALIZE_RESEAL_TO_AUDIT", + "IMAGE_STATE_SPECIALIZE_RESEAL_TO_OOBE", + "IMAGE_STATE_SPECIALIZE_RESEAL_TO_AUDIT") + +REG_SZ = lambda k, v: {'key': k, 't': 1L, + 'value': (v + '\x00').encode('utf-16le')} +REG_EXPAND_SZ = lambda k, v: {'key': k, 't': 2L, + 'value': (v + '\x00').encode('utf-16le')} +REG_BINARY = lambda k, v: {'key': k, 't': 3L, 'value': v} +REG_DWORD = lambda k, v: {'key': k, 't': 4L, 'value': struct.pack('<I', v)} + + +def safe_add_node(hive, parent, name): + """Add a registry node only if it is not present""" + + node = hive.node_get_child(parent, name) + return hive.node_add_child(parent, name) if node is None else node + + +def traverse(hive, path): + """Traverse a hive following a path""" + + node = hive.root() + + for name in path.split('/'): + + if len(name) == 0: + continue + + node = hive.node_get_child(node, name) + if node is None: + break + + return node + + +class Registry(object): + """Windows Registry manipulation methods""" + + def __init__(self, image): + # Do not copy the guestfs handler. It may be overwritten by the image + # class in the future + self.image = image + self.root = image.root + + def open_hive(self, hive, write=False): + """Returns a context manager for opening a hive file of the image for + reading or writing. + """ + systemroot = self.image.g.inspect_get_windows_systemroot(self.root) + path = "%s/system32/config/%s" % (systemroot, hive) + try: + path = self.image.g.case_sensitive_path(path) + except RuntimeError as err: + raise FatalError("Unable to retrieve file: %s. Reason: %s" % + (hive, str(err))) + + # OpenHive class needs this since 'self' gets overwritten + g = self.image.g + + class OpenHive: + """The OpenHive context manager""" + def __enter__(self): + localfd, self.localpath = tempfile.mkstemp() + try: + os.close(localfd) + g.download(path, self.localpath) + + hive = hivex.Hivex(self.localpath, write=write) + except: + os.unlink(self.localpath) + raise + + return hive + + def __exit__(self, exc_type, exc_value, traceback): + try: + if write: + g.upload(self.localpath, path) + finally: + os.unlink(self.localpath) + + return OpenHive() + + @property + def current_control_set(self): + """Returns the current control set of the registry""" + + if hasattr(self, '_current_control_set'): + return self._current_control_set + + with self.open_hive('SYSTEM') as hive: + select = hive.node_get_child(hive.root(), 'Select') + current_value = hive.node_get_value(select, 'Current') + + # expecting a little endian dword + assert hive.value_type(current_value)[1] == 4 + current = "%03d" % hive.value_dword(current_value) + + self._current_control_set = 'ControlSet%s' % current + + return self._current_control_set + + def get_setup_state(self): + """Returns the stage of Windows Setup the image is in. + The method will return an int with one of the following values: + 0 => IMAGE_STATE_COMPLETE + 1 => IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE + 2 => IMAGE_STATE_GENERALIZE_RESEAL_TO_AUDIT + 3 => IMAGE_STATE_SPECIALIZE_RESEAL_TO_OOBE + 4 => IMAGE_STATE_SPECIALIZE_RESEAL_TO_AUDIT + For more information check here: + http://technet.microsoft.com/en-us/library/hh824815.aspx + """ + + with self.open_hive('SOFTWARE') as hive: + # Navigate to: + # SOFTWARE/Microsoft/Windows/CurrentVersion/Setup/State + state = hive.root() + for child in ('Microsoft', 'Windows', 'CurrentVersion', + 'Setup', 'State'): + state = hive.node_get_child(state, child) + + image_state = hive.node_get_value(state, 'ImageState') + vtype, value = hive.value_value(image_state) + assert vtype == 1L, \ + "ImageState field type (=%d) is not REG_SZ" % vtype + + value = value.decode('utf-16le') + + ret = 0 + for known_state in WINDOWS_SETUP_STATES: + if value == known_state + '\x00': # REG_SZ is null-terminated + return ret + ret += 1 + + raise FatalError("Unknown Windows Setup State: %s" % value) + + def runonce(self, commands): + """Add commands to the RunOnce registry key""" + + with self.open_hive('SOFTWARE', write=True) as hive: + + key = hive.root() + for child in ('Microsoft', 'Windows', 'CurrentVersion'): + key = hive.node_get_child(key, child) + + runonce = hive.node_get_child(key, "RunOnce") + if runonce is None: + runonce = hive.node_add_child(key, "RunOnce") + + for desc, cmd in commands.items(): + hive.node_set_value(runonce, REG_SZ(desc, cmd)) + + hive.commit(None) + + def enable_autologon(self, username, password=""): + """Enable automatic logon for a specific user""" + + with self.open_hive('SOFTWARE', write=True) as hive: + + winlogon = hive.root() + for child in ('Microsoft', 'Windows NT', 'CurrentVersion', + 'Winlogon'): + winlogon = hive.node_get_child(winlogon, child) + + hive.node_set_value(winlogon, REG_SZ('DefaultUserName', username)) + hive.node_set_value(winlogon, REG_SZ('DefaultPassword', password)) + hive.node_set_value(winlogon, REG_SZ('AutoAdminLogon', "1")) + + hive.commit(None) + + def update_firewalls(self, domain, public, standard): + """Enables or disables the firewall for the Domain, the Public and the + Standard profile. Returns a triple with the old values. + + 1 will enable a firewall and 0 will disable it + """ + + if domain not in (0, 1): + raise ValueError("Valid values for domain parameter are 0 and 1") + + if public not in (0, 1): + raise ValueError("Valid values for public parameter are 0 and 1") + + if standard not in (0, 1): + raise ValueError("Valid values for standard parameter are 0 and 1") + + with self.open_hive('SYSTEM', write=True) as hive: + firewall_policy = hive.root() + for child in (self.current_control_set, 'services', 'SharedAccess', + 'Parameters', 'FirewallPolicy'): + firewall_policy = hive.node_get_child(firewall_policy, child) + + old_values = [] + new_values = [domain, public, standard] + for profile in ('Domain', 'Public', 'Standard'): + node = hive.node_get_child(firewall_policy, + '%sProfile' % profile) + + old_value = hive.node_get_value(node, 'EnableFirewall') + + # expecting a little endian dword + assert hive.value_type(old_value)[1] == 4 + old_values.append(hive.value_dword(old_value)) + + hive.node_set_value(node, REG_DWORD('EnableFirewall', + new_values.pop(0))) + hive.commit(None) + + return old_values + + def update_uac_remote_setting(self, value): + r"""Updates the registry key value: + [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies + \System]"LocalAccountTokenFilterPolicy" + + value = 1 will disable the UAC remote restrictions + value = 0 will enable the UAC remote restrictions + + For more info see here: http://support.microsoft.com/kb/951016 + + Returns: + True if the key is changed + False if the key is unchanged + """ + + if value not in (0, 1): + raise ValueError("Valid values for value parameter are 0 and 1") + + with self.open_hive('SOFTWARE', write=True) as hive: + path = 'Microsoft/Windows/CurrentVersion/Policies/System' + system = traverse(hive, path) + + policy = None + for val in hive.node_values(system): + if hive.value_key(val) == "LocalAccountTokenFilterPolicy": + policy = val + + if policy is not None: + if value == hive.value_dword(policy): + return False + elif value == 0: + return False + + hive.node_set_value( + system, REG_DWORD("LocalAccountTokenFilterPolicy", value)) + hive.commit(None) + + return True + + def update_uac(self, value): + """Enable or disable the User Account Control by changing the value of + the EnableLUA registry key + + value = 1 will enable the UAC + value = 0 will disable the UAC + + Returns: + True if the key is changed + False if the key is unchanged + """ + + if value not in (0, 1): + raise ValueError("Valid values for value parameter are 0 and 1") + + with self.open_hive('SOFTWARE', write=True) as hive: + path = 'Microsoft/Windows/CurrentVersion/Policies/System' + system = traverse(hive, path) + + enablelua = None + for val in hive.node_values(system): + if hive.value_key(val) == 'EnableLUA': + enablelua = val + + if enablelua is not None: + if value == hive.value_dword(enablelua): + return False + elif value == 1: + return False + + hive.node_set_value(system, REG_DWORD('EnableLUA', value)) + hive.commit(None) + + return True + + def enum_users(self): + """Returns: + a map of RID->username for all users found on the system + a list of RIDs of active users + a list of RIDs of members of the Administrators group + """ + + users = {} + active = [] + members = [] + + # Under HKLM\SAM\SAM\Domains\Account\Users\%RID% there is an F field + # that contains information about this user account. Bytes 56 & 57 are + # the account type and status flags and the first bit in this flag is + # the 'account disabled' bit: + # + # http://www.beginningtoseethelight.org/ntsecurity/index.htm + # #8603CF0AFBB170DD + # + disabled = lambda f: int(f[56].encode('hex'), 16) & 0x01 + + def collect_group_members(hive, group, rid_node): + """Enumerate group members""" + c_val = hive.value_value(hive.node_get_value(rid_node, 'C'))[1] + + # Check http://pogostick.net/~pnh/ntpasswd/ for more info + offset = struct.unpack('<I', c_val[0x28:0x2c])[0] + 0x34 + #size = struct.unpack('<I', c_val[0x2c:0x30])[0] + count = struct.unpack('<I', c_val[0x30:0x34])[0] + + # Parse the sid array and get all members + while len(members) < count: + sections = struct.unpack('<B', c_val[offset+1:offset+2])[0] + rid_offs = offset + 8 + (sections - 1) * 4 + rid = struct.unpack('<I', c_val[rid_offs:rid_offs+4])[0] + members.append(rid) + offset += sections * 4 + 8 + + def collect_users(hive, username, rid_node): + """Enumerate active users""" + f_val = hive.value_value(hive.node_get_value(rid_node, 'F'))[1] + rid = int(hive.node_name(rid_node), 16) + + if not disabled(f_val): + active.append(rid) + + users[rid] = username + + self._foreach_account( + userlist=[], useraction=collect_users, + grouplist=[ADMINS], groupaction=collect_group_members) + + return (users, active, members) + + def reset_passwd(self, rid, v_field=None): + r"""Reset the password for user 'user'. If v_field is not None, the + value of key \HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\%RID%\V + is replaced with this one, otherwise the LM and NT passwords of the + original V field are cleared out. In any case, the value of the + original V field is returned. + """ + + # This is a hack because python 2.x does not support assigning new + # values to nonlocal variables + parent = {} + + def update_v_field(hive, username, rid_node): + """Updates the user's V field to reset the password""" + assert 'old' not in parent, "Multiple users with same username" + + field = hive.node_get_value(rid_node, 'V') + v_type, v_val = hive.value_value(field) + assert v_type == 3L, "V field type (=%d) isn't REG_BINARY" % v_type + + new = v_field + if new is None: + # In order to reset the passwords, all we need to do is to zero + # out the length fields for the LM password hash and the NT + # password hash in the V field of the user's %RID% node. LM + # password hash length field is at offset 0xa0 and NT password + # hash length is at offset 0xac. See here for more info: + # + # http://www.beginningtoseethelight.org/ntsecurity/index.htm + # #D3BC3F5643A17823 + fmt = '%ds4x8s4x%ds' % (0xa0, len(v_val) - 0xb0) + new = ("\x00" * 4).join(struct.unpack(fmt, v_val)) + + hive.node_set_value(rid_node, REG_BINARY('V', new)) + hive.commit(None) + parent['old'] = v_val + + self._foreach_account(True, userlist=[rid], useraction=update_v_field) + + assert 'old' in parent, "user whith RID: `%s' does not exist" % rid + return parent['old'] + + def reset_account(self, rid, activate=True): + + # This is a hack. I cannot assign a new value to nonlocal variable. + # This is why I'm using a dict + state = {} + + # Convert byte to int + to_int = lambda b: int(b.encode('hex'), 16) + + # Under HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\%RID% there is + # an F field that contains information about this user account. Bytes + # 56 & 57 are the account type and status flags. The first bit is the + # 'account disabled' bit: + # + # http://www.beginningtoseethelight.org/ntsecurity/index.htm + # #8603CF0AFBB170DD + # + isactive = lambda f: (to_int(f[56]) & 0x01) == 0 + + def update_f_field(hive, username, rid_node): + """Updates the user's F field to reset the account""" + field = hive.node_get_value(rid_node, 'F') + f_type, f_val = hive.value_value(field) + assert f_type == 3L, "F field type (=%d) isn't REG_BINARY" % f_type + + state['old'] = isactive(f_val) + if activate is state['old']: + # nothing to do + return + + mask = (lambda b: b & 0xfe) if activate else (lambda b: b | 0x01) + new = struct.pack("56sB23s", f_val[:56], mask(to_int(f_val[56])), + f_val[57:]) + + hive.node_set_value(rid_node, REG_BINARY('F', new)) + hive.commit(None) + + self._foreach_account(True, userlist=[rid], useraction=update_f_field) + + return state['old'] + + def reset_first_logon_animation(self, activate=True): + """Enable or disable the first-logon animation. + + The method return the old value + """ + + with self.open_hive('SOFTWARE', write=True) as hive: + path = 'Microsoft/Windows/CurrentVersion/Policies/System' + system = traverse(hive, path) + try: + val = hive.node_get_value(system, 'EnableFirstLogonAnimation') + old = bool(hive.value_dword(val)) + + # There is no need to reset the value + if old is activate: + return old + except RuntimeError: + # The value is not present at all + if activate is False: + return False + old = False + + hive.node_set_value(system, REG_DWORD('EnableFirstLogonAnimation', + int(activate))) + hive.commit(None) + + return old + + def _foreach_account(self, write=False, **kargs): + """Performs an action on the RID node of a user or a group in the + registry, for every user/group found in the userlist/grouplist. + If userlist/grouplist is empty, it performs the action on all + users/groups. + The write flag determines if the registry is opened for reading or + writing. + """ + + def parse_sam(ridlist, action, path): + """Parse the registry users and groups nodes""" + + accounts = traverse(hive, 'SAM/Domains/' + path) + names = hive.node_get_child(accounts, 'Names') + + # The RID (relative identifier) of each user/group is stored as the + # type!!!! (not the value) of the default key of the node under + # Names whose name is the username/groupname. + + for node in hive.node_children(names): + name = hive.node_name(node) + rid = hive.value_type(hive.node_get_value(node, ""))[0] + + if len(ridlist) != 0 and rid not in ridlist: + continue + + # if RID is 500 (=0x1f4), the corresponding node name is + # '000001F4' + key = ("%8.x" % rid).replace(' ', '0').upper() + rid_node = hive.node_get_child(accounts, key) + + action(hive, name, rid_node) + + userlist = kargs['userlist'] if 'userlist' in kargs else None + useraction = kargs['useraction'] if 'useraction' in kargs else None + + grouplist = kargs['grouplist'] if 'grouplist' in kargs else None + groupaction = kargs['groupaction'] if 'groupaction' in kargs else None + + if userlist is not None: + assert useraction is not None + + if grouplist is not None: + assert groupaction is not None + + with self.open_hive('SAM', write) as hive: + if userlist is not None: + parse_sam(userlist, useraction, 'Account/Users') + + if grouplist is not None: + parse_sam(grouplist, groupaction, 'Builtin/Aliases') + parse_sam(grouplist, groupaction, 'Account/Aliases') + + def add_viostor(self): + """Add the viostor driver to the critical device database and register + the viostor service + """ + + path = r"system32\drivers\viostor.sys" + pci = r"PCI\VEN_1AF4&DEV_1001&SUBSYS_00021AF4&REV_00\3&13c0b0c5&0&20" + + with self.open_hive('SYSTEM', write=True) as hive: + + # SYSTEM/CurrentControlSet/Control/CriticalDeviceDatabase + control = traverse(hive, "/%s/Control" % self.current_control_set) + cdd = safe_add_node(hive, control, 'CriticalDeviceDatabase') + + guid = "{4D36E97B-E325-11CE-BFC1-08002BE10318}" + + for subsys in '00000000', '00020000', '00021af4': + name = "pci#ven_1af4&dev_1001&subsys_%s" % subsys + + node = safe_add_node(hive, cdd, name) + + hive.node_set_value(node, REG_SZ('ClassGUID', guid)) + hive.node_set_value(node, REG_SZ('Service', 'viostor')) + + # SYSTEM/CurrentContolSet/Services/viostor + services = hive.root() + for child in (self.current_control_set, 'Services'): + services = hive.node_get_child(services, child) + + viostor = safe_add_node(hive, services, 'viostor') + hive.node_set_value(viostor, REG_SZ('Group', 'SCSI miniport')) + hive.node_set_value(viostor, REG_SZ('ImagePath', path)) + hive.node_set_value(viostor, REG_DWORD('ErrorControl', 1)) + hive.node_set_value(viostor, REG_DWORD('Start', 0)) + hive.node_set_value(viostor, REG_DWORD('Type', 1)) + hive.node_set_value(viostor, REG_DWORD('Tag', 0x21)) + + params = safe_add_node(hive, viostor, 'Parameters') + hive.node_set_value(params, REG_DWORD('BusType', 1)) + + mts = safe_add_node(hive, params, 'MaxTransferSize') + hive.node_set_value(mts, + REG_SZ('ParamDesc', 'Maximum Transfer Size')) + hive.node_set_value(mts, REG_SZ('type', 'enum')) + hive.node_set_value(mts, REG_SZ('default', '0')) + + enum = safe_add_node(hive, mts, 'enum') + hive.node_set_value(enum, REG_SZ('0', '64 KB')) + hive.node_set_value(enum, REG_SZ('1', '128 KB')) + hive.node_set_value(enum, REG_SZ('2', '256 KB')) + + pnp_interface = safe_add_node(hive, params, 'PnpInterface') + hive.node_set_value(pnp_interface, REG_DWORD('5', 1)) + enum = safe_add_node(hive, viostor, 'Enum') + hive.node_set_value(enum, REG_SZ('0', pci)) + hive.node_set_value(enum, REG_DWORD('Count', 1)) + hive.node_set_value(enum, REG_DWORD('NextInstance', 1)) + + hive.commit(None) + + def check_viostor_service(self): + """Checks if the viostor service is installed""" + + service = '%s/Services/viostor' % self.current_control_set + + with self.open_hive('SYSTEM', write=False) as hive: + return traverse(hive, service) is not None + + def update_devices_dirs(self, dirname, append=True): + """Update the value of the DevicePath registry key. If the append flag + is True, the dirname is appended to the list of devices directories, + otherwise the value is overwritten. + + This function returns the old value of the registry key + """ + + with self.open_hive('SOFTWARE', write=True) as hive: + + current = traverse(hive, '/Microsoft/Windows/CurrentVersion') + + device_path = hive.node_get_value(current, 'DevicePath') + regtype, value = hive.value_value(device_path) + + assert regtype == 2L, "Type (=%d) is not REG_EXPAND_SZ" % regtype + + # Remove the trailing '\x00' character + old_value = value.decode('utf-16le')[:-1] + + new_value = "%s;%s" % (old_value, dirname) if append else dirname + + hive.node_set_value(current, + REG_EXPAND_SZ('DevicePath', new_value)) + hive.commit(None) + + return old_value + +# vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/os_type/windows/vm.py b/image_creator/os_type/windows/vm.py new file mode 100644 index 0000000000000000000000000000000000000000..4501166ca963c20dc160791bb5c284e42e326f5b --- /dev/null +++ b/image_creator/os_type/windows/vm.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011-2014 GRNET S.A. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +"""This module provides an interface for launching windows VMs""" + +import random +import subprocess +import signal +import tempfile +import os +import time +import errno +from string import lowercase, uppercase, digits + +from image_creator.util import FatalError, get_kvm_binary +from image_creator.os_type.windows.winexe import WinEXE, WinexeTimeout + +# Just a random 16 character long token +RANDOM_TOKEN = "".join(random.choice(lowercase + uppercase) for _ in range(16)) + + +class VM(object): + """Windows Virtual Machine""" + def __init__(self, disk, params, admin): + """Create VM instance""" + + self.disk = disk + self.params = params + self.admin = admin + self.interface = 'virtio' + + # expected number of token occurrences in serial port + self._ntokens = 0 + + kvm, needed_args = get_kvm_binary() + if kvm is None: + raise FatalError("Can't find the kvm binary") + + self.kvm = [kvm] + list(needed_args) + + def random_mac(): + """creates a random mac address""" + mac = [0x00, 0x16, 0x3e, + random.randint(0x00, 0x7f), + random.randint(0x00, 0xff), + random.randint(0x00, 0xff)] + + return ':'.join(['%02x' % x for x in mac]) + + self.mac = random_mac() + + def random_password(): + """Creates a random password""" + + # I borrowed this from Synnefo + pool = lowercase + uppercase + digits + lowerset = set(lowercase) + upperset = set(uppercase) + digitset = set(digits) + length = 10 + + password = ''.join(random.choice(pool) for i in range(length - 2)) + + # Make sure the password is compliant + chars = set(password) + if not chars & lowerset: + password += random.choice(lowercase) + if not chars & upperset: + password += random.choice(uppercase) + if not chars & digitset: + password += random.choice(digits) + + # Pad if necessary to reach required length + password += ''.join(random.choice(pool) for i in + range(length - len(password))) + + return password + + self.password = random_password() + + # Use Ganeti's VNC port range for a random vnc port + self.display = random.randint(11000, 14999) - 5900 + + self.serial = None + self.process = None + + def isalive(self): + """Check if the VM is alive""" + return self.process is not None and self.process.poll() is None + + def start(self, **kwargs): + """Start the windows VM""" + + self._ntokens = 0 + + args = [] + args.extend(self.kvm) + + if 'smp' in self.params: + args.extend(['-smp', str(self.params['smp'].value)]) + + if 'mem' in self.params: + args.extend(['-m', str(self.params['mem'].value)]) + + args.extend(['-drive', + 'file=%s,format=raw,cache=unsafe,if=%s' % + (self.disk, self.interface)]) + + args.extend( + ['-netdev', 'type=user,hostfwd=tcp::445-:445,id=netdev0', + '-device', 'rtl8139,mac=%s,netdev=netdev0' % self.mac]) + + if 'extra_disk' in kwargs: + fname, iftype = kwargs['extra_disk'] + args.extend(['-drive', + 'file=%s,format=raw,cache=unsafe,if=%s' % + (fname, iftype)]) + + args.extend(['-vnc', ":%d" % self.display]) + + # The serial port + serialfd, self.serial = tempfile.mkstemp() + os.close(serialfd) + args.extend(['-serial', 'file:%s' % self.serial]) + + args.extend(['-monitor', 'stdio']) + + self.process = subprocess.Popen(args, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + def stop(self, timeout=0, fatal=True): + """Stop the VM""" + + try: + if not self.isalive(): + return + + def handler(signum, frame): + self.process.terminate() + time.sleep(1) + if self.isalive(): + self.process.kill() + self.process.wait() + if fatal: + raise FatalError("Stopping the VM timed-out") + + signal.signal(signal.SIGALRM, handler) + + signal.alarm(timeout) + self.process.communicate(input="system_powerdown\n") + signal.alarm(0) + + finally: + if self.serial is not None: + try: + os.unlink(self.serial) + except OSError as e: + if errno.errorcode[e.errno] != 'ENOENT': # File not found + raise + + def wait_on_serial(self, timeout): + """Wait until the random token appears on the VM's serial port""" + + self._ntokens += 1 + + for _ in xrange(timeout): + time.sleep(1) + with open(self.serial) as f: + current = 0 + for line in f: + if line.startswith(RANDOM_TOKEN): + current += 1 + if current == self._ntokens: + return True + if not self.isalive(): + (stdout, stderr, rc) = self.wait() + raise FatalError("Windows VM died unexpectedly!\n\n" + "(rc=%d)\n%s" % (rc, stderr)) + + return False + + def wait(self, timeout=0): + """Wait for the VM to shutdown by itself""" + + def handler(signum, frame): + raise FatalError("VM wait timed-out.") + + signal.signal(signal.SIGALRM, handler) + + signal.alarm(timeout) + stdout, stderr = self.process.communicate() + signal.alarm(0) + + return (stdout, stderr, self.process.poll()) + + def rexec(self, command, **kwargs): + """Remote execute a command on the windows VM + + The following optional flags are allowed: + + * fatal: If True, a FatalError is thrown if the command fails + + * debug: If True, WinEXE is executed in the highest debug level + + * uninstall: If True, the winexesvc.exe service will be uninstalled + after the execution of the command. + """ + + fatal = kwargs['fatal'] if 'fatal' in kwargs else True + debug = kwargs['debug'] if 'debug' in kwargs else False + uninstall = kwargs['uninstall'] if 'uninstall' in kwargs else False + + winexe = WinEXE(self.admin.name, 'localhost', password=self.password) + winexe.no_pass() + + if debug: + winexe.debug(9) + + if uninstall: + winexe.uninstall() + + try: + (stdout, stderr, rc) = winexe.run(command) + except WinexeTimeout: + raise FatalError("Command: `%s' timeout out." % command) + + if rc != 0 and fatal: + log = tempfile.NamedTemporaryFile(delete=False) + try: + log.file.write("STDOUT:\n%s\n" % stdout) + log.file.write("STDERR:\n%s\n" % stderr) + finally: + fname = log.name + log.close() + + # self.out.output("Command: `%s' failed (rc=%d). Reason: %s" % + # (command, rc, reason)) + raise FatalError("Command: `%s' failed (rc=%d). See: %s" % + (command, rc, fname)) + + return (stdout, stderr, rc) + +# vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/winexe.py b/image_creator/os_type/windows/winexe.py similarity index 57% rename from image_creator/winexe.py rename to image_creator/os_type/windows/winexe.py index 80bdea96587ec5b7c4f09d2ba49c6109d9a8a54d..990d849c05067253a6c680be61b3e96035e309c8 100644 --- a/image_creator/winexe.py +++ b/image_creator/os_type/windows/winexe.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2013 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module provides an interface for the WinEXE utility""" @@ -55,11 +37,12 @@ class WinEXE: def is_installed(program='winexe'): return which(program) is not None - def __init__(self, username, password, hostname, program='winexe'): - self._host = hostname + def __init__(self, username, hostname, **kwargs): self._user = username - self._pass = password - self._prog = program + self._host = hostname + + self._pass = kwargs['password'] if 'password' in kwargs else None + self._prog = kwargs['progname'] if 'progname' in kwargs else 'winexe' # -U USERNAME[%PASSWORD] user = '%s%s' % (self._user, '%%%s' % self._pass if self._pass else "") @@ -72,9 +55,12 @@ class WinEXE: user = '%s%s' % (self._user, '%%%s' % self._pass if self._pass else "") self._opts = ['-U', user] - def runas(self, username, password): + def runas(self, username, passwd=None): """Run command as this user""" - self._opts.append('--runas=%s%%%s' % (username, password)) + + opt = '--runas=%s%s' % (username, + '%%%s' % passwd if passwd is not None else "") + self._opts.append(opt) return self def system(self): @@ -82,6 +68,11 @@ class WinEXE: self._opts.append('--system') return self + def no_pass(self): + """Do not ask for password""" + self._opts.append('--no-pass') + return self + def uninstall(self): """Uninstall winexe service after remote execution""" self._opts.append('--uninstall') diff --git a/image_creator/output/__init__.py b/image_creator/output/__init__.py index b4aa7c080a09c5399d1ce0282f751560b576959e..4e86a8032c0cbfd1d087249a5523300054b668e6 100644 --- a/image_creator/output/__init__.py +++ b/image_creator/output/__init__.py @@ -1,40 +1,22 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This package is intended to provide output classes for printing messages and -progress bars. The user can change the output behaviour of the program by +progress bars. The user can change the output behavior of the program by subclassing the Output class and assigning the derived one as the output class of the various parts of the image-creator package. """ diff --git a/image_creator/output/cli.py b/image_creator/output/cli.py index 46c84c9d14bde79436ff2847da09e21ba356d819..d938e945edb5849f3f72ca99975dc3313ec585da 100644 --- a/image_creator/output/cli.py +++ b/image_creator/output/cli.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """Normal Command-line interface output""" diff --git a/image_creator/output/composite.py b/image_creator/output/composite.py index 52285047d2ed8486ffbfeb660b76dbf8b8306c9a..cb7820651e61c9c9b57a5fde375c9809fe469575 100644 --- a/image_creator/output/composite.py +++ b/image_creator/output/composite.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module implements the CompositeOutput output class""" diff --git a/image_creator/output/dialog.py b/image_creator/output/dialog.py index a82b986d7334bac54774734634917143e07b1b26..be0297ba001bce22ee5c92dce8be94149e4f92f5 100644 --- a/image_creator/output/dialog.py +++ b/image_creator/output/dialog.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module provides various dialog-based Output classes""" @@ -48,12 +30,12 @@ class GaugeOutput(Output): self.percent = 0 self.d.gauge_start(self.msg, title=title) - # Open pipe workaround. A fork will dublicate the open file descriptor. + # Open pipe workaround. A fork will duplicate the open file descriptor. # The FD_CLOEXEC flag makes sure that the gauge internal fd will be # closed if execve is executed. This is needed because libguestfs will - # fork/exec the kvm process. If this fd stays open in the kvm process, + # fork/exec the KVM process. If this fd stays open in the KVM process, # then doing a gauge_stop will make this process wait forever for - # a dialog process that is blocked waiting for input from the kvm + # a dialog process that is blocked waiting for input from the KVM # process's open file descriptor. fd = self.d._gauge_process['stdin'].fileno() flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0) @@ -67,7 +49,7 @@ class GaugeOutput(Output): time.sleep(0.4) def success(self, result, new_line=True): - """Print result after a successfull action""" + """Print result after a successful action""" self.percent = 100 self.d.gauge_update(self.percent, "%s %s" % (self.msg, result), update_text=True) diff --git a/image_creator/rsync.py b/image_creator/rsync.py index 833d0be745cb50af218eaefa06579a25d9c3b710..deef53195d94dfd2748f635c016a52241a551980 100644 --- a/image_creator/rsync.py +++ b/image_creator/rsync.py @@ -1,37 +1,19 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module provides an interface for the rsync utility""" diff --git a/image_creator/util.py b/image_creator/util.py index 4e1b7062098e678dc99e5c4c202c8baec7992fc6..c38e5a4f943c4ed78ade70eec465ca04a1478198 100644 --- a/image_creator/util.py +++ b/image_creator/util.py @@ -1,47 +1,30 @@ # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """This module provides various helper functions to be used by other parts of the package. """ import sh -import hashlib import time import os import re +import json +import tempfile class FatalError(Exception): @@ -64,6 +47,25 @@ def get_command(command): return find_sbin_command(command, e) +def image_info(image): + """Returns information about an image file""" + + qemu_img = get_command('qemu-img') + info = qemu_img('info', '--output', 'json', image) + return json.loads(str(info)) + + +def create_snapshot(source, target_dir): + """Returns a qcow2 snapshot of an image file""" + + qemu_img = get_command('qemu-img') + snapfd, snap = tempfile.mkstemp(prefix='snapshot-', dir=target_dir) + os.close(snapfd) + qemu_img('create', '-f', 'qcow2', '-o', + 'backing_file=%s' % os.path.abspath(source), snap) + return snap + + def get_kvm_binary(): """Returns the path to the kvm binary and some extra arguments if needed""" @@ -108,32 +110,73 @@ def free_space(dirname): return stat.f_bavail * stat.f_frsize -class MD5: - """Represents MD5 computations""" - def __init__(self, output): - """Create an MD5 instance""" - self.out = output - - def compute(self, filename, size): - """Compute the MD5 checksum of a file""" - MB = 2 ** 20 - BLOCKSIZE = 4 * MB # 4MB - - prog_size = ((size + MB - 1) // MB) # in MB - progressbar = self.out.Progress(prog_size, "Calculating md5sum", 'mb') - md5 = hashlib.md5() - with open(filename, "r") as src: - left = size - while left > 0: - length = min(left, BLOCKSIZE) - data = src.read(length) - md5.update(data) - left -= length - progressbar.goto((size - left) // MB) - - checksum = md5.hexdigest() - progressbar.success(checksum) - - return checksum +def virtio_versions(virtio_state): + """Returns the versions of the drivers defined by the virtio state""" + + ret = {} + for name, infs in virtio_state.items(): + driver_ver = [drv['DriverVer'].split(',', 1) if 'DriverVer' in drv + else [] for drv in infs.values()] + vers = [v[1] if len(v) > 1 else " " for v in driver_ver] + ret[name] = "<not found>" if len(infs) == 0 else ", ".join(vers) + + return ret + + +class QemuNBD(object): + """Wrapper class for the qemu-nbd tool""" + + def __init__(self, image): + """Initialize an instance""" + self.image = image + self.device = None + self.pattern = re.compile('^nbd\d+$') + self.modprobe = get_command('modprobe') + self.qemu_nbd = get_command('qemu-nbd') + + def _list_devices(self): + """Returns all the NBD block devices""" + return set([d for d in os.listdir('/dev/') if self.pattern.match(d)]) + + def connect(self, ro=True): + """Connect the image to a free NBD device""" + devs = self._list_devices() + + if len(devs) == 0: # Is nbd module loaded? + self.modprobe('nbd', 'max_part=16') + # Wait a second for /dev to be populated + time.sleep(1) + devs = self._list_devices() + if len(devs) == 0: + raise FatalError("/dev/nbd* devices not present!") + + # Ignore the nbd block devices that are in use + with open('/proc/partitions') as partitions: + for line in iter(partitions): + entry = line.split() + if len(entry) != 4: + continue + if entry[3] in devs: + devs.remove(entry[3]) + + if len(devs) == 0: + raise FatalError("All NBD block devices are busy!") + + device = '/dev/%s' % devs.pop() + args = ['-c', device] + if ro: + args.append('-r') + args.append(self.image) + + self.qemu_nbd(*args) + self.device = device + return device + + def disconnect(self): + """Disconnect the image from the connected device""" + assert self.device is not None, "No device connected" + + self.qemu_nbd('-d', self.device) + self.device = None # vim: set sta sts=4 shiftwidth=4 sw=4 et ai : diff --git a/image_creator/version.py b/image_creator/version.py index ecc3557b9aab7760bfbb9410eddf2c400084e439..c3fc276ffd32ea11b0ab818a049feb6874b81a4b 100644 --- a/image_creator/version.py +++ b/image_creator/version.py @@ -1,8 +1,8 @@ -__version__ = "0.6.2" +__version__ = "0.7rc2" __version_vcs_info__ = { - 'branch': 'hotfix-0.6.2', - 'revid': '73cec8b', - 'revno': 438} + 'branch': 'release-0.7', + 'revid': '9813162', + 'revno': 564} __version_user_email__ = "skalkoto@grnet.gr" __version_user_name__ = "Nikos Skalkotos" diff --git a/setup.py b/setup.py index 3a6dd27063970093d3d8818ee078ae5882e551dc..d2de6fcdc3e84058b74697c5bb8db5539ac10b05 100755 --- a/setup.py +++ b/setup.py @@ -1,38 +1,20 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- # -# Copyright 2012 GRNET S.A. All rights reserved. +# Copyright (C) 2011-2014 GRNET S.A. # -# Redistribution and use in source and binary forms, with or -# without modification, are permitted provided that the following -# conditions are met: +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. # -# 1. Redistributions of source code must retain the above -# copyright notice, this list of conditions and the following -# disclaimer. +# 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 General Public License for more details. # -# 2. Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials -# provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR -# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# -# The views and conclusions contained in the software and -# documentation are those of the authors and should not be -# interpreted as representing official policies, either expressed -# or implied, of GRNET S.A. +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. import image_creator @@ -42,7 +24,7 @@ setup( name='snf_image_creator', version=image_creator.__version__, description='Command line tool for creating images', - long_description=open('README').read(), + long_description=open('README.md').read(), url='https://code.grnet.gr/projects/snf-image-creator', author="Synnefo development team", author_email="synnefo-devel@googlegroups.com", diff --git a/version b/version index b6160487433ba524a39a93cde5a330f7e71d0d39..22e9674151c70675fea07f7ed4dbed62fabfdc4a 100644 --- a/version +++ b/version @@ -1 +1 @@ -0.6.2 +0.7rc2