commit 379262a74fb870c16bc60e0f641a0b4f1b434f9d Author: Joshua M. Boniface Date: Wed Dec 29 22:31:01 2021 -0500 Initial commit of PVC Bootstrap system Adds the PVC Bootstrap system, which allows the automated deployment of one or more PVC clusters. diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..a0b5e47 --- /dev/null +++ b/.flake8 @@ -0,0 +1,10 @@ +[flake8] +# We ignore the following errors: +# * W503 (line break before binary operator): Black moves these to new lines +# * E501 (line too long): Long lines are a fact of life in comment blocks; Black handles active instances of this +# * E203 (whitespace before ':'): Black recommends this as disabled +ignore = W503, E501 +extend-ignore = E203 +# Set the max line length to 88 for Black +max-line-length = 88 + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9c923c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.pyc +*.tmp +*.swp diff --git a/.hooks/pre-commit b/.hooks/pre-commit new file mode 100755 index 0000000..caf166c --- /dev/null +++ b/.hooks/pre-commit @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +pushd $( git rev-parse --show-toplevel ) &>/dev/null + +ex=0 + +./format check +if [[ $? -ne 0 ]]; then + ./format + echo "Black formatting change detected; review and recommit" + ex=1 +fi + +./lint +if [[ $? -ne 0 ]]; then + echo "Linting error detected; correct and recommit" + ex=1 +fi + +echo +popd &>/dev/null +exit $ex diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d0341c6 --- /dev/null +++ b/README.md @@ -0,0 +1,178 @@ +# PVC Bootstrap System + +The PVC bootstrap system provides a convenient way to deploy PVC clusters. Rather than manual node installation, this system provides a fully-automated deployment from node powering to cluster readiness, based on pre-configured values. It is useful if an administrator will deploy several PVC clusters or for repeated re-deployment for testing purposes. + +## Setup + +Setting up the PVC bootstrap system manually is very complicated, and has thus been automated with an installer script instead of providing a Debian or PIP package. + +### Preparing to use the PVC Bootstrap system + +1. Prepare a Git repository to store cluster configurations. This can be done automatically with the `create-local-repo.sh` script in the [PVC Ansible](https://github.com/parallelvirtualcluster/pvc-ansible) repository. + +1. Create `group_vars` for each cluster you plan to bootstrap. Additionally, ensure you configure the `bootstrap.yml` file for each cluster with the relevant details of the hardware you will be using. This step can be repeated for each cluster in the future as new clusters are required, and the system will automatically pull changes to the local PVC repository once configured. + +### Preparing a PVC Bootstrap host + +1. The recommended OS for a PVC Bootstrap host is Debian GNU/Linux 10+. In terms of hardware, there are several supported options: + + i) A small single-board computer with wired Ethernet like a Raspberry Pi on `aarch64` (32-bit ARM not supported); at least a Pi model 4 or similar modern system is required; Pi models 1-3 do not support `aarch64` or are extremely slow in comparison, especially when building the initial TFTP installer root. + + ii) A small desktop computer on `amd64` with at least one wired Ethernet port. + + iii) A VM on `amd64` or `aarch64` connected to the required networks. + +1. Set up a basic outbound network with Internet access; as detailed below, the installer will take care of the internal bootstrap network, either on a dedicated NIC or vLAN, with this host providing NAT'd access out. + +1. Clone this repository somewhere on the host, for instance to `/srv` or `/home`. + +1. Run the `./install-pvcbootstrapd.sh` script from the root of the repository to install the PVC Bootstrap system on the host. It will prompt for several configuration parameters. The final steps will take some time (up to 2 hours on a Raspberry Pi 4B) so be patient. + +### Networking for Bootstrap + +When using the pvcbootstrapd system, a dedicated network is required to provide bootstrap DHCP and TFTP to the cluster. This network can either have a dedicated, upstream router that does not provide DHCP, or the network can be routed with network address translation (NAT) through the bootstrap host. By default, the installer will configure the latter automatically using a second NIC separate from the upstream NIC of the bootstrap host, or via a vLAN on top of the single NIC. + +In bootstrap mode (as opposed to manual install mode), new nodes are configured with their interfaces as follows: + + * BMC: bootstrap + * Interface 1 (first among all LOM ports): bootstrap + * Interface 2+ (all other ports): LACP (802.3ad) bond0 + +The Bootstrap interfaces do DHCP from the bootstrap host, and are thus responsible for autoconfiguration. The remaining interfaces, in an LACP bond, are used to underlay the various standard PVC networks. + +Care must therefore be taken to ensure that the BMC and *first* lan-on-motherboard interface are connected as vLAN access ports in the bootstrap network, and that the remaining ports have some connectivity along the various configured PVC networks, before proceeding. + +Consider the following diagram for reference: + +![Per-Node Physical Connections](/docs/images/pvcbootstrapd-phy.png) + +![Overall Network Topology](/docs/images/pvcbootstrapd-net.png) + +### Deploying a Cluster with PVC Bootstrap - Redfish + +Redfish is an industry-standard RESTful API for interfacing with the BMC (baseband management controller, or out-of-band network management system) on modern (post ~2015) servers from most vendors, including Dell iDRAC, HP iLO, Cisco CIMC, Lenovo XCC, and Supermicro X10 and newer BMCs. Redfish allows remote management, data collection, and configuration from the BMC in a standardized way across server vendors. + +The PVC Bootstrap system is designed to heavily leverage Redfish in its automation. With Redfish, cluster deployment is plug-and-play, with no human input after committing the required configuration and connecting the servers. The steps are thus: + +1. Ensure the cluster configuration `hosts` entries and `group_vars` are committed to the local PVC repository, including the BMC MAC addresses, default IPMI credentials, and desired hooks (`bootstrap.yml`), and all other cluster configurations (`base.yml` and `pvc.yml`). Generated configurations (e.g. `files`) will be automatically committed to the repository. + +1. Connect the network ports as outlined in the above diagrams. + +1. Connect power to the servers, but do not manually power on the servers - Redfish will handle this aspect after characterizing each host, as well as manage boot, RAID array creation (as documented in `bootstrap.yml`), BIOS configuration, etc. + +1. Wait for the cluster bootstrapping to complete; you can watch the output of the `pvcbootstrapd` and `pvcbootstrapd-worker` services on the Bootstrap host to see progress. If supported, the indicator LEDs of the nodes will be lit during setup and will be disabled upon completion to provide a physical indication of the process. + +1. Verify and power off the servers and put them into production; you may need to complete several post-install tasks (for instance setting the production BMC networking via `sudo ifup ipmi` on each node) before the cluster is completely finished. + +### Deploying a Cluster with PVC Bootstrap - Non-Redfish + +The PVC Bootstrap system can still handle nodes without Redfish support, for instance older servers or those from non-compliant vendors. There is however more manual setup in the process. The steps are thus: + +1. Ensure the cluster configuration `hosts` entries and `group_vars` are committed to the local PVC repository, including the BMC MAC addresses, default IPMI credentials, and desired hooks (`bootstrap.yml`), and all other cluster configurations (`base.yml` and `pvc.yml`). Generated configurations (e.g. `files`) will be automatically committed to the repository. Ensure you set `redfish: no` in the appropriate section of the `bootstrap.yml` file; the BMC credentials can be empty but the variables must exist. + +1. Do not (yet) connect network ports. + +1. Connect power to the servers and power them on. + +1. Perform any required configuration of BIOS settings, hardware RAID arrays for the system disk, etc. + +1. Power off the servers. + +1. Create a set of host configuration files in the TFTP `host` directory on the PVC controller, by default at `/srv/pvc/tftp/host`, one per node. You will need to know the MAC address of the first ethernet (bootstrap network) port of each node to correctly set the filename. Some example contents for the two files are shown below. + +1. Connect the network ports as outlined in the above diagrams. + +1. Power on the servers and set them to boot temporarily (one time) from PXE. + +1. Wait for the cluster bootstrapping to complete; you can watch the output of the `pvcbootstrapd` and `pvcbootstrapd-worker` services on the Bootstrap host to see progress. If supported, the indicator LEDs of the nodes will be lit during setup and will be disabled upon completion to provide a physical indication of the process. + +1. Verify and power off the servers and put them into production; you may need to complete several post-install tasks (for instance setting the production BMC networking via `sudo ifup ipmi` on each node) before the cluster is completely finished. + +#### `host-MAC.ipxe` + +``` +#1ipxe + +# The name of this file is "host-123456abcdef.ipxe", where "123456abcdef" is the MAC address of the +# server's Bootstrap Ethernet port (on-motherboard port 1), without spaces or punctuation. + +# ARGUMENTS are any additional kernel command line arguments that might be needed for installer boot +# For instance, on an HP DL360 G6 the serial console is ttyS1 at 115200 baud, so the line would be: +# set imgargs-host console=ttyS1,115200n + +# If no additional arguments are required, then this file is optional, or you can set an empty +# imaargs-host value. + +set imgargs-host ARGUMENTS +``` + +#### `host-MAC.preseed` + +``` +# The name of this file is "host-123456abcdef.preseed", where "123456abcdef" is the MAC address of the +# server's Bootstrap Ethernet port (on-motherboard port 1), without spaces or punctuation. + +# This file defines the various configuration options to preseed the installer. An example here shows +# the various options, but what to put depends on the exact configuration of pvcbootstrapd. This +# information is, under Redfish, populated automatically based on the information provided in the +# cluster "bootstrap.yml" group vars file. + +# Any option not set explicitly here is not set by the bootstrap system by default and should not need +# to be changed by the administrator. + +# This BASH-compliant variables file is Loaded during PXE installs to preseed the environment. +# During normal usage, the pvcbootstrapd will load this file, adjust it according to its needs, +# and write out one instance per node to be installed. +# +# This file is thus not designed to be used by humans, and its values are seeded via options in +# the cluster-local Ansible group_vars, though it can be used as a manual template if required. + +### +### General definitions/overrides +### +# The Debian release to use (overrides the default) +debrelease="bullseye" + +# The Debian mirror to use (overrides the default) +debmirror="http://ftp.debian.org/debian" + +# Additional packages (comma-separated) to install in the base system +addpkglist="ca-certificates" + +# Alternate filesystem for system volumes (/, /var/lib/ceph, /var/lib/zookeeper) +filesystem="ext4" + + +### +### Per-host definitions (required) +### + +# The hostname of the system (set per-run) +target_hostname="hv1.example.tld" + +# The target system disk path +target_disk="detect:LOGICAL:146GB:0" + +# SSH key method (usually tftp) +target_keys_method="tftp" + +# SSH key path (usually keys.txt) +target_keys_path="keys.txt" + +# Deploy username (usually deploy) +target_deploy_user="deploy" + +# Consoles to use by the inital boot process; these are normally set automatically +# based on the TTYs found by the installer, and are later overridden by the Ansible +# playbooks based on the hardware configuration. It is best to leave this commented +# unless you know that you need it. +#target_consoles="console=tty1 console=ttyS1,115200" + +# Modules to blacklist from the installed system; we include hpwdt (HP Proliant +# watchdog) by default since this is known to cause kernel panics on boot with this +# hardware. Add others here too if you wish to add more to the default. +#target_module_blacklist=( "hpwdt" ) + +# Installer checkin URI (provided by pvcbootstrapd) +pvcbootstrapd_checkin_uri="http://10.255.255.1:9999/checkin/host" +``` diff --git a/bootstrap-daemon/clusters.yaml.sample b/bootstrap-daemon/clusters.yaml.sample new file mode 100644 index 0000000..73fd85a --- /dev/null +++ b/bootstrap-daemon/clusters.yaml.sample @@ -0,0 +1,7 @@ +--- +# clusters.yml +# This file defines a list of Clusters that pvcbootstrapd should be aware of. + +clusters: + - cluster1 + - cluster2 diff --git a/bootstrap-daemon/pvcbootstrapd-worker.service b/bootstrap-daemon/pvcbootstrapd-worker.service new file mode 100644 index 0000000..fde632b --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd-worker.service @@ -0,0 +1,16 @@ +# Parallel Virtual Cluster Provisioner API provisioner worker unit file + +[Unit] +Description = Parallel Virtual Cluster Bootstrap API worker +After = network-online.target + +[Service] +Type = simple +WorkingDirectory = /usr/share/pvc +Environment = PYTHONUNBUFFERED=true +Environment = PVC_CONFIG_FILE=/etc/pvc/pvcbootstrapd.yaml +ExecStart = /usr/share/pvc/pvcbootstrapd-worker.sh +Restart = on-failure + +[Install] +WantedBy = multi-user.target diff --git a/bootstrap-daemon/pvcbootstrapd-worker.sh b/bootstrap-daemon/pvcbootstrapd-worker.sh new file mode 100755 index 0000000..3063f81 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd-worker.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +# pvcbootstrapd-worker.py - API Celery worker daemon startup stub +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +CELERY_BIN="$( which celery )" + +# This absolute hackery is needed because Celery got the bright idea to change how their +# app arguments work in a non-backwards-compatible way with Celery 5. +case "$( cat /etc/debian_version )" in + 10.*) + CELERY_ARGS="worker --app pvcbootstrapd.flaskapi.celery --concurrency 99 --pool gevent --loglevel DEBUG" + ;; + 11.*) + CELERY_ARGS="--app pvcbootstrapd.flaskapi.celery worker --concurrency 99 --pool gevent --loglevel DEBUG" + ;; + *) + echo "Invalid Debian version found!" + exit 1 + ;; +esac + +${CELERY_BIN} ${CELERY_ARGS} +exit $? diff --git a/bootstrap-daemon/pvcbootstrapd.py b/bootstrap-daemon/pvcbootstrapd.py new file mode 100755 index 0000000..5d12e8f --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 + +# pvcbootstrapd.py - Bootstrap API daemon startup stub +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import pvcbootstrapd.Daemon # noqa: F401 + +pvcbootstrapd.Daemon.entrypoint() diff --git a/bootstrap-daemon/pvcbootstrapd.service b/bootstrap-daemon/pvcbootstrapd.service new file mode 100644 index 0000000..1fe3616 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd.service @@ -0,0 +1,16 @@ +# Parallel Virtual Cluster Bootstrap API daemon unit file + +[Unit] +Description = Parallel Virtual Cluster Bootstrap API daemon +After = network-online.target + +[Service] +Type = simple +WorkingDirectory = /usr/share/pvc +Environment = PYTHONUNBUFFERED=true +Environment = PVC_CONFIG_FILE=/etc/pvc/pvcbootstrapd.yaml +ExecStart = /usr/share/pvc/pvcbootstrapd.py +Restart = on-failure + +[Install] +WantedBy = multi-user.target diff --git a/bootstrap-daemon/pvcbootstrapd.yaml.sample b/bootstrap-daemon/pvcbootstrapd.yaml.sample new file mode 100644 index 0000000..b50c7ae --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd.yaml.sample @@ -0,0 +1,91 @@ +--- +pvc: + # Enable debug mode + debug: true + + # Deploy username + deploy_username: deploy + + # Database (SQLite) configuration + database: + # Path to the database file + path: /srv/tftp/pvcbootstrapd.sql + + # Flask API configuration + api: + # Listen address + address: 10.199.199.254 + + # Listen port + port: 9999 + + # Redis Celery queue configuration + queue: + # Connect address + address: 127.0.0.1 + + # Connect port + port: 6379 + + # Redis path (almost always 0) + path: "/0" + + # DNSMasq DHCP configuration + dhcp: + # Listen address + address: 10.199.199.254 + + # Default gateway address + gateway: 10.199.199.1 + + # Local domain + domain: pvcbootstrap.local + + # DHCP lease range start + lease_start: 10.199.199.10 + + # DHCP lease range end + lease_end: 10.199.199.99 + + # DHCP lease time + lease_time: 1h + + # DNSMasq TFTP configuration + tftp: + # Root TFTP path (contents of the "buildpxe.sh" output directory; generally read-only) + root_path: "/srv/tftp/pvc-installer" + + # Per-host TFTP path (almost always "/host" under "root_path"; must be writable) + host_path: "/srv/tftp/pvc-installer/host" + + # PVC Ansible repository configuration + # Note: If "path" does not exist, "remote" will be cloned to it via Git using SSH private key "keyfile". + # Note: The VCS will be refreshed regularly via the API in response to webhooks. + ansible: + # Path to the VCS repository + path: "/var/home/joshua/pvc" + + # Path to the deploy key (if applicable) used to clone and pull the repository + keyfile: "/var/home/joshua/id_ed25519.joshua.key" + + # Git remote URI for the repository + remote: "ssh://git@git.bonifacelabs.ca:2222/bonifacelabs/pvc.git" + + # Git branch to use + branch: "master" + + # Clusters configuration file + clusters_file: "clusters.yml" + + # Filenames of the various group_vars components of a cluster + # Generally with pvc-ansible this will contain 2 files: "base.yml", and "pvc.yml"; refer to the + # pvc-ansible documentation and examples for details on these files. + # The third file, "bootstrap.yml", is used by pvcbootstrapd to map BMC MAC addresses to hosts and + # to simplify hardware detection. It must be present or the cluster will not be bootstrapped. + # Adjust these entries to match the actual filenames of your clusters; the pvc-ansible defaults + # are provided here. All clusters using this pvcbootstrapd instance must share identical filenames + # here. + cspec_files: + base: "base.yml" + pvc: "pvc.yml" + bootstrap: "bootstrap.yml" diff --git a/bootstrap-daemon/pvcbootstrapd.yaml.template b/bootstrap-daemon/pvcbootstrapd.yaml.template new file mode 100644 index 0000000..afe08a4 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd.yaml.template @@ -0,0 +1,33 @@ +--- +pvc: + debug: true + deploy_username: DEPLOY_USERNAME + database: + path: ROOT_DIRECTORY/pvcbootstrapd.sql + api: + address: BOOTSTRAP_ADDRESS + port: 9999 + queue: + address: 127.0.0.1 + port: 6379 + path: "/0" + dhcp: + address: BOOTSTRAP_ADDRESS + gateway: BOOTSTRAP_ADDRESS + domain: pvcbootstrap.local + lease_start: BOOTSTRAP_DHCPSTART + lease_end: BOOTSTRAP_DHCPEND + lease_time: 1h + tftp: + root_path: "ROOT_DIRECTORY/tftp" + host_path: "ROOT_DIRECTORY/tftp/host" + ansible: + path: "ROOT_DIRECTORY/repo" + keyfile: "ROOT_DIRECTORY/id_ed25519" + remote: "GIT_REMOTE" + branch: "GIT_BRANCH" + clusters_file: "clusters.yml" + cspec_files: + base: "base.yml" + pvc: "pvc.yml" + bootstrap: "bootstrap.yml" diff --git a/bootstrap-daemon/pvcbootstrapd/Daemon.py b/bootstrap-daemon/pvcbootstrapd/Daemon.py new file mode 100755 index 0000000..8820ed1 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/Daemon.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 + +# Daemon.py - PVC HTTP API daemon +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import os +import yaml +import signal + +from sys import argv + +import pvcbootstrapd.lib.dnsmasq as dnsmasqd +import pvcbootstrapd.lib.db as db +import pvcbootstrapd.lib.git as git +import pvcbootstrapd.lib.tftp as tftp + +from distutils.util import strtobool as dustrtobool + +# Daemon version +version = "0.1" + +# API version +API_VERSION = 1.0 + + +########################################################## +# Exceptions +########################################################## + + +class MalformedConfigurationError(Exception): + """ + An exception when parsing the PVC daemon configuration file + """ + + def __init__(self, error=None): + self.msg = f"ERROR: Configuration file is malformed: {error}" + + def __str__(self): + return str(self.msg) + + +########################################################## +# Helper Functions +########################################################## + + +def strtobool(stringv): + if stringv is None: + return False + if isinstance(stringv, bool): + return bool(stringv) + try: + return bool(dustrtobool(stringv)) + except Exception: + return False + + +########################################################## +# Configuration Parsing +########################################################## + + +def get_config_path(): + try: + return os.environ["PVCD_CONFIG_FILE"] + except KeyError: + print('ERROR: The "PVCD_CONFIG_FILE" environment variable must be set.') + os._exit(1) + + +def read_config(): + pvcbootstrapd_config_file = get_config_path() + + print(f"Loading configuration from file '{pvcbootstrapd_config_file}'") + + # Load the YAML config file + with open(pvcbootstrapd_config_file, "r") as cfgfile: + try: + o_config = yaml.load(cfgfile, Loader=yaml.SafeLoader) + except Exception as e: + print(f"ERROR: Failed to parse configuration file: {e}") + os._exit(1) + + # Create the configuration dictionary + config = dict() + + # Get the base configuration + try: + o_base = o_config["pvc"] + except KeyError as k: + raise MalformedConfigurationError(f"Missing top-level category {k}") + + for key in ["debug", "deploy_username"]: + try: + config[key] = o_base[key] + except KeyError as k: + raise MalformedConfigurationError(f"Missing first-level key {k}") + + # Get the first-level categories + try: + o_database = o_base["database"] + o_api = o_base["api"] + o_queue = o_base["queue"] + o_dhcp = o_base["dhcp"] + o_tftp = o_base["tftp"] + o_ansible = o_base["ansible"] + except KeyError as k: + raise MalformedConfigurationError(f"Missing first-level category {k}") + + # Get the Datbase configuration + for key in ["path"]: + try: + config[f"database_{key}"] = o_database[key] + except Exception: + raise MalformedConfigurationError( + f"Missing second-level key '{key}' under 'database'" + ) + + # Get the API configuration + for key in ["address", "port"]: + try: + config[f"api_{key}"] = o_api[key] + except Exception: + raise MalformedConfigurationError( + f"Missing second-level key '{key}' under 'api'" + ) + + # Get the queue configuration + for key in ["address", "port", "path"]: + try: + config[f"queue_{key}"] = o_queue[key] + except Exception: + raise MalformedConfigurationError( + f"Missing second-level key '{key}' under 'queue'" + ) + + # Get the DHCP configuration + for key in [ + "address", + "gateway", + "domain", + "lease_start", + "lease_end", + "lease_time", + ]: + try: + config[f"dhcp_{key}"] = o_dhcp[key] + except Exception: + raise MalformedConfigurationError( + f"Missing second-level key '{key}' under 'dhcp'" + ) + + # Get the TFTP configuration + for key in ["root_path", "host_path"]: + try: + config[f"tftp_{key}"] = o_tftp[key] + except Exception: + raise MalformedConfigurationError( + f"Missing second-level key '{key}' under 'tftp'" + ) + + # Get the Ansible configuration + for key in ["path", "keyfile", "remote", "branch", "clusters_file"]: + try: + config[f"ansible_{key}"] = o_ansible[key] + except Exception: + raise MalformedConfigurationError( + f"Missing second-level key '{key}' under 'ansible'" + ) + + # Get the second-level categories under Ansible + try: + o_ansible_cspec_files = o_ansible["cspec_files"] + except KeyError as k: + raise MalformedConfigurationError( + f"Missing second-level category {k} under 'ansible'" + ) + + # Get the Ansible CSpec Files configuration + for key in ["base", "pvc", "bootstrap"]: + try: + config[f"ansible_cspec_files_{key}"] = o_ansible_cspec_files[key] + except Exception: + raise MalformedConfigurationError( + f"Missing third-level key '{key}' under 'ansible/cspec_files'" + ) + + return config + + +config = read_config() + + +########################################################## +# Entrypoint +########################################################## + + +def entrypoint(): + import pvcbootstrapd.flaskapi as pvcbootstrapd # noqa: E402 + + # Print our startup messages + print("") + print("|----------------------------------------------------------|") + print("| |") + print("| ███████████ ▜█▙ ▟█▛ █████ █ █ █ |") + print("| ██ ▜█▙ ▟█▛ ██ |") + print("| ███████████ ▜█▙ ▟█▛ ██ |") + print("| ██ ▜█▙▟█▛ ███████████ |") + print("| |") + print("|----------------------------------------------------------|") + print("| Parallel Virtual Cluster Bootstrap API daemon v{0: <9} |".format(version)) + print("| Debug: {0: <49} |".format(str(config["debug"]))) + print("| API version: v{0: <42} |".format(API_VERSION)) + print( + "| Listen: {0: <48} |".format( + "{}:{}".format(config["api_address"], config["api_port"]) + ) + ) + print("|----------------------------------------------------------|") + print("") + + # Initialize the database + db.init_database(config) + + # Initialize the Ansible repository + git.init_repository(config) + + # Initialize the tftp root + tftp.init_tftp(config) + + if "--init-only" in argv: + print("Successfully initialized pvcbootstrapd; exiting.") + exit(0) + + # Start DNSMasq + dnsmasq = dnsmasqd.DNSMasq(config) + dnsmasq.start() + + def cleanup(retcode): + dnsmasq.stop() + exit(retcode) + + def term(signum="", frame=""): + print("Received TERM, exiting.") + cleanup(0) + + signal.signal(signal.SIGTERM, term) + signal.signal(signal.SIGINT, term) + signal.signal(signal.SIGQUIT, term) + + # Start Flask + pvcbootstrapd.app.run( + config["api_address"], + config["api_port"], + use_reloader=False, + threaded=False, + processes=4, + ) diff --git a/bootstrap-daemon/pvcbootstrapd/__init__.py b/bootstrap-daemon/pvcbootstrapd/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bootstrap-daemon/pvcbootstrapd/dnsmasq-lease.py b/bootstrap-daemon/pvcbootstrapd/dnsmasq-lease.py new file mode 100755 index 0000000..1b39186 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/dnsmasq-lease.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 + +# dnsmasq-lease.py - DNSMasq lease interface for pvcnodedprov +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +from os import environ +from sys import argv +from requests import post +from json import dumps + +# Request log +# dnsmasq-dhcp[877466]: 2067194916 available DHCP range: 10.199.199.10 -- 10.199.199.19 +# dnsmasq-dhcp[877466]: 2067194916 DHCPDISCOVER(ens8) 52:54:00:34:36:40 +# dnsmasq-dhcp[877466]: 2067194916 tags: ens8 +# dnsmasq-dhcp[877466]: 2067194916 DHCPOFFER(ens8) 10.199.199.14 52:54:00:34:36:40 +# dnsmasq-dhcp[877466]: 2067194916 requested options: 1:netmask, 28:broadcast, 2:time-offset, 3:router, +# dnsmasq-dhcp[877466]: 2067194916 requested options: 15:domain-name, 6:dns-server, 12:hostname +# dnsmasq-dhcp[877466]: 2067194916 next server: 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 1 option: 53 message-type 2 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 54 server-identifier 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 51 lease-time 1h +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 58 T1 30m +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 59 T2 52m30s +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 1 netmask 255.255.255.0 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 28 broadcast 10.199.199.255 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 3 router 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 6 dns-server 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 8 option: 15 domain-name test.com +# dnsmasq-dhcp[877466]: 2067194916 available DHCP range: 10.199.199.10 -- 10.199.199.19 +# dnsmasq-dhcp[877466]: 2067194916 DHCPREQUEST(ens8) 10.199.199.14 52:54:00:34:36:40 +# dnsmasq-dhcp[877466]: 2067194916 tags: ens8 +# dnsmasq-dhcp[877466]: 2067194916 DHCPACK(ens8) 10.199.199.14 52:54:00:34:36:40 +# dnsmasq-dhcp[877466]: 2067194916 requested options: 1:netmask, 28:broadcast, 2:time-offset, 3:router, +# dnsmasq-dhcp[877466]: 2067194916 requested options: 15:domain-name, 6:dns-server, 12:hostname +# dnsmasq-dhcp[877466]: 2067194916 next server: 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 1 option: 53 message-type 5 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 54 server-identifier 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 51 lease-time 1h +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 58 T1 30m +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 59 T2 52m30s +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 1 netmask 255.255.255.0 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 28 broadcast 10.199.199.255 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 3 router 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 4 option: 6 dns-server 10.199.199.1 +# dnsmasq-dhcp[877466]: 2067194916 sent size: 8 option: 15 domain-name test.com +# dnsmasq-script[877466]: ['/var/home/joshua/dnsmasq-lease.py', 'add', '52:54:00:34:36:40', '10.199.199.14'] +# dnsmasq-script[877466]: environ({'DNSMASQ_INTERFACE': 'ens8', 'DNSMASQ_LEASE_EXPIRES': '1638422308', 'DNSMASQ_REQUESTED_OPTIONS': '1,28,2,3,15,6,12', 'DNSMASQ_TAGS': 'ens8', 'DNSMASQ_TIME_REMAINING': '3600', 'DNSMASQ_LOG_DHCP': '1', 'LC_CTYPE': 'C.UTF-8'}) + +# Renew log +# dnsmasq-dhcp[877466]: 1471211555 available DHCP range: 10.199.199.10 -- 10.199.199.19 +# dnsmasq-dhcp[877466]: 1471211555 DHCPREQUEST(ens8) 10.199.199.14 52:54:00:34:36:40 +# dnsmasq-dhcp[877466]: 1471211555 tags: ens8 +# dnsmasq-dhcp[877466]: 1471211555 DHCPACK(ens8) 10.199.199.14 52:54:00:34:36:40 +# dnsmasq-dhcp[877466]: 1471211555 requested options: 1:netmask, 28:broadcast, 2:time-offset, 3:router, +# dnsmasq-dhcp[877466]: 1471211555 requested options: 15:domain-name, 6:dns-server, 12:hostname +# dnsmasq-dhcp[877466]: 1471211555 next server: 10.199.199.1 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 1 option: 53 message-type 5 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 54 server-identifier 10.199.199.1 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 51 lease-time 1h +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 58 T1 30m +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 59 T2 52m30s +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 1 netmask 255.255.255.0 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 28 broadcast 10.199.199.255 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 3 router 10.199.199.1 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 4 option: 6 dns-server 10.199.199.1 +# dnsmasq-dhcp[877466]: 1471211555 sent size: 8 option: 15 domain-name test.com +# dnsmasq-script[877466]: ['/var/home/joshua/dnsmasq-lease.py', 'old', '52:54:00:34:36:40', '10.199.199.14'] +# dnsmasq-script[877466]: environ({'DNSMASQ_INTERFACE': 'ens8', 'DNSMASQ_LEASE_EXPIRES': '1638422371', 'DNSMASQ_REQUESTED_OPTIONS': '1,28,2,3,15,6,12', 'DNSMASQ_TAGS': 'ens8', 'DNSMASQ_TIME_REMAINING': '3600', 'DNSMASQ_LOG_DHCP': '1', 'LC_CTYPE': 'C.UTF-8'}) + +action = argv[1] + +api_uri = environ.get("API_URI", "http://127.0.0.1:9999/checkin/dnsmasq") +api_headers = {"ContentType": "application/json"} + +print(environ) + +if action in ["add"]: + macaddr = argv[2] + ipaddr = argv[3] + api_data = dumps( + { + "action": action, + "macaddr": macaddr, + "ipaddr": ipaddr, + "hostname": environ.get("DNSMASQ_SUPPLIED_HOSTNAME"), + "client_id": environ.get("DNSMASQ_CLIENT_ID"), + "expiry": environ.get("DNSMASQ_LEASE_EXPIRES"), + "vendor_class": environ.get("DNSMASQ_VENDOR_CLASS"), + "user_class": environ.get("DNSMASQ_USER_CLASS0"), + } + ) + post(api_uri, headers=api_headers, data=api_data, verify=False) + +elif action in ["tftp"]: + size = argv[2] + destaddr = argv[3] + filepath = argv[4] + api_data = dumps( + {"action": action, "size": size, "destaddr": destaddr, "filepath": filepath} + ) + post(api_uri, headers=api_headers, data=api_data, verify=False) + +exit(0) diff --git a/bootstrap-daemon/pvcbootstrapd/flaskapi.py b/bootstrap-daemon/pvcbootstrapd/flaskapi.py new file mode 100755 index 0000000..c85cd1c --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/flaskapi.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 + +# pvcbootstrapd.py - PVC Cluster Auto-bootstrap +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import flask +import json + +from pvcbootstrapd.Daemon import config + +import pvcbootstrapd.lib.lib as lib + +from flask_restful import Resource, Api +from celery import Celery +from celery.utils.log import get_task_logger + + +logger = get_task_logger(__name__) + + +# Create Flask app and set config values +app = flask.Flask(__name__) +blueprint = flask.Blueprint("api", __name__, url_prefix="") +api = Api(blueprint) +app.register_blueprint(blueprint) + +app.config[ + "CELERY_BROKER_URL" +] = f"redis://{config['queue_address']}:{config['queue_port']}{config['queue_path']}" + +celery = Celery(app.name, broker=app.config["CELERY_BROKER_URL"]) +celery.conf.update(app.config) + + +# +# Celery functions +# +@celery.task(bind=True) +def dnsmasq_checkin(self, data): + lib.dnsmasq_checkin(config, data) + + +@celery.task(bind=True) +def host_checkin(self, data): + lib.host_checkin(config, data) + + +# +# API routes +# +class API_Root(Resource): + def get(self): + """ + Return basic details of the API + --- + tags: + - root + responses: + 200: + description: OK + schema: + type: object + id: Message + properties: + message: + type: string + description: A text message describing the result + example: "The foo was successfully maxed" + """ + return {"message": "pvcbootstrapd API"}, 200 + + +api.add_resource(API_Root, "/") + + +class API_Checkin(Resource): + def get(self): + """ + Return checkin details of the API + --- + tags: + - checkin + responses: + 200: + description: OK + schema: + type: object + id: Message + """ + return {"message": "pvcbootstrapd API Checkin interface"}, 200 + + +api.add_resource(API_Checkin, "/checkin") + + +class API_Checkin_DNSMasq(Resource): + def post(self): + """ + Register a checkin from the DNSMasq subsystem + --- + tags: + - checkin + consumes: + - application/json + parameters: + - in: body + name: dnsmasq_checkin_event + description: An event checkin from an external bootstrap tool component. + schema: + type: object + required: + - action + properties: + action: + type: string + description: The action of the event. + example: "add" + macaddr: + type: string + description: (add, old) The MAC address from a DHCP request. + example: "ff:ff:ff:ab:cd:ef" + ipaddr: + type: string + description: (add, old) The IP address from a DHCP request. + example: "10.199.199.10" + hostname: + type: string + description: (add, old) The client hostname from a DHCP request. + example: "pvc-installer-live" + client_id: + type: string + description: (add, old) The client ID from a DHCP request. + example: "01:ff:ff:ff:ab:cd:ef" + vendor_class: + type: string + description: (add, old) The DHCP vendor-class option from a DHCP request. + example: "CPQRIB3 (HP Proliant DL360 G6 iLO)" + user_class: + type: string + description: (add, old) The DHCP user-class option from a DHCP request. + example: None + responses: + 200: + description: OK + schema: + type: object + id: Message + """ + try: + data = json.loads(flask.request.data) + except Exception as e: + logger.warn(e) + data = {"action": None} + logger.info(f"Handling DNSMasq checkin for: {data}") + + task = dnsmasq_checkin.delay(data) + logger.debug(task) + return {"message": "received checkin from DNSMasq"}, 200 + + +api.add_resource(API_Checkin_DNSMasq, "/checkin/dnsmasq") + + +class API_Checkin_Host(Resource): + def post(self): + """ + Register a checkin from the Host subsystem + --- + tags: + - checkin + consumes: + - application/json + parameters: + - in: body + name: host_checkin_event + description: An event checkin from an external bootstrap tool component. + schema: + type: object + required: + - action + properties: + action: + type: string + description: The action of the event. + example: "begin" + hostname: + type: string + description: The system hostname. + example: "hv1.mydomain.tld" + host_macaddr: + type: string + description: The MAC address of the system provisioning interface. + example: "ff:ff:ff:ab:cd:ef" + host_ipaddr: + type: string + description: The IP address of the system provisioning interface. + example: "10.199.199.11" + bmc_macaddr: + type: string + description: The MAC address of the system BMC interface. + example: "ff:ff:ff:01:23:45" + bmc_ipaddr: + type: string + description: The IP addres of the system BMC interface. + example: "10.199.199.10" + responses: + 200: + description: OK + schema: + type: object + id: Message + """ + try: + data = json.loads(flask.request.data) + except Exception as e: + logger.warning(f"Invalid JSON data, setting action to None: {e}") + data = {"action": None} + logger.info(f"Handling Host checkin for: {data}") + + task = host_checkin.delay(data) + logger.debug(task) + return {"message": "received checkin from Host"}, 200 + + +api.add_resource(API_Checkin_Host, "/checkin/host") diff --git a/bootstrap-daemon/pvcbootstrapd/lib/__init__.py b/bootstrap-daemon/pvcbootstrapd/lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bootstrap-daemon/pvcbootstrapd/lib/ansible.py b/bootstrap-daemon/pvcbootstrapd/lib/ansible.py new file mode 100755 index 0000000..9c55142 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/ansible.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 + +# ansible.py - PVC Cluster Auto-bootstrap Ansible libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import pvcbootstrapd.lib.git as git + +import ansible_runner +import tempfile + +from time import sleep +from celery.utils.log import get_task_logger + + +logger = get_task_logger(__name__) + + +def run_bootstrap(config, cspec, cluster, nodes): + """ + Run an Ansible bootstrap against a cluster + """ + logger.debug(nodes) + + # Construct our temporary INI inventory string + logger.info("Constructing virtual Ansible inventory") + base_yaml = cspec["clusters"][cluster.name]["base_yaml"] + local_domain = base_yaml.get("local_domain") + inventory = [f"""[{cluster.name}]"""] + for node in nodes: + inventory.append( + f"""{node.name}.{local_domain} ansible_host={node.host_ipaddr}""" + ) + inventory = "\n".join(inventory) + logger.debug(inventory) + + # Waiting 30 seconds to ensure everything is booted an stabilized + logger.info("Waiting 60s before starting Ansible bootstrap.") + sleep(60) + + # Run the Ansible playbooks + with tempfile.TemporaryDirectory(prefix="pvc-ansible-bootstrap_") as pdir: + try: + r = ansible_runner.run( + private_data_dir=f"{pdir}", + inventory=inventory, + limit=f"{cluster.name}", + playbook=f"{config['ansible_path']}/pvc.yml", + extravars={ + "ansible_ssh_private_key_file": config["ansible_keyfile"], + "bootstrap": "yes", + }, + forks=len(nodes), + verbosity=2, + ) + logger.info("Final status:") + logger.info("{}: {}".format(r.status, r.rc)) + logger.info(r.stats) + if r.rc == 0: + git.commit_repository(config) + git.push_repository(config) + except Exception as e: + logger.warning(f"Error: {e}") diff --git a/bootstrap-daemon/pvcbootstrapd/lib/dataclasses.py b/bootstrap-daemon/pvcbootstrapd/lib/dataclasses.py new file mode 100755 index 0000000..85ea632 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/dataclasses.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 + +# dataclasses.py - PVC Cluster Auto-bootstrap dataclasses +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +from dataclasses import dataclass + + +@dataclass +class Cluster: + """ + An instance of a Cluster + """ + + id: int + name: str + state: str + + +@dataclass +class Node: + """ + An instance of a Node + """ + + id: int + cluster: str + state: str + name: str + nid: int + bmc_macaddr: str + bmc_iapddr: str + host_macaddr: str + host_ipaddr: str diff --git a/bootstrap-daemon/pvcbootstrapd/lib/db.py b/bootstrap-daemon/pvcbootstrapd/lib/db.py new file mode 100755 index 0000000..ca07f20 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/db.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 + +# db.py - PVC Cluster Auto-bootstrap database libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import os +import sqlite3 +import contextlib + +from pvcbootstrapd.lib.dataclasses import Cluster, Node + +from celery.utils.log import get_task_logger + + +logger = get_task_logger(__name__) + + +# +# Database functions +# +@contextlib.contextmanager +def dbconn(db_path): + conn = sqlite3.connect(db_path) + conn.execute("PRAGMA foreign_keys = 1") + cur = conn.cursor() + yield cur + conn.commit() + conn.close() + + +def init_database(config): + db_path = config["database_path"] + if not os.path.isfile(db_path): + print("First run: initializing database.") + # Initializing the database + with dbconn(db_path) as cur: + # Table listing all clusters + cur.execute( + """CREATE TABLE clusters + (id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT UNIQUE NOT NULL, + state TEXT NOT NULL)""" + ) + # Table listing all nodes + # FK: cluster -> clusters.id + cur.execute( + """CREATE TABLE nodes + (id INTEGER PRIMARY KEY AUTOINCREMENT, + cluster INTEGER NOT NULL, + state TEXT NOT NULL, + name TEXT UNIQUE NOT NULL, + nodeid INTEGER NOT NULL, + bmc_macaddr TEXT NOT NULL, + bmc_ipaddr TEXT NOT NULL, + host_macaddr TEXT NOT NULL, + host_ipaddr TEXT NOT NULL, + CONSTRAINT cluster_col FOREIGN KEY (cluster) REFERENCES clusters(id) ON DELETE CASCADE )""" + ) + + +# +# Cluster functions +# +def get_cluster(config, cid=None, name=None): + if cid is None and name is None: + return None + elif cid is not None: + findfield = "id" + datafield = cid + elif name is not None: + findfield = "name" + datafield = name + + with dbconn(config["database_path"]) as cur: + cur.execute(f"""SELECT * FROM clusters WHERE {findfield} = ?""", (datafield,)) + rows = cur.fetchall() + + if len(rows) > 0: + row = rows[0] + else: + return None + + return Cluster(row[0], row[1], row[2]) + + +def add_cluster(config, cspec, name, state): + with dbconn(config["database_path"]) as cur: + cur.execute( + """INSERT INTO clusters + (name, state) + VALUES + (?, ?)""", + (name, state), + ) + + logger.info(f"New cluster {name} added, populating bootstrap nodes from cspec") + for bmcmac in cspec["clusters"][name]["cspec_yaml"]["bootstrap"]: + hostname = cspec["clusters"][name]["cspec_yaml"]["bootstrap"][bmcmac]["node"][ + "hostname" + ] + add_node( + config, + name, + hostname, + int("".join(filter(str.isdigit, hostname))), + "init", + bmcmac, + "", + "", + "", + ) + logger.info(f"Added node {hostname}") + + return get_cluster(config, name=name) + + +def update_cluster_state(config, name, state): + with dbconn(config["database_path"]) as cur: + cur.execute( + """UPDATE clusters + SET state = ? + WHERE name = ?""", + (state, name), + ) + + return get_cluster(config, name=name) + + +# +# Node functions +# +def get_node(config, cluster_name, nid=None, name=None, bmc_macaddr=None): + cluster = get_cluster(config, name=cluster_name) + + if nid is None and name is None and bmc_macaddr is None: + return None + elif nid is not None: + findfield = "id" + datafield = nid + elif bmc_macaddr is not None: + findfield = "bmc_macaddr" + datafield = bmc_macaddr + elif name is not None: + findfield = "name" + datafield = name + + with dbconn(config["database_path"]) as cur: + cur.execute( + f"""SELECT * FROM nodes WHERE {findfield} = ? AND cluster = ?""", + (datafield, cluster.id), + ) + rows = cur.fetchall() + + if len(rows) > 0: + row = rows[0] + else: + return None + + return Node( + row[0], cluster.name, row[2], row[3], row[4], row[5], row[6], row[7], row[8] + ) + + +def get_nodes_in_cluster(config, cluster_name): + cluster = get_cluster(config, name=cluster_name) + + with dbconn(config["database_path"]) as cur: + cur.execute("""SELECT * FROM nodes WHERE cluster = ?""", (cluster.id,)) + rows = cur.fetchall() + + node_list = list() + for row in rows: + node_list.append( + Node( + row[0], + cluster.name, + row[2], + row[3], + row[4], + row[5], + row[6], + row[7], + row[8], + ) + ) + + return node_list + + +def add_node( + config, + cluster_name, + name, + nodeid, + state, + bmc_macaddr, + bmc_ipaddr, + host_macaddr, + host_ipaddr, +): + cluster = get_cluster(config, name=cluster_name) + + with dbconn(config["database_path"]) as cur: + cur.execute( + """INSERT INTO nodes + (cluster, state, name, nodeid, bmc_macaddr, bmc_ipaddr, host_macaddr, host_ipaddr) + VALUES + (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + cluster.id, + state, + name, + nodeid, + bmc_macaddr, + bmc_ipaddr, + host_macaddr, + host_ipaddr, + ), + ) + + return get_node(config, cluster_name, name=name) + + +def update_node_state(config, cluster_name, name, state): + cluster = get_cluster(config, name=cluster_name) + + with dbconn(config["database_path"]) as cur: + cur.execute( + """UPDATE nodes + SET state = ? + WHERE name = ? AND cluster = ?""", + (state, name, cluster.id), + ) + + return get_node(config, cluster_name, name=name) + + +def update_node_addresses( + config, cluster_name, name, bmc_macaddr, bmc_ipaddr, host_macaddr, host_ipaddr +): + cluster = get_cluster(config, name=cluster_name) + + with dbconn(config["database_path"]) as cur: + cur.execute( + """UPDATE nodes + SET bmc_macaddr = ?, bmc_ipaddr = ?, host_macaddr = ?, host_ipaddr = ? + WHERE name = ? AND cluster = ?""", + (bmc_macaddr, bmc_ipaddr, host_macaddr, host_ipaddr, name, cluster.id), + ) + + return get_node(config, cluster_name, name=name) diff --git a/bootstrap-daemon/pvcbootstrapd/lib/dnsmasq.py b/bootstrap-daemon/pvcbootstrapd/lib/dnsmasq.py new file mode 100755 index 0000000..92e59d8 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/dnsmasq.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 + +# dnsmasq.py - PVC Cluster Auto-bootstrap DNSMasq instance +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import os +import subprocess +import signal + +from threading import Thread + + +class DNSMasq: + """ + Implementes a daemonized instance of DNSMasq for providing DHCP and TFTP services + + The DNSMasq instance listens on the configured 'dhcp_address', and instead of a "real" + leases database forwards requests to the 'dnsmasq-lease.py' script. This script will + then hit the pvcbootstrapd '/checkin' API endpoint to perform actions. + + TFTP is provided to automate the bootstrap of a node, providing the pvc-installer + over TFTP as well as a seed configuration which is created by the API. + """ + + def __init__(self, config): + self.environment = { + "API_URI": f"http://{config['api_address']}:{config['api_port']}/checkin/dnsmasq" + } + self.dnsmasq_cmd = [ + "/usr/sbin/dnsmasq", + "--bogus-priv", + "--no-hosts", + "--dhcp-authoritative", + "--filterwin2k", + "--expand-hosts", + "--domain-needed", + f"--domain={config['dhcp_domain']}", + f"--local=/{config['dhcp_domain']}/", + "--log-facility=-", + "--log-dhcp", + "--keep-in-foreground", + f"--dhcp-script={os.getcwd()}/pvcbootstrapd/dnsmasq-lease.py", + "--bind-interfaces", + f"--listen-address={config['dhcp_address']}", + f"--dhcp-option=3,{config['dhcp_gateway']}", + f"--dhcp-range={config['dhcp_lease_start']},{config['dhcp_lease_end']},{config['dhcp_lease_time']}", + "--enable-tftp", + f"--tftp-root={config['tftp_root_path']}/", + # This block of dhcp-match, tag-if, and dhcp-boot statements sets the following TFTP setup: + # If the machine sends client-arch 0, and is not tagged iPXE, load undionly.kpxe (chainload) + # If the machine sends client-arch 7 or 9, and is not tagged iPXE, load ipxe.efi (chainload) + # If the machine sends the iPXE option, load boot.ipxe (iPXE boot configuration) + "--dhcp-match=set:o_bios,option:client-arch,0", + "--dhcp-match=set:o_uefi,option:client-arch,7", + "--dhcp-match=set:o_uefi,option:client-arch,9", + "--dhcp-match=set:ipxe,175", + "--tag-if=set:bios,tag:!ipxe,tag:o_bios", + "--tag-if=set:uefi,tag:!ipxe,tag:o_uefi", + "--dhcp-boot=tag:bios,undionly.kpxe", + "--dhcp-boot=tag:uefi,ipxe.efi", + "--dhcp-boot=tag:ipxe,boot.ipxe", + ] + if config["debug"]: + self.dnsmasq_cmd.append("--leasefile-ro") + + print(self.dnsmasq_cmd) + self.stdout = subprocess.PIPE + + def execute(self): + self.proc = subprocess.Popen( + self.dnsmasq_cmd, + env=self.environment, + ) + + def start(self): + self.thread = Thread(target=self.execute, args=()) + self.thread.start() + + def stop(self): + self.proc.send_signal(signal.SIGTERM) + + def reload(self): + self.proc.send_signal(signal.SIGHUP) diff --git a/bootstrap-daemon/pvcbootstrapd/lib/git.py b/bootstrap-daemon/pvcbootstrapd/lib/git.py new file mode 100755 index 0000000..bc39096 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/git.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 + +# git.py - PVC Cluster Auto-bootstrap Git repository libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import os.path +import git +import yaml + +from celery.utils.log import get_task_logger + + +logger = get_task_logger(__name__) + + +def init_repository(config): + """ + Clone the Ansible git repository + """ + try: + git_ssh_cmd = f"ssh -i {config['ansible_keyfile']} -o StrictHostKeyChecking=no" + if not os.path.exists(config["ansible_path"]): + print( + f"First run: cloning repository {config['ansible_remote']} branch {config['ansible_branch']} to {config['ansible_path']}" + ) + git.Repo.clone_from( + config["ansible_remote"], + config["ansible_path"], + branch=config["ansible_branch"], + env=dict(GIT_SSH_COMMAND=git_ssh_cmd), + ) + + g = git.cmd.Git(f"{config['ansible_path']}") + g.checkout(config["ansible_branch"]) + g.submodule("update", "--init", env=dict(GIT_SSH_COMMAND=git_ssh_cmd)) + except Exception as e: + print(f"Error: {e}") + + +def pull_repository(config): + """ + Pull (with rebase) the Ansible git repository + """ + logger.info(f"Updating local configuration repository {config['ansible_path']}") + try: + git_ssh_cmd = f"ssh -i {config['ansible_keyfile']} -o StrictHostKeyChecking=no" + g = git.cmd.Git(f"{config['ansible_path']}") + g.pull(rebase=True, env=dict(GIT_SSH_COMMAND=git_ssh_cmd)) + g.submodule("update", "--init", env=dict(GIT_SSH_COMMAND=git_ssh_cmd)) + except Exception as e: + logger.warn(e) + + +def commit_repository(config): + """ + Commit uncommitted changes to the Ansible git repository + """ + logger.info( + f"Committing changes to local configuration repository {config['ansible_path']}" + ) + + try: + g = git.cmd.Git(f"{config['ansible_path']}") + g.add("--all") + commit_env = { + "GIT_COMMITTER_NAME": "PVC Bootstrap", + "GIT_COMMITTER_EMAIL": "git@pvcbootstrapd", + } + g.commit( + "-m", + "Automated commit from PVC Bootstrap Ansible subsystem", + author="PVC Bootstrap ", + env=commit_env, + ) + except Exception as e: + logger.warn(e) + + +def push_repository(config): + """ + Push changes to the default remote + """ + logger.info( + f"Pushing changes from local configuration repository {config['ansible_path']}" + ) + + try: + git_ssh_cmd = f"ssh -i {config['ansible_keyfile']} -o StrictHostKeyChecking=no" + g = git.Repo(f"{config['ansible_path']}") + origin = g.remote(name="origin") + origin.push(env=dict(GIT_SSH_COMMAND=git_ssh_cmd)) + except Exception as e: + logger.warn(e) + + +def load_cspec_yaml(config): + """ + Load the bootstrap group_vars for all known clusters + """ + # Pull down the repository + pull_repository(config) + + # Load our clusters file and read the clusters from it + clusters_file = f"{config['ansible_path']}/{config['ansible_clusters_file']}" + logger.info(f"Loading cluster configuration from file '{clusters_file}'") + with open(clusters_file, "r") as clustersfh: + clusters = yaml.load(clustersfh, Loader=yaml.SafeLoader).get("clusters", list()) + + # Define a base cpec + cspec = { + "bootstrap": dict(), + "hooks": dict(), + "clusters": dict(), + } + + # Read each cluster's cspec and update the base cspec + logger.info("Loading per-cluster specifications") + for cluster in clusters: + cspec["clusters"][cluster] = dict() + cspec["clusters"][cluster]["bootstrap_nodes"] = list() + + cspec_file = f"{config['ansible_path']}/group_vars/{cluster}/{config['ansible_cspec_files_bootstrap']}" + if os.path.exists(cspec_file): + with open(cspec_file, "r") as cpsecfh: + try: + cspec_yaml = yaml.load(cpsecfh, Loader=yaml.SafeLoader) + except Exception as e: + logger.warn( + f"Failed to load {config['ansible_cspec_files_bootstrap']} for cluster {cluster}: {e}" + ) + continue + + cspec["clusters"][cluster]["cspec_yaml"] = cspec_yaml + + # Convert the MAC address keys to lowercase + # DNSMasq operates with lowercase keys, but often these are written with uppercase. + # Convert them to lowercase to prevent discrepancies later on. + cspec_yaml["bootstrap"] = { + k.lower(): v for k, v in cspec_yaml["bootstrap"].items() + } + + # Load in the YAML for the cluster + base_yaml = load_base_yaml(config, cluster) + cspec["clusters"][cluster]["base_yaml"] = base_yaml + pvc_yaml = load_pvc_yaml(config, cluster) + cspec["clusters"][cluster]["pvc_yaml"] = pvc_yaml + + # Set per-node values from elsewhere + for node in cspec_yaml["bootstrap"]: + cspec["clusters"][cluster]["bootstrap_nodes"].append( + cspec_yaml["bootstrap"][node]["node"]["hostname"] + ) + + # Set the cluster value automatically + cspec_yaml["bootstrap"][node]["node"]["cluster"] = cluster + + # Set the domain value automatically via base config + cspec_yaml["bootstrap"][node]["node"]["domain"] = base_yaml[ + "local_domain" + ] + + # Set the node FQDN value automatically + cspec_yaml["bootstrap"][node]["node"][ + "fqdn" + ] = f"{cspec_yaml['bootstrap'][node]['node']['hostname']}.{cspec_yaml['bootstrap'][node]['node']['domain']}" + + # Append bootstrap entries to the main dictionary + cspec["bootstrap"] = {**cspec["bootstrap"], **cspec_yaml["bootstrap"]} + + # Append hooks to the main dictionary (per-cluster) + if cspec_yaml.get("hooks"): + cspec["hooks"][cluster] = cspec_yaml["hooks"] + + logger.info("Finished loading per-cluster specifications") + return cspec + + +def load_base_yaml(config, cluster): + """ + Load the base.yml group_vars for a cluster + """ + base_file = f"{config['ansible_path']}/group_vars/{cluster}/{config['ansible_cspec_files_base']}" + with open(base_file, "r") as varsfile: + base_yaml = yaml.load(varsfile, Loader=yaml.SafeLoader) + + return base_yaml + + +def load_pvc_yaml(config, cluster): + """ + Load the pvc.yml group_vars for a cluster + """ + pvc_file = f"{config['ansible_path']}/group_vars/{cluster}/{config['ansible_cspec_files_pvc']}" + with open(pvc_file, "r") as varsfile: + pvc_yaml = yaml.load(varsfile, Loader=yaml.SafeLoader) + + return pvc_yaml diff --git a/bootstrap-daemon/pvcbootstrapd/lib/hooks.py b/bootstrap-daemon/pvcbootstrapd/lib/hooks.py new file mode 100755 index 0000000..16804bf --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/hooks.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 + +# hooks.py - PVC Cluster Auto-bootstrap Hook libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import pvcbootstrapd.lib.db as db + +import json +import tempfile +import paramiko +import contextlib +import requests + +from re import match +from time import sleep +from celery.utils.log import get_task_logger + + +logger = get_task_logger(__name__) + + +@contextlib.contextmanager +def run_paramiko(config, node_address): + ssh_client = paramiko.SSHClient() + ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh_client.connect( + hostname=node_address, + username=config["deploy_username"], + key_filename=config["ansible_keyfile"], + ) + yield ssh_client + ssh_client.close() + + +def run_hook_osddb(config, targets, args): + """ + Add an OSD DB defined by args['disk'] + """ + for node in targets: + node_name = node.name + node_address = node.host_ipaddr + + device = args["disk"] + + logger.info(f"Creating OSD DB on node {node_name} device {device}") + + # Using a direct command on the target here is somewhat messy, but avoids many + # complexities of determining a valid API listen address, etc. + pvc_cmd_string = f"pvc storage osd create-db-vg --yes {node_name} {device}" + + with run_paramiko(config, node_address) as c: + stdin, stdout, stderr = c.exec_command(pvc_cmd_string) + logger.debug(stdout.readlines()) + logger.debug(stderr.readlines()) + + +def run_hook_osd(config, targets, args): + """ + Add an OSD defined by args['disk'] with weight args['weight'] + """ + for node in targets: + node_name = node.name + node_address = node.host_ipaddr + + device = args["disk"] + weight = args.get("weight", 1) + ext_db_flag = args.get("ext_db", False) + ext_db_ratio = args.get("ext_db_ratio", 0.05) + + logger.info(f"Creating OSD on node {node_name} device {device} weight {weight}") + + # Using a direct command on the target here is somewhat messy, but avoids many + # complexities of determining a valid API listen address, etc. + pvc_cmd_string = ( + f"pvc storage osd add --yes {node_name} {device} --weight {weight}" + ) + if ext_db_flag: + pvc_cmd_string = f"{pvc_cmd_string} --ext-db --ext-db-ratio {ext_db_ratio}" + + with run_paramiko(config, node_address) as c: + stdin, stdout, stderr = c.exec_command(pvc_cmd_string) + logger.debug(stdout.readlines()) + logger.debug(stderr.readlines()) + + +def run_hook_pool(config, targets, args): + """ + Add an pool defined by args['name'] on device tier args['tier'] + """ + for node in targets: + node_name = node.name + node_address = node.host_ipaddr + + name = args["name"] + pgs = args.get("pgs", "64") + tier = args.get("tier", "default") # Does nothing yet + + logger.info( + f"Creating storage pool on node {node_name} name {name} pgs {pgs} tier {tier}" + ) + + # Using a direct command on the target here is somewhat messy, but avoids many + # complexities of determining a valid API listen address, etc. + pvc_cmd_string = f"pvc storage pool add {name} {pgs}" + + with run_paramiko(config, node_address) as c: + stdin, stdout, stderr = c.exec_command(pvc_cmd_string) + logger.debug(stdout.readlines()) + logger.debug(stderr.readlines()) + + # This only runs once on whatever the first node is + break + + +def run_hook_network(config, targets, args): + """ + Add an network defined by args (many) + """ + for node in targets: + node_name = node.name + node_address = node.host_ipaddr + + vni = args["vni"] + description = args["description"] + nettype = args["type"] + mtu = args.get("mtu", None) + + pvc_cmd_string = ( + f"pvc network add {vni} --description {description} --type {nettype}" + ) + + if mtu is not None and mtu not in ["auto", "default"]: + pvc_cmd_string = f"{pvc_cmd_string} --mtu {mtu}" + + if nettype == "managed": + domain = args["domain"] + pvc_cmd_string = f"{pvc_cmd_string} --domain {domain}" + + dns_servers = args.get("dns_servers", []) + for dns_server in dns_servers: + pvc_cmd_string = f"{pvc_cmd_string} --dns-server {dns_server}" + + is_ip4 = args["ip4"] + if is_ip4: + ip4_network = args["ip4_network"] + pvc_cmd_string = f"{pvc_cmd_string} --ipnet {ip4_network}" + + ip4_gateway = args["ip4_gateway"] + pvc_cmd_string = f"{pvc_cmd_string} --gateway {ip4_gateway}" + + ip4_dhcp = args["ip4_dhcp"] + if ip4_dhcp: + pvc_cmd_string = f"{pvc_cmd_string} --dhcp" + ip4_dhcp_start = args["ip4_dhcp_start"] + ip4_dhcp_end = args["ip4_dhcp_end"] + pvc_cmd_string = f"{pvc_cmd_string} --dhcp-start {ip4_dhcp_start} --dhcp-end {ip4_dhcp_end}" + else: + pvc_cmd_string = f"{pvc_cmd_string} --no-dhcp" + + is_ip6 = args["ip6"] + if is_ip6: + ip6_network = args["ip6_network"] + pvc_cmd_string = f"{pvc_cmd_string} --ipnet6 {ip6_network}" + + ip6_gateway = args["ip6_gateway"] + pvc_cmd_string = f"{pvc_cmd_string} --gateway6 {ip6_gateway}" + + logger.info(f"Creating network on node {node_name} VNI {vni} type {nettype}") + + with run_paramiko(config, node_address) as c: + stdin, stdout, stderr = c.exec_command(pvc_cmd_string) + logger.debug(stdout.readlines()) + logger.debug(stderr.readlines()) + + # This only runs once on whatever the first node is + break + + +def run_hook_script(config, targets, args): + """ + Run a script on the targets + """ + for node in targets: + node_name = node.name + node_address = node.host_ipaddr + + script = args.get("script", None) + source = args.get("source", None) + path = args.get("path", None) + + logger.info(f"Running script on node {node_name}") + + with run_paramiko(config, node_address) as c: + if script is not None: + remote_path = "/tmp/pvcbootstrapd.hook" + with tempfile.NamedTemporaryFile(mode="w") as tf: + tf.write(script) + tf.seek(0) + + # Send the file to the remote system + tc = c.open_sftp() + tc.put(tf.name, remote_path) + tc.chmod(remote_path, 0o755) + tc.close() + elif source == "local": + if not match(r"^/", path): + path = config["ansible_path"] + "/" + path + + remote_path = "/tmp/pvcbootstrapd.hook" + if path is None: + continue + + tc = c.open_sftp() + tc.put(path, remote_path) + tc.chmod(remote_path, 0o755) + tc.close() + elif source == "remote": + remote_path = path + + stdin, stdout, stderr = c.exec_command(remote_path) + logger.debug(stdout.readlines()) + logger.debug(stderr.readlines()) + + +def run_hook_webhook(config, targets, args): + """ + Send an HTTP requests (no targets) + """ + logger.info(f"Running webhook against {args['uri']}") + + # Get the body data + data = json.dumps(args["body"]) + headers = {"content-type": "application/json"} + + # Craft up a Requests endpoint set for this + requests_actions = { + "get": requests.get, + "post": requests.post, + "put": requests.put, + "patch": requests.patch, + "delete": requests.delete, + "options": requests.options, + } + action = args["action"] + + result = requests_actions[action](args["uri"], headers=headers, data=data) + + logger.info(f"Result: {result}") + + +hook_functions = { + "osddb": run_hook_osddb, + "osd": run_hook_osd, + "pool": run_hook_pool, + "network": run_hook_network, + "script": run_hook_script, + "webhook": run_hook_webhook, +} + + +def run_hooks(config, cspec, cluster, nodes): + """ + Run an Ansible bootstrap against a cluster + """ + # Waiting 30 seconds to ensure everything is booted an stabilized + logger.info("Waiting 300s before starting hook run.") + sleep(300) + + cluster_hooks = cspec["hooks"][cluster.name] + + cluster_nodes = db.get_nodes_in_cluster(config, cluster.name) + + for hook in cluster_hooks: + hook_target = hook.get("target", "all") + hook_name = hook.get("name") + logger.info(f"Running hook on {hook_target}: {hook_name}") + + if "all" in hook_target: + target_nodes = cluster_nodes + else: + target_nodes = [node for node in cluster_nodes if node.name in hook_target] + + hook_type = hook.get("type") + hook_args = hook.get("args") + + if hook_type is None or hook_args is None: + logger.warning("Invalid hook: missing required configuration") + continue + + # Run the hook function + try: + hook_functions[hook_type](config, target_nodes, hook_args) + except Exception as e: + logger.warning(f"Error running hook: {e}") + + # Wait 5s between hooks + sleep(5) + + # Restart nodes to complete setup + hook_functions['script'](config, cluster_nodes, {'script': '#!/usr/bin/env bash\necho bootstrapped | sudo tee /etc/pvc-install.hooks\nsudo reboot'}) diff --git a/bootstrap-daemon/pvcbootstrapd/lib/host.py b/bootstrap-daemon/pvcbootstrapd/lib/host.py new file mode 100755 index 0000000..4bdc963 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/host.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 + +# host.py - PVC Cluster Auto-bootstrap host libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +from celery.utils.log import get_task_logger + +import pvcbootstrapd.lib.db as db + + +logger = get_task_logger(__name__) + + +def installer_init(config, cspec, data): + bmc_macaddr = data["bmc_macaddr"] + bmc_ipaddr = data["bmc_ipaddr"] + host_macaddr = data["host_macaddr"] + host_ipaddr = data["host_ipaddr"] + cspec_cluster = cspec["bootstrap"][bmc_macaddr]["node"]["cluster"] + cspec_hostname = cspec["bootstrap"][bmc_macaddr]["node"]["hostname"] + + cluster = db.get_cluster(config, name=cspec_cluster) + if cluster is None: + cluster = db.add_cluster(config, cspec, cspec_cluster, "provisioning") + logger.debug(cluster) + + db.update_node_addresses( + config, + cspec_cluster, + cspec_hostname, + bmc_macaddr, + bmc_ipaddr, + host_macaddr, + host_ipaddr, + ) + db.update_node_state(config, cspec_cluster, cspec_hostname, "installing") + node = db.get_node(config, cspec_cluster, name=cspec_hostname) + logger.debug(node) + + +def installer_complete(config, cspec, data): + bmc_macaddr = data["bmc_macaddr"] + cspec_hostname = cspec["bootstrap"][bmc_macaddr]["node"]["hostname"] + cspec_cluster = cspec["bootstrap"][bmc_macaddr]["node"]["cluster"] + + db.update_node_state(config, cspec_cluster, cspec_hostname, "installed") + node = db.get_node(config, cspec_cluster, name=cspec_hostname) + logger.debug(node) + + +def set_boot_state(config, cspec, data, state): + bmc_macaddr = data["bmc_macaddr"] + bmc_ipaddr = data["bmc_ipaddr"] + host_macaddr = data["host_macaddr"] + host_ipaddr = data["host_ipaddr"] + cspec_cluster = cspec["bootstrap"][bmc_macaddr]["node"]["cluster"] + cspec_hostname = cspec["bootstrap"][bmc_macaddr]["node"]["hostname"] + + db.update_node_addresses( + config, + cspec_cluster, + cspec_hostname, + bmc_macaddr, + bmc_ipaddr, + host_macaddr, + host_ipaddr, + ) + db.update_node_state(config, cspec_cluster, cspec_hostname, state) + node = db.get_node(config, cspec_cluster, name=cspec_hostname) + logger.debug(node) diff --git a/bootstrap-daemon/pvcbootstrapd/lib/installer.py b/bootstrap-daemon/pvcbootstrapd/lib/installer.py new file mode 100755 index 0000000..4b46cee --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/installer.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 + +# lib.py - PVC Cluster Auto-bootstrap libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +from jinja2 import Template + + +# +# Worker Functions - PXE/Installer Per-host Templates +# +def add_pxe(config, cspec_node, host_macaddr): + # Generate a per-client iPXE configuration for this host + destination_filename = ( + f"{config['tftp_host_path']}/mac-{host_macaddr.replace(':', '')}.ipxe" + ) + template_filename = f"{config['tftp_root_path']}/host-ipxe.j2" + + with open(template_filename, "r") as tfh: + template = Template(tfh.read()) + + imgargs_host_list = cspec_node.get("config", {}).get("kernel_options") + if imgargs_host_list is not None: + imgargs_host = " ".join(imgargs_host_list) + else: + imgargs_host = None + + rendered = template.render(imgargs_host=imgargs_host) + + with open(destination_filename, "w") as dfh: + dfh.write(rendered) + dfh.write("\n") + + +def add_preseed(config, cspec_node, host_macaddr, system_drive_target): + # Generate a per-client Installer configuration for this host + destination_filename = ( + f"{config['tftp_host_path']}/mac-{host_macaddr.replace(':', '')}.preseed" + ) + template_filename = f"{config['tftp_root_path']}/host-preseed.j2" + + with open(template_filename, "r") as tfh: + template = Template(tfh.read()) + + add_packages_list = cspec_node.get("config", {}).get("packages") + if add_packages_list is not None: + add_packages = ",".join(add_packages_list) + else: + add_packages = None + + # We use the dhcp_address here to allow the listen_address to be 0.0.0.0 + rendered = template.render( + debrelease=cspec_node.get("config", {}).get("release"), + debmirror=cspec_node.get("config", {}).get("mirror"), + addpkglist=add_packages, + filesystem=cspec_node.get("config", {}).get("filesystem"), + skip_blockcheck=False, + fqdn=cspec_node["node"]["fqdn"], + target_disk=system_drive_target, + pvcbootstrapd_checkin_uri=f"http://{config['dhcp_address']}:{config['api_port']}/checkin/host", + ) + + with open(destination_filename, "w") as dfh: + dfh.write(rendered) + dfh.write("\n") diff --git a/bootstrap-daemon/pvcbootstrapd/lib/lib.py b/bootstrap-daemon/pvcbootstrapd/lib/lib.py new file mode 100755 index 0000000..a87e39b --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/lib.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 + +# lib.py - PVC Cluster Auto-bootstrap libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import pvcbootstrapd.lib.db as db +import pvcbootstrapd.lib.git as git +import pvcbootstrapd.lib.redfish as redfish +import pvcbootstrapd.lib.host as host +import pvcbootstrapd.lib.ansible as ansible +import pvcbootstrapd.lib.hooks as hooks + +from time import sleep +from celery.utils.log import get_task_logger + + +logger = get_task_logger(__name__) + + +# +# Worker Functions - Checkins (Celery root tasks) +# +def dnsmasq_checkin(config, data): + """ + Handle checkins from DNSMasq + """ + logger.debug(f"data = {data}") + + # This is an add event; what we do depends on some stuff + if data["action"] in ["add"]: + logger.info( + f"Receiving 'add' checkin from DNSMasq for MAC address '{data['macaddr']}'" + ) + cspec = git.load_cspec_yaml(config) + is_in_bootstrap_map = True if data["macaddr"] in cspec["bootstrap"] else False + if is_in_bootstrap_map: + if ( + cspec["bootstrap"][data["macaddr"]]["bmc"].get("redfish", None) + is not None + ): + if cspec["bootstrap"][data["macaddr"]]["bmc"]["redfish"]: + is_redfish = True + else: + is_redfish = False + else: + is_redfish = redfish.check_redfish(config, data) + + logger.info(f"Is device '{data['macaddr']}' Redfish capable? {is_redfish}") + if is_redfish: + redfish.redfish_init(config, cspec, data) + else: + logger.warn(f"Device '{data['macaddr']}' not in bootstrap map; ignoring.") + + return + + # This is a tftp event; a node installer has booted + if data["action"] in ["tftp"]: + logger.info( + f"Receiving 'tftp' checkin from DNSMasq for IP address '{data['destaddr']}'" + ) + return + + +def host_checkin(config, data): + """ + Handle checkins from the PVC node + """ + logger.info(f"Registering checkin for host {data['hostname']}") + logger.debug(f"data = {data}") + cspec = git.load_cspec_yaml(config) + bmc_macaddr = data["bmc_macaddr"] + cspec_cluster = cspec["bootstrap"][bmc_macaddr]["node"]["cluster"] + + if data["action"] in ["install-start"]: + # Node install has started + logger.info(f"Registering install start for host {data['hostname']}") + host.installer_init(config, cspec, data) + + elif data["action"] in ["install-complete"]: + # Node install has finished + logger.info(f"Registering install complete for host {data['hostname']}") + host.installer_complete(config, cspec, data) + + elif data["action"] in ["system-boot_initial"]: + # Node has booted for the first time and can begin Ansible runs once all nodes up + logger.info(f"Registering first boot for host {data['hostname']}") + target_state = "booted-initial" + + host.set_boot_state(config, cspec, data, target_state) + sleep(1) + + all_nodes = db.get_nodes_in_cluster(config, cspec_cluster) + ready_nodes = [node for node in all_nodes if node.state == target_state] + + # Continue once all nodes are in the booted-initial state + logger.info(f"Ready: {len(ready_nodes)} All: {len(all_nodes)}") + if len(ready_nodes) >= len(all_nodes): + cluster = db.update_cluster_state(config, cspec_cluster, "ansible-running") + + ansible.run_bootstrap(config, cspec, cluster, ready_nodes) + + elif data["action"] in ["system-boot_configured"]: + # Node has been booted after Ansible run and can begin hook runs + logger.info(f"Registering post-Ansible boot for host {data['hostname']}") + target_state = "booted-configured" + + host.set_boot_state(config, cspec, data, target_state) + sleep(1) + + all_nodes = db.get_nodes_in_cluster(config, cspec_cluster) + ready_nodes = [node for node in all_nodes if node.state == target_state] + + # Continue once all nodes are in the booted-configured state + logger.info(f"Ready: {len(ready_nodes)} All: {len(all_nodes)}") + if len(ready_nodes) >= len(all_nodes): + cluster = db.update_cluster_state(config, cspec_cluster, "hooks-running") + + hooks.run_hooks(config, cspec, cluster, ready_nodes) + + elif data["action"] in ["system-boot_completed"]: + # Node has been fully configured and can be shut down for the final time + logger.info(f"Registering post-hooks boot for host {data['hostname']}") + target_state = "booted-completed" + + host.set_boot_state(config, cspec, data, target_state) + sleep(1) + + all_nodes = db.get_nodes_in_cluster(config, cspec_cluster) + ready_nodes = [node for node in all_nodes if node.state == target_state] + + logger.info(f"Ready: {len(ready_nodes)} All: {len(all_nodes)}") + if len(ready_nodes) >= len(all_nodes): + cluster = db.update_cluster_state(config, cspec_cluster, "completed") + + # Hosts will now power down ready for real activation in production diff --git a/bootstrap-daemon/pvcbootstrapd/lib/redfish.py b/bootstrap-daemon/pvcbootstrapd/lib/redfish.py new file mode 100755 index 0000000..7921e64 --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/redfish.py @@ -0,0 +1,835 @@ +#!/usr/bin/env python3 + +# redfish.py - PVC Cluster Auto-bootstrap Redfish libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +# Refs: +# https://downloads.dell.com/manuals/all-products/esuprt_software/esuprt_it_ops_datcentr_mgmt/dell-management-solution-resources_white-papers11_en-us.pdf +# https://downloads.dell.com/solutions/dell-management-solution-resources/RESTfulSerConfig-using-iDRAC-REST%20API%28DTC%20copy%29.pdf + +import requests +import urllib3 +import json +import re +import math +from time import sleep +from celery.utils.log import get_task_logger + +import pvcbootstrapd.lib.installer as installer +import pvcbootstrapd.lib.db as db + + +logger = get_task_logger(__name__) + + +# +# Helper Classes +# +class AuthenticationException(Exception): + def __init__(self, error=None, response=None): + if error is not None: + self.short_message = error + else: + self.short_message = "Generic authentication failure" + + if response is not None: + rinfo = response.json()["error"]["@Message.ExtendedInfo"][0] + if rinfo.get("Message") is not None: + self.full_message = rinfo["Message"] + self.res_message = rinfo["Resolution"] + self.severity = rinfo["Severity"] + self.message_id = rinfo["MessageId"] + else: + self.full_message = "" + self.res_message = "" + self.severity = "Fatal" + self.message_id = rinfo["MessageId"] + self.status_code = response.status_code + else: + self.status_code = None + + def __str__(self): + if self.status_code is not None: + message = f"{self.short_message}: {self.full_message} {self.res_message} (HTTP Code: {self.status_code}, Severity: {self.severity}, ID: {self.message_id})" + else: + message = f"{self.short_message}" + return str(message) + + +class RedfishSession: + def __init__(self, host, username, password): + # Disable urllib3 warnings + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + # Perform login + login_payload = {"UserName": username, "Password": password} + login_uri = f"{host}/redfish/v1/Sessions" + login_headers = {"content-type": "application/json"} + + self.host = None + login_response = None + + tries = 1 + max_tries = 25 + while tries < max_tries: + logger.info(f"Trying to log in to Redfish ({tries}/{max_tries - 1})...") + try: + login_response = requests.post( + login_uri, + data=json.dumps(login_payload), + headers=login_headers, + verify=False, + timeout=5, + ) + break + except Exception: + sleep(2) + tries += 1 + + if login_response is None: + logger.error("Failed to log in to Redfish") + return + + if login_response.status_code not in [200, 201]: + raise AuthenticationException("Login failed", response=login_response) + logger.info(f"Logged in to Redfish at {host} successfully") + + self.host = host + self.token = login_response.headers.get("X-Auth-Token") + self.headers = {"content-type": "application/json", "x-auth-token": self.token} + + logout_uri = login_response.headers.get("Location") + if re.match(r"^/", logout_uri): + self.logout_uri = f"{host}{logout_uri}" + else: + self.logout_uri = logout_uri + + def __del__(self): + if self.host is None: + return + + logout_headers = { + "Content-Type": "application/json", + "X-Auth-Token": self.token, + } + + logout_response = requests.delete( + self.logout_uri, headers=logout_headers, verify=False, timeout=15 + ) + + if logout_response.status_code not in [200, 201]: + raise AuthenticationException("Logout failed", response=logout_response) + logger.info(f"Logged out of Redfish at {self.host} successfully") + + def get(self, uri): + url = f"{self.host}{uri}" + + response = requests.get(url, headers=self.headers, verify=False) + + if response.status_code in [200, 201]: + return response.json() + else: + rinfo = response.json()["error"]["@Message.ExtendedInfo"][0] + if rinfo.get("Message") is not None: + message = f"{rinfo['Message']} {rinfo['Resolution']}" + severity = rinfo["Severity"] + message_id = rinfo["MessageId"] + else: + message = rinfo + severity = "Error" + message_id = "N/A" + logger.warn(f"! Error: GET request to {url} failed") + logger.warn( + f"! HTTP Code: {response.status_code} Severity: {severity} ID: {message_id}" + ) + logger.warn(f"! Details: {message}") + return None + + def delete(self, uri): + url = f"{self.host}{uri}" + + response = requests.delete(url, headers=self.headers, verify=False) + + if response.status_code in [200, 201]: + return response.json() + else: + rinfo = response.json()["error"]["@Message.ExtendedInfo"][0] + if rinfo.get("Message") is not None: + message = f"{rinfo['Message']} {rinfo['Resolution']}" + severity = rinfo["Severity"] + message_id = rinfo["MessageId"] + else: + message = rinfo + severity = "Error" + message_id = "N/A" + + logger.warn(f"! Error: DELETE request to {url} failed") + logger.warn( + f"! HTTP Code: {response.status_code} Severity: {severity} ID: {message_id}" + ) + logger.warn(f"! Details: {message}") + return None + + def post(self, uri, data): + url = f"{self.host}{uri}" + payload = json.dumps(data) + + response = requests.post(url, data=payload, headers=self.headers, verify=False) + + if response.status_code in [200, 201]: + return response.json() + else: + rinfo = response.json()["error"]["@Message.ExtendedInfo"][0] + if rinfo.get("Message") is not None: + message = f"{rinfo['Message']} {rinfo['Resolution']}" + severity = rinfo["Severity"] + message_id = rinfo["MessageId"] + else: + message = rinfo + severity = "Error" + message_id = "N/A" + + logger.warn(f"! Error: POST request to {url} failed") + logger.warn( + f"! HTTP Code: {response.status_code} Severity: {severity} ID: {message_id}" + ) + logger.warn(f"! Details: {message}") + return None + + def put(self, uri, data): + url = f"{self.host}{uri}" + payload = json.dumps(data) + + response = requests.put(url, data=payload, headers=self.headers, verify=False) + + if response.status_code in [200, 201]: + return response.json() + else: + rinfo = response.json()["error"]["@Message.ExtendedInfo"][0] + if rinfo.get("Message") is not None: + message = f"{rinfo['Message']} {rinfo['Resolution']}" + severity = rinfo["Severity"] + message_id = rinfo["MessageId"] + else: + message = rinfo + severity = "Error" + message_id = "N/A" + + logger.warn(f"! Error: PUT request to {url} failed") + logger.warn( + f"! HTTP Code: {response.status_code} Severity: {severity} ID: {message_id}" + ) + logger.warn(f"! Details: {message}") + return None + + def patch(self, uri, data): + url = f"{self.host}{uri}" + payload = json.dumps(data) + + response = requests.patch(url, data=payload, headers=self.headers, verify=False) + + if response.status_code in [200, 201]: + return response.json() + else: + rinfo = response.json()["error"]["@Message.ExtendedInfo"][0] + if rinfo.get("Message") is not None: + message = f"{rinfo['Message']} {rinfo['Resolution']}" + severity = rinfo["Severity"] + message_id = rinfo["MessageId"] + else: + message = rinfo + severity = "Error" + message_id = "N/A" + + logger.warn(f"! Error: PATCH request to {url} failed") + logger.warn( + f"! HTTP Code: {response.status_code} Severity: {severity} ID: {message_id}" + ) + logger.warn(f"! Details: {message}") + return None + + +# +# Helper functions +# +def format_bytes_tohuman(databytes): + """ + Format a string of bytes into a human-readable value (using base-1000) + """ + # Matrix of human-to-byte values + byte_unit_matrix = { + "B": 1, + "KB": 1000, + "MB": 1000 * 1000, + "GB": 1000 * 1000 * 1000, + "TB": 1000 * 1000 * 1000 * 1000, + "PB": 1000 * 1000 * 1000 * 1000 * 1000, + "EB": 1000 * 1000 * 1000 * 1000 * 1000 * 1000, + } + + datahuman = "" + for unit in sorted(byte_unit_matrix, key=byte_unit_matrix.get, reverse=True): + if unit in ["TB", "PB", "EB"]: + # Handle the situation where we might want to round to integer values + # for some entries (2TB) but not others (e.g. 1.92TB). We round if the + # result is within +/- 2% of the integer value, otherwise we use two + # decimal places. + new_bytes = databytes / byte_unit_matrix[unit] + new_bytes_plustwopct = new_bytes * 1.02 + new_bytes_minustwopct = new_bytes * 0.98 + cieled_bytes = int(math.ceil(databytes / byte_unit_matrix[unit])) + rounded_bytes = round(databytes / byte_unit_matrix[unit], 2) + if ( + cieled_bytes > new_bytes_minustwopct + and cieled_bytes < new_bytes_plustwopct + ): + new_bytes = cieled_bytes + else: + new_bytes = rounded_bytes + + # Round up if 5 or more digits + if new_bytes > 999: + # We can jump down another level + continue + else: + # We're at the end, display with this size + datahuman = "{}{}".format(new_bytes, unit) + + return datahuman + + +def get_system_drive_target(session, cspec_node, storage_root): + """ + Determine the system drive target for the installer + """ + # Handle an invalid >2 number of system disks, use only first 2 + if len(cspec_node["config"]["system_disks"]) > 2: + cspec_drives = cspec_node["config"]["system_disks"][0:2] + else: + cspec_drives = cspec_node["config"]["system_disks"] + + # If we have no storage root, we just return the first entry from + # the cpsec_drives as-is and hope the administrator has the right + # format here. + if storage_root is None: + return cspec_drives[0] + # We proceed with Redfish configuration to determine the disks + else: + storage_detail = session.get(storage_root) + + # Grab a full list of drives + drive_list = list() + for storage_member in storage_detail["Members"]: + storage_member_root = storage_member["@odata.id"] + storage_member_detail = session.get(storage_member_root) + for drive in storage_member_detail["Drives"]: + drive_root = drive["@odata.id"] + drive_detail = session.get(drive_root) + drive_list.append(drive_detail) + + system_drives = list() + + # Iterate through each drive and include those that match + for cspec_drive in cspec_drives: + if re.match(r"^\/dev", cspec_drive) or re.match(r"^detect:", cspec_drive): + # We only match the first drive that has these conditions for use in the preseed config + logger.info( + "Found a drive with a 'detect:' string or Linux '/dev' path, using it for bootstrap." + ) + return cspec_drive + + # Match any chassis-ID spec drives + for drive in drive_list: + # Like "Disk.Bay.2:Enclosure.Internal.0-1:RAID.Integrated.1-1" + drive_name = drive["Id"].split(":")[0] + # Craft up the cspec version of this + cspec_drive_name = f"Drive.Bay.{cspec_drive}" + if drive_name == cspec_drive_name: + system_drives.append(drive) + + # We found a single drive, so determine its actual detect string + if len(system_drives) == 1: + logger.info( + "Found a single drive matching the requested chassis ID, using it as the system disk." + ) + + # Get the model's first word + drive_model = system_drives[0].get("Model", "INVALID").split()[0] + # Get and convert the size in bytes value to human + drive_size_bytes = system_drives[0].get("CapacityBytes", 0) + drive_size_human = format_bytes_tohuman(drive_size_bytes) + # Get the drive ID out of all the valid entries + # How this works is that, for each non-array disk, we must find what position our exact disk is + # So for example, say we want disk 3 out of 4, and all 4 are the same size and model and not in + # another (RAID) volume. This will give us an index of 2. Then in the installer this will match + # the 3rd list entry from "lsscsi". This is probably an unneccessary hack, since people will + # probably just give the first disk if they want one, or 2 disks if they want a RAID-1, but this + # is here just in case + idx = 0 + for drive in drive_list: + list_drive_model = drive.get("Model", "INVALID").split()[0] + list_drive_size_bytes = drive.get("CapacityBytes", 0) + list_drive_in_array = ( + False + if drive.get("Links", {}) + .get("Volumes", [""])[0] + .get("@odata.id") + .split("/")[-1] + == drive.get("Id") + else True + ) + if ( + drive_model == list_drive_model + and drive_size_bytes == list_drive_size_bytes + and not list_drive_in_array + ): + index = idx + idx += 1 + drive_id = index + + # Create the target string + system_drive_target = f"detect:{drive_model}:{drive_size_human}:{drive_id}" + + # We found two drives, so create a RAID-1 array then determine the volume's detect string + elif len(system_drives) == 2: + logger.info( + "Found two drives matching the requested chassis IDs, creating a RAID-1 and using it as the system disk." + ) + + drive_one = system_drives[0] + drive_one_id = drive_one.get("Id", "INVALID") + drive_one_path = drive_one.get("@odata.id", "INVALID") + drive_one_controller = drive_one_id.split(":")[-1] + drive_two = system_drives[1] + drive_two_id = drive_two.get("Id", "INVALID") + drive_two_path = drive_two.get("@odata.id", "INVALID") + drive_two_controller = drive_two_id.split(":")[-1] + + # Determine that the drives are on the same controller + if drive_one_controller != drive_two_controller: + logger.error( + "Two drives are not on the same controller; this should not happen" + ) + return None + + # Get the controller details + controller_root = f"{storage_root}/{drive_one_controller}" + controller_detail = session.get(controller_root) + + # Get the name of the controller (for crafting the detect string) + controller_name = controller_detail.get("Name", "INVALID").split()[0] + + # Get the volume root for the controller + controller_volume_root = controller_detail.get("Volumes", {}).get( + "@odata.id" + ) + + # Get the pre-creation list of volumes on the controller + controller_volumes_pre = [ + volume["@odata.id"] + for volume in session.get(controller_volume_root).get("Members", []) + ] + + # Create the RAID-1 volume + payload = { + "VolumeType": "Mirrored", + "Drives": [ + {"@odata.id": drive_one_path}, + {"@odata.id": drive_two_path}, + ], + } + session.post(controller_volume_root, payload) + + # Wait for the volume to be created + new_volume_list = [] + while len(new_volume_list) < 1: + sleep(5) + controller_volumes_post = [ + volume["@odata.id"] + for volume in session.get(controller_volume_root).get("Members", []) + ] + new_volume_list = list( + set(controller_volumes_post).difference(controller_volumes_pre) + ) + new_volume_root = new_volume_list[0] + + # Get the IDX of the volume out of any others + volume_id = 0 + for idx, volume in enumerate(controller_volumes_post): + if volume == new_volume_root: + volume_id = idx + break + + # Get and convert the size in bytes value to human + volume_detail = session.get(new_volume_root) + volume_size_bytes = volume_detail.get("CapacityBytes", 0) + volume_size_human = format_bytes_tohuman(volume_size_bytes) + + # Create the target string + system_drive_target = ( + f"detect:{controller_name}:{volume_size_human}:{volume_id}" + ) + + # We found too few or too many drives, error + else: + system_drive_target = None + + return system_drive_target + + +# +# Redfish Task functions +# +def set_indicator_state(session, system_root, redfish_vendor, state): + """ + Set the system indicator LED to the desired state (on/off) + """ + state_values_write = { + "Dell": { + "on": "Blinking", + "off": "Off", + }, + "default": { + "on": "Lit", + "off": "Off", + }, + } + + state_values_read = { + "default": { + "on": "Lit", + "off": "Off", + }, + } + + try: + # Allow vendor-specific overrides + if redfish_vendor not in state_values_write: + redfish_vendor = "default" + # Allow nice names ("on"/"off") + if state in state_values_write[redfish_vendor]: + state = state_values_write[redfish_vendor][state] + + # Get current state + system_detail = session.get(system_root) + current_state = system_detail["IndicatorLED"] + except KeyError: + return False + + try: + state_read = state + # Allow vendor-specific overrides + if redfish_vendor not in state_values_read: + redfish_vendor = "default" + # Allow nice names ("on"/"off") + if state_read in state_values_read[redfish_vendor]: + state_read = state_values_read[redfish_vendor][state] + + if state_read == current_state: + return False + except KeyError: + return False + + session.patch(system_root, {"IndicatorLED": state}) + + return True + + +def set_power_state(session, system_root, redfish_vendor, state): + """ + Set the system power state to the desired state + """ + state_values = { + "default": { + "on": "On", + "off": "ForceOff", + }, + } + + try: + # Allow vendor-specific overrides + if redfish_vendor not in state_values: + redfish_vendor = "default" + # Allow nice names ("on"/"off") + if state in state_values[redfish_vendor]: + state = state_values[redfish_vendor][state] + + # Get current state, target URI, and allowable values + system_detail = session.get(system_root) + current_state = system_detail["PowerState"] + power_root = system_detail["Actions"]["#ComputerSystem.Reset"]["target"] + power_choices = system_detail["Actions"]["#ComputerSystem.Reset"][ + "ResetType@Redfish.AllowableValues" + ] + except KeyError: + return False + + # Remap some namings so we can check the current state against the target state + if state in ["ForceOff"]: + target_state = "Off" + else: + target_state = state + + if target_state == current_state: + return False + + if state not in power_choices: + return False + + session.post(power_root, {"ResetType": state}) + + return True + + +def set_boot_override(session, system_root, redfish_vendor, target): + """ + Set the system boot override to the desired target + """ + try: + system_detail = session.get(system_root) + boot_targets = system_detail["Boot"]["BootSourceOverrideSupported"] + except KeyError: + return False + + if target not in boot_targets: + return False + + session.patch(system_root, {"Boot": {"BootSourceOverrideTarget": target}}) + + return True + + +def check_redfish(config, data): + """ + Validate that a BMC is Redfish-capable + """ + headers = {"Content-Type": "application/json"} + logger.info("Checking for Redfish response...") + count = 0 + while True: + try: + count += 1 + if count > 30: + retcode = 500 + logger.warn("Aborted after 300s; device too slow or not booting.") + break + resp = requests.get( + f"https://{data['ipaddr']}/redfish/v1", + headers=headers, + verify=False, + timeout=10, + ) + retcode = resp.retcode + break + except Exception: + logger.info(f"Attempt {count}...") + continue + + if retcode == 200: + return True + else: + return False + + +# +# Entry function +# +def redfish_init(config, cspec, data): + """ + Initialize a new node with Redfish + """ + bmc_ipaddr = data["ipaddr"] + bmc_macaddr = data["macaddr"] + bmc_host = f"https://{bmc_ipaddr}" + + cspec_node = cspec["bootstrap"][bmc_macaddr] + logger.debug(f"cspec_node = {cspec_node}") + + bmc_username = cspec_node["bmc"]["username"] + bmc_password = cspec_node["bmc"]["password"] + + host_macaddr = "" + host_ipaddr = "" + + cspec_cluster = cspec_node["node"]["cluster"] + cspec_hostname = cspec_node["node"]["hostname"] + + cluster = db.get_cluster(config, name=cspec_cluster) + if cluster is None: + cluster = db.add_cluster(config, cspec, cspec_cluster, "provisioning") + + logger.debug(cluster) + + db.update_node_state(config, cspec_cluster, cspec_hostname, "characterzing") + db.update_node_addresses( + config, + cspec_cluster, + cspec_hostname, + bmc_macaddr, + bmc_ipaddr, + host_macaddr, + host_ipaddr, + ) + node = db.get_node(config, cspec_cluster, name=cspec_hostname) + logger.debug(node) + + # Create the session and log in + session = RedfishSession(bmc_host, bmc_username, bmc_password) + if session.host is None: + logger.info("Aborting Redfish configuration; reboot BMC to try again.") + del session + return + + logger.info("Characterizing node...") + # Get Refish bases + redfish_base_root = "/redfish/v1" + redfish_base_detail = session.get(redfish_base_root) + + redfish_vendor = list(redfish_base_detail["Oem"].keys())[0] + redfish_name = redfish_base_detail["Name"] + redfish_version = redfish_base_detail["RedfishVersion"] + + systems_base_root = redfish_base_detail["Systems"]["@odata.id"].rstrip("/") + systems_base_detail = session.get(systems_base_root) + + system_root = systems_base_detail["Members"][0]["@odata.id"].rstrip("/") + + # Force off the system and turn on the indicator + set_power_state(session, system_root, redfish_vendor, "off") + set_indicator_state(session, system_root, redfish_vendor, "on") + + # Get the system details + system_detail = session.get(system_root) + + system_sku = system_detail["SKU"].strip() + system_serial = system_detail["SerialNumber"].strip() + system_power_state = system_detail["PowerState"].strip() + system_indicator_state = system_detail["IndicatorLED"].strip() + system_health_state = system_detail["Status"]["Health"].strip() + + # Walk down the EthernetInterfaces construct to get the bootstrap interface MAC address + try: + ethernet_root = system_detail["EthernetInterfaces"]["@odata.id"].rstrip("/") + ethernet_detail = session.get(ethernet_root) + first_interface_root = ethernet_detail["Members"][0]["@odata.id"].rstrip("/") + first_interface_detail = session.get(first_interface_root) + # Something went wrong, so fall back + except KeyError: + first_interface_detail = dict() + + # Try to get the MAC address directly from the interface detail (Redfish standard) + if first_interface_detail.get("MACAddress") is not None: + bootstrap_mac_address = first_interface_detail["MACAddress"].strip().lower() + # Try to get the MAC address from the HostCorrelation->HostMACAddress (HP DL360x G8) + elif len(system_detail.get("HostCorrelation", {}).get("HostMACAddress", [])) > 0: + bootstrap_mac_address = ( + system_detail["HostCorrelation"]["HostMACAddress"][0].strip().lower() + ) + # We can't find it, so use a dummy value + else: + logger.error("Could not find a valid MAC address for the bootstrap interface.") + return + + # Display the system details + logger.info("Found details from node characterization:") + logger.info(f"> System Manufacturer: {redfish_vendor}") + logger.info(f"> System Redfish Version: {redfish_version}") + logger.info(f"> System Redfish Name: {redfish_name}") + logger.info(f"> System SKU: {system_sku}") + logger.info(f"> System Serial: {system_serial}") + logger.info(f"> Power State: {system_power_state}") + logger.info(f"> Indicator LED: {system_indicator_state}") + logger.info(f"> Health State: {system_health_state}") + logger.info(f"> Bootstrap NIC MAC: {bootstrap_mac_address}") + + # Update node host MAC address + host_macaddr = bootstrap_mac_address + node = db.update_node_addresses( + config, + cspec_cluster, + cspec_hostname, + bmc_macaddr, + bmc_ipaddr, + host_macaddr, + host_ipaddr, + ) + logger.debug(node) + + logger.info("Determining system disk...") + storage_root = system_detail.get("Storage", {}).get("@odata.id") + system_drive_target = get_system_drive_target(session, cspec_node, storage_root) + if system_drive_target is None: + logger.error( + "No valid drives found; configure a single system drive as a 'detect:' string or Linux '/dev' path instead and try again." + ) + return + logger.info(f"Found system disk {system_drive_target}") + + # Create our preseed configuration + logger.info("Creating node boot configurations...") + installer.add_pxe(config, cspec_node, host_macaddr) + installer.add_preseed(config, cspec_node, host_macaddr, system_drive_target) + + # Adjust any BIOS settings + logger.info("Adjusting BIOS settings...") + bios_root = system_detail.get("Bios", {}).get("@odata.id") + if bios_root is not None: + bios_detail = session.get(bios_root) + bios_attributes = list(bios_detail["Attributes"].keys()) + for setting, value in cspec_node["bmc"].get("bios_settings", {}).items(): + if setting not in bios_attributes: + continue + + payload = {"Attributes": {setting: value}} + session.patch(f"{bios_root}/Settings", payload) + + # Set boot override to Pxe for the installer boot + logger.info("Setting temporary PXE boot...") + set_boot_override(session, system_root, redfish_vendor, "Pxe") + + # Turn on the system + logger.info("Powering on node...") + set_power_state(session, system_root, redfish_vendor, "on") + + node = db.update_node_state(config, cspec_cluster, cspec_hostname, "pxe-booting") + + logger.info("Waiting for completion of node and cluster installation...") + # Wait for the system to install and be configured + while node.state != "booted-completed": + sleep(60) + # Keep the Redfish session alive + session.get(redfish_base_root) + # Refresh our node state + node = db.get_node(config, cspec_cluster, name=cspec_hostname) + + # Graceful shutdown of the machine + set_power_state(session, system_root, redfish_vendor, "GracefulShutdown") + system_power_state = "On" + while system_power_state != "Off": + sleep(5) + # Refresh our power state from the system details + system_detail = session.get(system_root) + system_power_state = system_detail["PowerState"].strip() + + # Turn off the indicator to indicate bootstrap has completed + set_indicator_state(session, system_root, redfish_vendor, "off") + + # We must delete the session + del session + return diff --git a/bootstrap-daemon/pvcbootstrapd/lib/tftp.py b/bootstrap-daemon/pvcbootstrapd/lib/tftp.py new file mode 100755 index 0000000..680fdaf --- /dev/null +++ b/bootstrap-daemon/pvcbootstrapd/lib/tftp.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +# tftp.py - PVC Cluster Auto-bootstrap TFTP preparation libraries +# Part of the Parallel Virtual Cluster (PVC) system +# +# Copyright (C) 2018-2021 Joshua M. Boniface +# +# 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, version 3. +# +# 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 . +# +############################################################################### + +import os.path +import shutil + + +def build_tftp_repository(config): + # Generate an installer config + build_cmd = f"{config['ansible_path']}/pvc-installer/buildpxe.sh -o {config['tftp_root_path']} -u {config['deploy_username']}" + print(f"Building TFTP contents via pvc-installer command: {build_cmd}") + os.system(build_cmd) + + +def init_tftp(config): + """ + Prepare a TFTP root + """ + if not os.path.exists(config["tftp_root_path"]): + print("First run: building TFTP root and contents - this will take some time!") + os.makedirs(config["tftp_root_path"]) + os.makedirs(config["tftp_host_path"]) + shutil.copyfile( + f"{config['ansible_keyfile']}.pub", f"{config['tftp_root_path']}/keys.txt" + ) + + build_tftp_repository(config) diff --git a/bootstrap-daemon/requirements.txt b/bootstrap-daemon/requirements.txt new file mode 100644 index 0000000..0b02bc6 --- /dev/null +++ b/bootstrap-daemon/requirements.txt @@ -0,0 +1,11 @@ +ansible +ansible_runner +celery +flask +flask_restful +gevent +gitpython +paramiko +pyyaml +redis +requests diff --git a/docs/images/pvcbootstrapd-net.png b/docs/images/pvcbootstrapd-net.png new file mode 100644 index 0000000..5b0edee Binary files /dev/null and b/docs/images/pvcbootstrapd-net.png differ diff --git a/docs/images/pvcbootstrapd-phy.png b/docs/images/pvcbootstrapd-phy.png new file mode 100644 index 0000000..bc60197 Binary files /dev/null and b/docs/images/pvcbootstrapd-phy.png differ diff --git a/docs/swagger.html b/docs/swagger.html new file mode 100644 index 0000000..a724f5b --- /dev/null +++ b/docs/swagger.html @@ -0,0 +1,13 @@ + + + + PVC Bootstrap API Documentation + + + + + + + + + diff --git a/docs/swagger.json b/docs/swagger.json new file mode 100644 index 0000000..0f57543 --- /dev/null +++ b/docs/swagger.json @@ -0,0 +1,191 @@ +{ + "definitions": { + "Message": { + "properties": { + "message": { + "description": "A text message describing the result", + "example": "The foo was successfully maxed", + "type": "string" + } + }, + "type": "object" + } + }, + "host": "localhost:9999", + "info": { + "title": "PVC Bootstrap API", + "version": "1.0" + }, + "paths": { + "/": { + "get": { + "description": "", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/Message" + } + } + }, + "summary": "Return basic details of the API", + "tags": [ + "root" + ] + } + }, + "/checkin": { + "get": { + "description": "", + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/Message" + } + } + }, + "summary": "Return checkin details of the API", + "tags": [ + "checkin" + ] + } + }, + "/checkin/dnsmasq": { + "post": { + "consumes": [ + "application/json" + ], + "description": "", + "parameters": [ + { + "description": "An event checkin from an external bootstrap tool component.", + "in": "body", + "name": "dnsmasq_checkin_event", + "schema": { + "properties": { + "action": { + "description": "The action of the event.", + "example": "add", + "type": "string" + }, + "client_id": { + "description": "(add, old) The client ID from a DHCP request.", + "example": "01:ff:ff:ff:ab:cd:ef", + "type": "string" + }, + "hostname": { + "description": "(add, old) The client hostname from a DHCP request.", + "example": "pvc-installer-live", + "type": "string" + }, + "ipaddr": { + "description": "(add, old) The IP address from a DHCP request.", + "example": "10.199.199.10", + "type": "string" + }, + "macaddr": { + "description": "(add, old) The MAC address from a DHCP request.", + "example": "ff:ff:ff:ab:cd:ef", + "type": "string" + }, + "user_class": { + "description": "(add, old) The DHCP user-class option from a DHCP request.", + "example": "None", + "type": "string" + }, + "vendor_class": { + "description": "(add, old) The DHCP vendor-class option from a DHCP request.", + "example": "CPQRIB3 (HP Proliant DL360 G6 iLO)", + "type": "string" + } + }, + "required": [ + "action" + ], + "type": "object" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/Message" + } + } + }, + "summary": "Register a checkin from the DNSMasq subsystem", + "tags": [ + "checkin" + ] + } + }, + "/checkin/host": { + "post": { + "consumes": [ + "application/json" + ], + "description": "", + "parameters": [ + { + "description": "An event checkin from an external bootstrap tool component.", + "in": "body", + "name": "host_checkin_event", + "schema": { + "properties": { + "action": { + "description": "The action of the event.", + "example": "begin", + "type": "string" + }, + "bmc_ipaddr": { + "description": "The IP addres of the system BMC interface.", + "example": "10.199.199.10", + "type": "string" + }, + "bmc_macaddr": { + "description": "The MAC address of the system BMC interface.", + "example": "ff:ff:ff:01:23:45", + "type": "string" + }, + "host_ipaddr": { + "description": "The IP address of the system provisioning interface.", + "example": "10.199.199.11", + "type": "string" + }, + "host_macaddr": { + "description": "The MAC address of the system provisioning interface.", + "example": "ff:ff:ff:ab:cd:ef", + "type": "string" + }, + "hostname": { + "description": "The system hostname.", + "example": "hv1.mydomain.tld", + "type": "string" + } + }, + "required": [ + "action" + ], + "type": "object" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/Message" + } + } + }, + "summary": "Register a checkin from the Host subsystem", + "tags": [ + "checkin" + ] + } + } + }, + "swagger": "2.0" +} \ No newline at end of file diff --git a/format b/format new file mode 100755 index 0000000..6354948 --- /dev/null +++ b/format @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +if ! which black &>/dev/null; then + echo "Black is required to format this project" + exit 1 +fi + +if [[ $1 == "check" ]]; then + check="--check" +fi + +pushd $( git rev-parse --show-toplevel ) &>/dev/null + +echo ">>> Formatting..." +black --safe ${check} . +ret=$? +if [[ $ret -eq 0 ]]; then + echo "Successfully formatted project!" +fi + +popd &>/dev/null +exit $ret diff --git a/gen-api-doc b/gen-api-doc new file mode 100755 index 0000000..b44b6fb --- /dev/null +++ b/gen-api-doc @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 + +# gen-doc.py - Generate a Swagger JSON document for the API +# Part of the Parallel Virtual Cluster (PVC) system + +from flask_swagger import swagger +import os +import sys +import json + +os.environ['PVCD_CONFIG_FILE'] = "./bootstrap-daemon/pvcbootstrapd.yaml.sample" + +sys.path.append('bootstrap-daemon') + +import pvcbootstrapd.flaskapi as pvcbootstrapd + +swagger_file = "docs/swagger.json" +swagger_data = swagger(pvcbootstrapd.app) +swagger_data['info']['version'] = "1.0" +swagger_data['info']['title'] = "PVC Bootstrap API" +swagger_data['host'] = "localhost:9999" + +with open(swagger_file, 'w') as fd: + fd.write(json.dumps(swagger_data, sort_keys=True, indent=4)) diff --git a/install-pvcbootstrapd.sh b/install-pvcbootstrapd.sh new file mode 100755 index 0000000..2e9ed71 --- /dev/null +++ b/install-pvcbootstrapd.sh @@ -0,0 +1,263 @@ +#!/usr/bin/env bash + +# PVC Bootstrap system installer + +username="${USER}" + +echo "Welcome to the PVC bootstrap installer. This will guide you through the setup process." +echo +echo "The PVC bootstrap system will be installed as user: ${username}" +echo +echo "Please enter the bootstrap root directory; all components will be installed here:" +echo -n "[/srv/pvc] > " +read root_directory +if [[ -z ${root_directory} ]]; then + root_directory="/srv/pvc" +fi +echo + +echo "Please enter the IP network for the Bootstrap network (MUST be an RFC1918 /24):" +echo -n "[10.255.255.0/24] > " +read bootstrap_network +if [[ -z ${bootstrap_network} ]]; then + bootstrap_network="10.255.255.0/24" +fi +echo + +echo "Will the bootstrap interface be a vLAN? Note: It should not be configured yet if so!" +echo -n "[y/N] > " +read is_bootstrap_interface_vlan +case ${is_bootstrap_interface_vlan} in + y|Y|yes|Yes|YES) is_bootstrap_interface_vlan="yes" ;; + *) is_bootstrap_interface_vlan="no" ;; +esac +echo + +all_interfaces=( $( + ip address | grep '^[0-9]' | grep 'bond\|eth\|eno\|enp\|ens\|wlan\|wlp' | awk '{ print $2 }' | tr -d ':' +) ) + +if [[ "${is_bootstrap_interface_vlan}" == "yes" ]]; then +echo "Please enter the underlying device for the Bootstrap network vLAN:" +else +echo "Please enter the Bootstrap network interface:" +fi +echo "Available interfaces: ${all_interfaces[@]}" +bootstrap_interface="" +while true; do + echo -n "> " + read bootstrap_interface + if [[ -n ${bootstrap_interface} && "${all_interfaces[@]}" =~ "${bootstrap_interface}" ]]; then + break + fi +done +echo + +if [[ "${is_bootstrap_interface_vlan}" == "yes" ]]; then +echo "Please enter the Bootstrap network vLAN ID:" +echo -n "> " +read bootstrap_vlan +echo +fi + +echo "Please enter the upstream network interface for outbound NAT:" +echo "Available interfaces: ${all_interfaces[@]}" +upstream_interface="" +while true; do + echo -n "> " + read upstream_interface + if [[ -n ${upstream_interface} && "${all_interfaces[@]}" =~ "${upstream_interface}" ]]; then + break + fi +done +echo + +echo "Please enter the Git remote (SSH-only) for your local PVC repository:" +while [[ -z ${git_remote} ]]; do +echo -n "> " +read git_remote +done +echo + +echo "Please enter the branch to use from the local PVC repository:" +echo -n "[master] > " +read git_branch +if [[ -z ${git_branch} ]]; then + git_branch="master" +fi +echo + +echo "Please enter a username for Ansible management of the clusters:" +echo -n "[deploy] > " +read deploy_username +if [[ -z ${deploy_username} ]]; then + deploy_username="deploy" +fi +echo + +echo "Proceeding with setup!" +echo + +echo "Installing APT dependencies..." +sudo apt-get update +sudo apt-get install --yes vlan iptables dnsmasq redis python3 python3-pip python3-requests sqlite3 celery pxelinux syslinux-common live-build debootstrap uuid-runtime qemu-user-static + +echo "Configuring dnsmasq..." +sudo systemctl disable --now dnsmasq +# Required to permit non-root running of dnsmasq +sudo chmod +s /usr/sbin/dnsmasq + +echo "Creating root directory..." +sudo mkdir -p ${root_directory} +sudo chown $USER ${root_directory} + +echo "Installing pvcbootstrapd..." +cp -a bootstrap-daemon ${root_directory}/pvcbootstrapd + +echo "Installing PIP dependencies..." +sudo pip3 install -r ${root_directory}/pvcbootstrapd/requirements.txt + +echo "Determining IP addresses..." +bootstrap_address="$( awk -F'.' '{ print $1"."$2"."$3".1" }' <<<"${bootstrap_network}" )" +bootstrap_dhcpstart="$( awk -F'.' '{ print $1"."$2"."$3".100" }' <<<"${bootstrap_network}" )" +bootstrap_dhcpend="$( awk -F'.' '{ print $1"."$2"."$3".199" }' <<<"${bootstrap_network}" )" + +echo "Creating configuration..." +cp ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml.template ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|DEPLOY_USERNAME|${deploy_username}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|ROOT_DIRECTORY|${root_directory}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|BOOTSTRAP_ADDRESS|${bootstrap_address}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|BOOTSTRAP_DHCPSTART|${bootstrap_dhcpstart}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|BOOTSTRAP_DHCPEND|${bootstrap_dhcpend}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|GIT_REMOTE|${git_remote}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +sed -i "s|GIT_BRANCH|${git_branch}|" ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml + +echo "Creating network configuration for interface ${bootstrap_interface} (is vLAN? ${is_bootstrap_interface_vlan})..." +if [[ "${is_bootstrap_interface_vlan}" == "yes" ]]; then +cat </dev/null +auto vlan${bootstrap_vlan} +iface vlan${bootstrap_vlan} inet static + vlan_raw_device ${bootstrap_interface} + address ${bootstrap_address} + netmask 255.255.255.0 + post-up echo 1 > /proc/sys/net/ipv4/ip_forward + post-up iptables -A FORWARD -i \$IFACE -j ACCEPT + post-up iptables -A FORWARD -o \$IFACE -m state --state ESTABLISHED,RELATED -j ACCEPT + post-up iptables -t nat -A POSTROUTING -o ${upstream_interface} -j MASQUERADE +EOF +else +cat </dev/null +auto ${bootstrap_interface} +iface ${bootstrap_interface} inet static + address ${bootstrap_address} + netmask 255.255.255.0 + post-up echo 1 > /proc/sys/net/ipv4/ip_forward + post-up iptables -A FORWARD -i \$IFACE -j ACCEPT + post-up iptables -A FORWARD -o \$IFACE -m state --state ESTABLISHED,RELATED -j ACCEPT + post-up iptables -t nat -A POSTROUTING -o ${upstream_interface} -j MASQUERADE +EOF +fi + +echo "Installing service units..." +cat </dev/null +# Parallel Virtual Cluster Bootstrap API daemon unit file + +[Unit] +Description = Parallel Virtual Cluster Bootstrap API daemon +After = network-online.target + +[Service] +Type = simple +User = ${username} +WorkingDirectory = ${root_directory}/pvcbootstrapd +Environment = PYTHONUNBUFFERED=true +Environment = PVCD_CONFIG_FILE=${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +ExecStart = ${root_directory}/pvcbootstrapd/pvcbootstrapd.py +Restart = on-failure + +[Install] +WantedBy = multi-user.target +EOF +sudo systemctl enable pvcbootstrapd.service + +cat </dev/null +# Parallel Virtual Cluster Provisioner API provisioner worker unit file + +[Unit] +Description = Parallel Virtual Cluster Bootstrap API worker +After = network-online.target + +[Service] +Type = simple +User = ${username} +WorkingDirectory = ${root_directory}/pvcbootstrapd +Environment = PYTHONUNBUFFERED=true +Environment = PVCD_CONFIG_FILE=${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml +ExecStart = ${root_directory}/pvcbootstrapd/pvcbootstrapd-worker.sh +Restart = on-failure + +[Install] +WantedBy = multi-user.target +EOF +sudo systemctl enable pvcbootstrapd-worker.service + +sudo systemctl daemon-reload + +if [[ ! -f ${root_directory}/id_ed25519 ]]; then + echo "Generating SSH keypair..." + ssh-keygen -t ed25519 -C "pvcbootstrapd@$(hostname)" -N "" -f ${root_directory}/id_ed25519 +fi +echo +echo "Before proceeding, add the following SSH key as a writable deploy key to your local PVC repository." +echo "This will allow both repository cloning and push of committed changes to the remote repository." +echo "This key will also be used for ${deploy_username} user Ansible access when configuring clusters." +echo +echo -n " " +cat ${root_directory}/id_ed25519.pub +echo +echo -n "Press once completed to continue. " +read +echo + +echo "Edit configuration before proceeding?" +echo -n "[y/N] > " +read edit_flag +case ${edit_flag} in + y|Y|yes|Yes|YES) + vim ${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml + ;; + *) + true + ;; +esac +echo + +echo "Start the pvcbootstrapd process manually for initialization (this will take quite some time)?" +echo -n "[Y/n] > " +read start_flag +case ${start_flag} in + n|N|no|No|NO) + true + ;; + *) + echo + export PVCD_CONFIG_FILE="${root_directory}/pvcbootstrapd/pvcbootstrapd.yaml" + ${root_directory}/pvcbootstrapd/pvcbootstrapd.py --init-only + ;; +esac +echo + +echo "Restart system to finalize installation?" +echo -n "[Y/n] > " +read reboot_flag +case ${reboot_flag} in + n|N|no|No|NO) + true + ;; + *) + sudo reboot + ;; +esac + +# Done +exit 0 diff --git a/lint b/lint new file mode 100755 index 0000000..7bd17bc --- /dev/null +++ b/lint @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +if ! which flake8 &>/dev/null; then + echo "Flake8 is required to lint this project" + exit 1 +fi + +pushd $( git rev-parse --show-toplevel ) &>/dev/null + +echo ">>> Linting..." +flake8 +ret=$? +if [[ $ret -eq 0 ]]; then + echo "No linting issues found!" +fi + +popd &>/dev/null +exit $ret