[
  {
    "path": ".gitignore",
    "content": "# Created by .ignore support plugin (hsz.mobi)\n### Example user template template\n### Example user template\n\n# IntelliJ project files\n.idea\n*.iml\nout\ngen\n"
  },
  {
    "path": "HISTORY.rst",
    "content": "=======\nHistory\n=======\n\n0.1.0 (2016-3-20)\n------------------\n\n* First release on PyPI.\n"
  },
  {
    "path": "LICENCE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "Kubespray wrapper\n=============\n\nThis tool helps to deploy a kubernetes cluster with ansible.\n\n\nExample on GCE:\n[![asciicast](https://asciinema.org/a/065mhh5pzmxcwxgp6evebarvd.png)](https://asciinema.org/a/065mhh5pzmxcwxgp6evebarvd?speed=4)\n\nRequirements\n============\n\n-   **Ansible v2.3 (or newer)**\n-   The current user must have its ssh **public key** installed on the\n    remote servers.\n-   The remote user (option --user) must be in the sudoers with no\n    password\n\nInstallation\n============\n\n### Python pip\n\n    sudo pip2 install kubespray\n\n\nConfig file\n-----------\n\nA config file can be updated (yaml). (default: *~/.kubespray.yml* ) </br>\nThis file contains default values for some parameters that don't change\nfrequently </br>\n**Note** these values are **overwritten** by the command line.\n\n\n    # Common options\n    # ---------------\n    # Path where the kubespray ansible playbooks will be installed\n    # Defaults to current user's home directory if not set\n    # kubespray_path: \"/tmp\"\n    # Default inventory path\n    kubespray_git_repo: \"https://github.com/kubernetes-incubator/kubespray.git\"\n    # Logging options\n    loglevel: \"info\"\n\n    # Amazon web services options\n    # ---\n    # aws_access_key: \"<key>\"\n    # aws_secret_key: \"<secret_key>\"\n    # key_name: \"<keypair_name>\"\n    # ami: \"<aws_ami>\"\n    # masters_instance_type: \"<masters_instance_type>\"\n    # nodes_instance_type: \"<nodes_instance_type>\"\n    # etcds_instance_type: \"<etcds_instance_type>\"\n    # masters_instance_profile_name: \"<master_instance_profile_name>\"\n    # nodes_instance_profile_name: \"<nodes_instance_profile_name>\"\n    # etcds_instance_profile_name: \"<etcds_instance_profile_name>\"\n    # security_group_name: \"<security_group_name>\"\n    # security_group_id: \"<security_group_id>\"\n    # assign_public_ip: True\n    # vpc_subnet_id: \"<vpc_id>\"\n    # region: \"<aws_region>\"\n    # tags:\n    #   - type: k8s\n\n    # OpenStack options\n    # ---\n    # os_auth_url: \"https://\"\n    # os_username: \"k8s\"\n    # os_password: \"secret\"\n    # os_project_name: \"k8s\"\n    # masters_flavor: \"m1.small\"\n    # nodes_flavor: \"m1.small\"\n    # etcds_flavor: \"m1.small\"\n    # image: \"wily-server-cloudimg-amd64\"\n    # network: \"my-network\"\n    # sshkey: \"my-pub-key\"\n    ...\n\nBasic usage\n-----------\n**Note**: You may want to choose the architecture of your cluster. </br>\nHere are 3 examples:\n* 3 vms, all 3 have etcd installed, all 3 are nodes (running pods), 2 of them run master components\n```\nkubespray [prepare|aws|gce] --nodes 3\n```\n\n![3nodes](https://s32.postimg.org/8q7gns8ut/3nodes.png)\n* 6 vms, 2 are nodes and masters, 1 is node only and a distinct etcd cluster\n```\nkubespray [prepare|aws|gce] --nodes 3 --etcds 3\n```\n\n![3nodes3etcds](https://s32.postimg.org/hphgxcjmt/3nodes_3etcds.png)\n* 8 vms, 2 distinct masters, 3 nodes and 3 etcds\n```\nkubespray [prepare|aws|gce] --nodes 3 --etcds 3 --masters 2\n```\n\n![3nodes3etcds2masters](https://s31.postimg.org/h4gdu4qjv/3nodes_2masters_3etcds.png)\n\nYou should have at least 3 nodes but you can spawn only one instance for\ntests purposes.\n\n### Generate inventory for a baremetal cluster\n\nIf the servers are already available you can use the argument **prepare**\nThe command below will just clone the git repository and creates the\ninventory.\nThe hostvars must be separated by a **comma without spaces**\n\n    kubespray prepare --nodes node1[ansible_ssh_host=10.99.21.1] node2[ansible_ssh_host=10.99.21.2] node3[ansible_ssh_host=10.99.21.3] [--etcds N+] [--masters N+]\n\n### Run instances and generate the inventory on Clouds\n\n\n**AWS**\n\nIn order to create vms on AWS you can either edit the config file *~/.kubespray.yml* or set the options with the argument **aws**\nif the config file is filled with the proper information you just need to run the following command\n\n    kubespray aws --nodes 3 [--etcds N+] [masters N+] [--nodes-instance-type m4.large]\n\nAnother example which download kubespray's repo in a defined directory and set the cluster name\n\n    kubespray aws --nodes 3 -p /tmp/mykubespray --cluster-name foobar\n\n\n**GCE**\n\nIn order to create vms on GCE you can either edit the config file */etc/kubespray/kubespray.yml* or set the options with the argument **gce**\nif the config file is filled with the proper information you just need to run the following command\n\n    kubespray gce --nodes 3\n\nAnother example if you already have a kubespray repository in your home dir\n\n    kubespray gce --nodes 3 --noclone --cluster-name foobar [--nodes-machine-type n1-standard-4]\n\n\n**OpenStack**\n\nIn order to create vms on a OpenStack cluster you can either edit the config file *~/.kubespray.yml* or set the options with the argument **openstack**.\nThe options **network** and **sshkey** are required and need to be created before running kubespray, you can either create them using the OpenStack Dashboard or the OpenStack CLI clients. Running the ansible routines that kubespray will invoke requires to have installed the [openstack cli tools](http://docs.openstack.org/user-guide/common/cli_install_openstack_command_line_clients.html) and openstack [shade](http://docs.openstack.org/infra/shade/installation.html).\n\n\nCreate a network using the OpenStack Neutron client\n\n    # create network\n    $ neutron net-create k8s-network\n\n    Created a new network:\n    +-----------------+--------------------------------------+\n    | Field           | Value                                |\n    +-----------------+--------------------------------------+\n    | admin_state_up  | True                                 |\n    | id              | 18989cb2-d9fc-4abd-85e8-fe5b33df3541 |\n    | mtu             | 0                                    |\n    | name            | k8s-network                          |\n    | router:external | False                                |\n    | shared          | False                                |\n    | status          | ACTIVE                               |\n    | subnets         |                                      |\n    | tenant_id       | 5de2cf232a674b05983b61fdc1ea67aa     |\n    +-----------------+--------------------------------------+\n\n    # create subnet\n    $ neutron subnet-create --name k8s-subnet --dns-nameserver 8.8.8.8 --enable-dhcp --allocation_pool \"start=192.168.0.100,end=192.168.0.200\" k8s-network 192.168.0.0/24\n\n    Created a new subnet:\n    +-------------------+----------------------------------------------------+\n    | Field             | Value                                              |\n    +-------------------+----------------------------------------------------+\n    | allocation_pools  | {\"start\": \"192.168.0.100\", \"end\": \"192.168.0.200\"} |\n    | cidr              | 192.168.0.0/24                                     |\n    | dns_nameservers   |                                                    |\n    | enable_dhcp       | True                                               |\n    | gateway_ip        | 192.168.0.1                                        |\n    | host_routes       |                                                    |\n    | id                | fc5a5436-de3a-4d68-9846-d977d047d6d7               |\n    | ip_version        | 4                                                  |\n    | ipv6_address_mode |                                                    |\n    | ipv6_ra_mode      |                                                    |\n    | name              | k8s-subnet                                         |\n    | network_id        | 18989cb2-d9fc-4abd-85e8-fe5b33df3541               |\n    | subnetpool_id     |                                                    |\n    | tenant_id         | 5de2cf232a674b05983b61fdc1ea67aa                   |\n    +-------------------+----------------------------------------------------+\n\n    # create a router\n    $ neutron router-create k8s-router\n\n    Created a new router:\n    +-----------------------+--------------------------------------+\n    | Field                 | Value                                |\n    +-----------------------+--------------------------------------+\n    | admin_state_up        | True                                 |\n    | external_gateway_info |                                      |\n    | id                    | 69027fa4-239b-4bae-89bc-3040c365ee4d |\n    | name                  | k8s-router                           |\n    | routes                |                                      |\n    | status                | ACTIVE                               |\n    | tenant_id             | 5de2cf232a674b05983b61fdc1ea67aa     |\n    +-----------------------+--------------------------------------+\n\n    # set gateway network, external_network is the name of the external network defined by your OpenStack provider\n    $ neutron router-gateway-set k8s-router external_network\n\n    Set gateway for router k8s-router\n\n    # add k8s-subnet to k8s-router, plug the virtual cable\n    $ neutron router-interface-add k8s-router subnet=k8s-subnet\n\n    Added interface a62ca3b4-3302-45b6-803e-f87a4f43b4b6 to router k8s-router.\n\nUpload a ssh key in order to connect to the vms using the OpenStack Nova client\n\n\n    # import SSH Public Key with name k8s-pub-key\n    $ nova keypair-add --pub-key id_rsa.pub k8s-pub-key\n\n\nOnce the preparation have been completed you can enter the required options to the config file */etc/kubespray/kubespray.yml*:\n\n    ...\n\n    network: \"k8s-network\"\n    sshkey: \"k8s-pub-key\"\n\n    ...\n\n\nIf the config file is filled with the proper information you just need to run the following command\n\n    kubespray openstack --masters 2 --nodes 2 --etcds 3\n\nAnother example if you already have a kubespray repository in your home dir\n\n    kubespray openstack --masters 2 --nodes 2 --etcds 3 --noclone --cluster-name foobar\n\n\n**Add a node to an existing cluster**\nIt's possible to add nodes to a running cluster, </br>\nthese newly added nodes will act as node only (no etcd, no master components)\n\nAdd a node\n\n    kubespray [aws|gce] --add --nodes 1\n\nThen deploy the cluster with the same options as the running cluster.\n\n\n### Deploy cluster\n\nThe last step is to run the cluster deployment.\n\n**Note**:\n-   default network plugin : flannel (vxlan) default\n-   default kubespray\\_path : \"/home/\\<current\\_user\\>/kubespray\"\n-   inventory path : \"\\<kubespray\\_path\\>/inventory/inventory.cfg\".\n-   The option `--inventory` allows to use an existing inventory (file or dynamic)\n-   On coreos (--coreos) the directory **/opt/bin** must be writable\n- You can use all Ansible's variables with\n`--ansible-opts '-e foo=bar -e titi=toto -vvv'` (the value must be enclosed by simple quotes)\n\nsome examples:\n\nDeploy with the default options on baremetal\n\n    kubespray deploy\n\nDeploy on AWS using a specific kubespray directory and set the api password\n\n    kubespray deploy --aws --passwd secret -p /tmp/mykubespray -n weave\n\nDeploy a kubernetes cluster on CoreOS servers located on GCE\n\n    kubespray deploy -u core -p /kubespray-dc1 --gce --coreos --cluster-name mykube --kube-network 10.42.0.0/16\n"
  },
  {
    "path": "bin/kubespray",
    "content": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    Foobar is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.\n\n__version__ = '0.5.2'\n\nimport os\nimport argparse\nimport getpass\ntry:\n    from ansible.utils.display import Display\nexcept ImportError:\n    raise ImportError('Cannot find Ansible: Please check your installation (required version 2)')\nfrom kubespray.common import clone_kubespray_git_repo\nfrom kubespray.configure import Config\nfrom kubespray.inventory import CfgInventory\nfrom kubespray.deploy import RunPlaybook\nfrom kubespray.cloud import AWS, GCE, OpenStack\ndisplay = Display()\n\n\ndef prepare(options):\n    clone_kubespray_git_repo(options)\n    Cfg = CfgInventory(options, 'metal')\n    Cfg.write_inventory(\n        options['masters_list'],\n        options['nodes_list'],\n        options['etcds_list']\n    )\n\n\ndef aws(options):\n    clone_kubespray_git_repo(options)\n    A = AWS(options)\n    A.gen_ec2_playbook()\n    A.create_instances()\n    A.write_inventory()\n\n\ndef gce(options):\n    clone_kubespray_git_repo(options)\n    G = GCE(options)\n    G.gen_gce_playbook()\n    G.create_instances()\n    G.write_inventory()\n\n\ndef openstack(options):\n    clone_kubespray_git_repo(options)\n    O = OpenStack(options)\n    O.gen_openstack_playbook()\n    O.create_instances()\n    O.write_inventory()\n\n\ndef deploy(options):\n    Run = RunPlaybook(options)\n    Run.ssh_prepare()\n    Run.deploy_kubernetes()\n\nif __name__ == '__main__':\n    # Main parser\n    parser = argparse.ArgumentParser(\n        prog='kubespray',\n        description='%(prog)s Kubernetes cluster deployment tool',\n        add_help=False\n    )\n    subparsers = parser.add_subparsers(help='commands')\n\n    parser.add_argument(\n        '-v', '--version', action='version',\n        version='%(prog)s'+' %s' % __version__\n    )\n    # Options shared by the first step subparsers (prepare, gce, aws)\n    firststep_parser = argparse.ArgumentParser(add_help=False)\n    firststep_parser.add_argument(\n        '--noclone', default=False, action='store_true', dest='noclone',\n        help='Do not clone the git repo. Useful when the repo is already downloaded'\n    )\n\n    # Options shared by all subparsers\n    parent_parser = argparse.ArgumentParser(add_help=False)\n    parent_parser.add_argument(\n        '-p', '--path', dest='kubespray_path',\n        help='Where the Ansible playbooks are installed. Default: ~/.kubespray'\n    )\n    parent_parser.add_argument(\n        '--config', dest='configfile',\n        help=\"Config file path. Defaults to ~/.kubespray.yml\"\n    )\n    parent_parser.add_argument(\n        '-y', '--assumeyes', default=False, dest='assume_yes', action='store_true',\n        help='When a yes/no prompt would be presented, assume that the user entered \"yes\"'\n    )\n    parent_parser.add_argument(\n        '-i', '--inventory', dest='inventory_path',\n        help='Inventory file path. Defaults to <path parameter>/inventory/inventory.cfg'\n    )\n\n    # prepare\n    prepare_parser = subparsers.add_parser(\n        'prepare', parents=[parent_parser, firststep_parser],\n        help='generate inventory and create vms on cloud providers'\n    )\n    prepare_parser.add_argument('--add', dest='add_node', action='store_true',\n        help=\"Add node to an existing cluster\"\n    )\n    prepare_parser.add_argument(\n        '--etcds', dest='etcds_list', metavar='N', nargs='+', default=[],\n        help='Number of etcd, these instances will just act as etcd members'\n    )\n    prepare_parser.add_argument(\n        '--masters', dest='masters_list', metavar='N', nargs='+', default=[],\n        help='Number of masters, these instances will not run workloads, master components only'\n    )\n    prepare_parser.add_argument(\n        '--nodes', dest='nodes_list', metavar='N', nargs='+',\n        required=True, help='List of nodes'\n    )\n    prepare_parser.set_defaults(func=prepare)\n\n    # aws\n    aws_parser = subparsers.add_parser(\n        'aws', parents=[parent_parser, firststep_parser],\n        help='Create AWS instances and generate inventory'\n    )\n    aws_parser.add_argument(\n        '--access-key', dest='aws_access_key', help='AWS access key'\n    )\n    aws_parser.add_argument(\n        '--secret-key', dest='aws_secret_key', help='AWS secret key'\n    )\n    aws_parser.add_argument(\n        '--masters-instance-type', dest='masters_instance_type',\n        help='AWS instance type for Masters (default: t2.medium)'\n    )\n    aws_parser.add_argument(\n        '--nodes-instance-type', dest='nodes_instance_type',\n        help='AWS instance type for Nodes (default: t2.large)'\n    )\n    aws_parser.add_argument(\n        '--etcds-instance-type', dest='etcds_instance_type',\n        help='AWS instance type for Etcd members (default: t2.small)'\n    )\n    aws_parser.add_argument(\n        '--keypair', dest='key_name', help='AWS key pair name'\n    )\n    aws_parser.add_argument('--region', dest='region', help='AWS region')\n    sg_group = aws_parser.add_mutually_exclusive_group()\n    sg_group.add_argument(\n        '--security-group-name', dest='security_group_name',\n        help='AWS security group Name'\n    )\n    sg_group.add_argument(\n        '--security-group-id', dest='security_group_id',\n        help='AWS security group ID. Uses the \"default\" security group if not specified.'\n    )\n    aws_parser.add_argument(\n        '--assign-public-ip', default=None, dest='assign_public_ip', action='store_true',\n         help='when provisioning within vpc, assign a public IP address'\n    )\n    aws_parser.add_argument(\n        '--use-private-ip', default=None, dest='use_private_ip', action='store_true',\n         help='If set to true, using the private ip for SSH connection'\n    )\n    aws_parser.add_argument('--vpc-id', dest='aws_vpc_id', help='EC2 VPC ID')\n    aws_parser.add_argument(\n        '--vpc-subnet', dest='vpc_subnet_id', help='EC2 VPC subnet ID'\n    )\n    aws_parser.add_argument('--ami', dest='ami', help='AWS AMI')\n    aws_parser.add_argument(\n        '--cluster-name', dest='cluster_name', help='Name of the cluster'\n    )\n    aws_parser.add_argument(\n        '--tags', dest='tags', help='List of VM tags of the form \\'name=value\\'', nargs=\"+\", metavar=\"NAME=VALUE\"\n    )\n    aws_parser.add_argument('--add', dest='add_node', action='store_true',\n        help=\"Add node to an existing cluster\")\n    aws_parser.add_argument(\n        '--etcd', dest='etcds_count', type=int,\n        help='Number of etcd, these instances will just act as etcd members'\n    )\n    aws_parser.add_argument(\n        '--masters', dest='masters_count', type=int,\n        help='Number of masters, these instances will not run workloads, master components only'\n    )\n    aws_parser.add_argument(\n        '--nodes', dest='nodes_count', type=int,\n        help='Number of nodes', required=True\n    )\n    aws_parser.set_defaults(func=aws)\n\n    # gce\n    gce_parser = subparsers.add_parser(\n        'gce', parents=[parent_parser, firststep_parser],\n        help='Create GCE machines and generate inventory'\n    )\n    gce_parser.add_argument(\n        '--pem_file', dest='pem_file', help='GCE ssh pem file path'\n    )\n    gce_parser.add_argument(\n        '--credentials_file', dest='credentials_file',\n        help='GCE credentials json file path'\n    )\n    gce_parser.add_argument(\n        '--zone', dest='zone', help='GCE zone'\n    )\n    gce_parser.add_argument(\n        '--masters-machine-type', dest='masters_machine_type',\n        help='GCE machine type for Masters (default: n1-standard-2)'\n    )\n    gce_parser.add_argument(\n        '--nodes-machine-type', dest='nodes_machine_type',\n        help='GCE machine type for Nodes (default: n1-standard-4)'\n    )\n    gce_parser.add_argument(\n        '--etcds-machine-type', dest='etcds_machine_type',\n        help='GCE machine type for Etcd members (default: n1-standard-1)'\n    )\n    gce_parser.add_argument('--image', dest='image', help='GCE image')\n    gce_parser.add_argument(\n        '--project', dest='project_id', help='GCE project ID'\n    )\n    gce_parser.add_argument(\n        '--email', dest='service_account_email', help='GCE project ID'\n    )\n    gce_parser.add_argument(\n        '--cluster-name', dest='cluster_name', help='Name of the cluster'\n    )\n    gce_parser.add_argument(\n        '--tags', dest='tags', help='List of VM tags', nargs=\"+\", metavar=\"TAG\"\n    )\n    gce_parser.add_argument('--add', dest='add_node', action='store_true',\n        help=\"Add node to an existing cluster\")\n    gce_parser.add_argument(\n        '--etcd', dest='etcds_count', type=int,\n        help='Number of etcd, these instances will just act as etcd members'\n    )\n    gce_parser.add_argument(\n        '--masters', dest='masters_count', type=int,\n        help='Number of masters, these instances will not run workloads, master components only'\n    )\n    gce_parser.add_argument(\n        '--nodes', dest='nodes_count', type=int,\n        help='Number of nodes', required=True\n    )\n    gce_parser.set_defaults(func=gce)\n\n    # openstack\n    openstack_parser = subparsers.add_parser(\n        'openstack', parents=[parent_parser, firststep_parser],\n        help='Create OpenStack instances and generate inventory'\n    )\n    openstack_parser.add_argument(\n        '--os_auth_url', dest='os_auth_url', help='OpenStack authentication URL'\n    )\n    openstack_parser.add_argument(\n        '--os_username', dest='os_username', help='OpenStack Username'\n    )\n    openstack_parser.add_argument(\n        '--os_project_name', dest='os_project_name',\n        help='OpenStack Project Name'\n    )\n    openstack_parser.add_argument(\n        '--os_region_name', dest='os_region_name', help='OpenStack Region Name',\n        required=False\n    )\n    openstack_parser.add_argument(\n        '--os_password', dest='os_password', help='OpenStack Password'\n    )\n    openstack_parser.add_argument(\n        '--etcd', dest='etcds_count', type=int,\n        help='Number of etcd, these instances will just act as etcd members'\n    )\n    openstack_parser.add_argument(\n        '--masters', dest='masters_count', type=int,\n        help='Number of masters, these instances will not run workloads, master components only'\n    )\n    openstack_parser.add_argument(\n        '--nodes', dest='nodes_count', type=int,\n        help='Number of nodes', required=True\n    )\n    openstack_parser.add_argument(\n        '--sshkey', dest='sshkey', help='Name of saved SSH Keypair'\n    )\n    openstack_parser.add_argument(\n        '-N', '--kube-network', dest='kube_network', default='10.233.0.0/16',\n        help=\"\"\"Network to be used inside the cluster (/16),\n             (must not overlap with any of your infrastructure networks and should be the same as in deploy).\n             default: 10.233.0.0/16\"\"\"\n    )\n    openstack_parser.add_argument(\n        '--add', dest='add_node', action='store_true', default=False,\n        help='Add node to an existing cluster')\n    openstack_parser.add_argument(\n        '--network', dest='network', help='Neutron network name'\n    )\n    openstack_parser.add_argument(\n        '--masters-flavor', dest='masters_flavor',\n        help='OpenStack instance flavor for Masters'\n    )\n    openstack_parser.add_argument(\n        '--nodes-flavor', dest='nodes_flavor',\n        help='OpenStack instance flavor for Nodes'\n    )\n    openstack_parser.add_argument(\n        '--etcds-flavor', dest='etcds_flavor',\n        help='OpenStack instance flavor for Etcd members'\n    )\n    openstack_parser.add_argument('--image', dest='image', help='Instance boot image')\n    openstack_parser.add_argument(\n        '--floating_ip', dest='floating_ip', action='store_true',\n        required=False, help='Associate public IP to instances'\n    )\n    openstack_parser.add_argument(\n        '--cluster-name', dest='cluster_name', help='Name of the cluster'\n    )\n    openstack_parser.set_defaults(func=openstack)\n\n    # deploy\n    deploy_parser = subparsers.add_parser(\n        'deploy', parents=[parent_parser],\n        help='Create GCE machines and generate inventory'\n    )\n    deploy_parser.add_argument(\n        '--verbose', default=False, action='store_true',\n        help=\"Run Ansible playbook in verbose mode '-vvvv'\"\n    )\n    deploy_parser.add_argument(\n        '-k', '--sshkey', dest='ssh_key',\n        help='ssh key for authentication on remote servers'\n    )\n    deploy_parser.add_argument(\n        '-K', '--ask-become-pass', default=False, action='store_true', dest='ask_become_pass',\n        help='ask for privilege escalation password'\n    )\n    deploy_parser.add_argument(\n        '-u', '--user', dest='ansible_user', default=getpass.getuser(),\n        help='Ansible SSH user (remote user)'\n    )\n    deploy_parser.add_argument(\n        '--passwd', dest='k8s_passwd',\n        help=\"Set the 'kube' passwd to authenticate to the API (default changeme')\"\n    )\n    deploy_parser.add_argument(\n        '-P', '--prompt-passwd', default=False, action='store_true', dest='prompt_pwd',\n        help=\"Set the 'kube' passwd to authenticate to the API (Interactive mode)\"\n    )\n    deploy_parser.add_argument(\n        '-V', '--kube-version', dest='kube_version',\n        help='Choose the kubernetes version to be installed'\n    )\n    deploy_parser.add_argument(\n        '-N', '--kube-network', dest='kube_network',\n        help=\"\"\"Network to be used inside the cluster (/16),\n             (must not overlap with any of your infrastructure networks).\n             default: 10.233.0.0/16\"\"\"\n    )\n    deploy_parser.add_argument(\n        '-n', '--network-plugin',\n        choices=['flannel', 'weave', 'calico', 'canal', 'contiv', 'cloud'],\n        help='Inventory defaults to calico'\n    )\n    deploy_parser.add_argument(\n        '--apps', dest='apps_enabled', metavar='N', nargs='+', default=[],\n        help='''List of optional applications to be installed,\n             Possible values: helm, netchecker, efk'''\n    )\n    deploy_parser.add_argument(\n        '--aws', default=False, action='store_true',\n        help='Kubernetes deployment on AWS'\n    )\n    deploy_parser.add_argument(\n        '--gce', default=False, action='store_true',\n        help='Kubernetes deployment on GCE'\n    )\n    deploy_parser.add_argument(\n        '--redhat', default=False, action='store_true',\n        help='bootstrap python on RHEL 7 and newer'\n    )\n    deploy_parser.add_argument(\n        '--coreos', default=False, action='store_true',\n        help='bootstrap python on CoreOS'\n    )\n    deploy_parser.add_argument(\n            '--ubuntu', default=False, action='store_true',\n            help='bootstrap python on Ubuntu 16.04 and newer'\n    )\n    deploy_parser.add_argument(\n        '--ansible-opts', dest='ansible_opts',\n        help='Ansible options'\n    )\n    deploy_parser.set_defaults(func=deploy)\n\n    # Parse arguments\n    args = parser.parse_args()\n    if args.configfile is None:\n        default_config_dir = os.path.expanduser(\"~\")\n        if not os.path.isdir(default_config_dir):\n            os.makedirs(default_config_dir)\n        args.configfile = os.path.join(default_config_dir, \".kubespray.yml\")\n    # Read configfile and update options dict\n    C = Config(args.configfile)\n    configfile_content = C.parse_configfile\n    config = C.default_values(args, configfile_content)\n    # Run functions with all the options\n    os.environ['ANSIBLE_FORCE_COLOR'] = 'true'\n    args.func(config)\n"
  },
  {
    "path": "setup.cfg",
    "content": "[metadata]\ndescription-file = README.md\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nfrom setuptools import setup, find_packages\n\nrequirements = [\n    'cffi>=1.6.0',\n    'setuptools>=11.3',\n    'cryptography>=1.3.2',\n    'requests>=2.4.3',\n    'netaddr>=0.7.18',\n    'markupsafe>=0.23',\n    'pyasn1>=0.1.8',\n    'boto>=2.40.0',\n    'apache-libcloud>=0.20.1'\n]\n\ntest_requirements = [\n    # TODO: put package test requirements here\n]\n\nmy_homedir = os.path.expanduser(\"~\")\n\nsetup(\n    name='kubespray',\n    version='0.5.2',\n    description=\"Kubespray kubernetes cluster deployment\",\n    author=\"Smaine Kahlouch\",\n    author_email='smainklh@gmail.com',\n    url='https://github.com/kubespray/kubespray-cli',\n    data_files=[\n        (my_homedir, ['src/kubespray/files/.kubespray.yml'])\n    ],\n    packages=find_packages('src'),\n    scripts=[\n        'bin/kubespray'\n    ],\n    package_dir={'': 'src'},\n    package_data={'kubespray': ['files/*.yml'], },\n    install_requires=requirements,\n    license=\"GPLv3\",\n    zip_safe=False,\n    keywords='kubespray',\n    classifiers=[\n        'Development Status :: 2 - Pre-Alpha',\n        'Intended Audience :: Developers',\n        'Natural Language :: English',\n        \"Programming Language :: Python :: 2\",\n        'Programming Language :: Python :: 2.7',\n    ],\n    test_suite='tests',\n    tests_require=test_requirements\n)\n"
  },
  {
    "path": "src/kubespray/__init__.py",
    "content": "# (c) 2016, Smaine Kahlouch <smainklh@gmail.com>\n__author__ = 'smana'\n__version__ = '0.5.2'\n"
  },
  {
    "path": "src/kubespray/cloud.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    Foobar is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nkubespray.cloud\n~~~~~~~~~~~~\n\nRun Instances on cloud providers and generate inventory\n\"\"\"\n\nimport sys\nimport os\nimport yaml\nimport json\nfrom kubespray.inventory import CfgInventory\nfrom kubespray.common import get_logger, query_yes_no, run_command, which, id_generator, get_cluster_name\nfrom ansible.utils.display import Display\ndisplay = Display()\nplaybook_exec = which('ansible-playbook')\n\ntry:\n    import configparser\nexcept ImportError:\n    import ConfigParser as configparser\n\n\nclass Cloud(object):\n    '''\n    Run Instances on cloud providers and generates inventory\n    '''\n    def __init__(self, options, cloud):\n        self.options = options\n        self.cloud = cloud\n        self.inventorycfg = options['inventory_path']\n        self.playbook = os.path.join(options['kubespray_path'], 'local.yml')\n        self.cparser = configparser.ConfigParser(allow_no_value=True)\n        self.Cfg = CfgInventory(options, cloud)\n        self.localcfg = os.path.join(\n            options['kubespray_path'],\n            'inventory/local.cfg'\n        )\n        self.instances = {'masters':\n                          {'file': os.path.join(\n                           options['kubespray_path'], 'masters_instances.json'),\n                           'json': None\n                           },\n                          'nodes':\n                          {'file': os.path.join(\n                           options['kubespray_path'], 'nodes_instances.json'),\n                           'json': None\n                           },\n                          'etcds':\n                          {'file': os.path.join(\n                           options['kubespray_path'], 'etcds_instances.json'),\n                           'json': None\n                           },\n                          }\n        self.logger = get_logger(\n            options.get('logfile'),\n            options.get('loglevel')\n        )\n        self.pbook_content = [{\n            'gather_facts': False,\n            'hosts': 'localhost',\n            'become': False,\n            'tasks': []\n        }]\n        self.logger.debug('''\n             The following options were used to generate the inventory: %s\n             ''' % self.options)\n\n    def write_local_inventory(self):\n        '''Generates inventory for local tasks'''\n        self.cparser.add_section('local')\n        self.cparser.set(\n            'local',\n            'localhost ansible_python_interpreter=python2 ansible_connection=local'\n        )\n        try:\n            with open(self.localcfg, 'wb') as f:\n                self.cparser.write(f)\n        except IOError as e:\n            display.error(\n                'Cannot write inventory %s: %s'\n                % (self.localcfg, e)\n            )\n            sys.exit(1)\n\n    def write_playbook(self):\n        '''Write the playbook for instances creation'''\n        try:\n            with open(self.playbook, \"w\") as pb:\n                pb.write(yaml.dump(self.pbook_content, default_flow_style=True))\n        except IOError as e:\n            display.error(\n                'Cant write the playbook %s: %s'\n                % (self.playbook, e)\n            )\n            sys.exit(1)\n\n    def write_inventory(self):\n        '''Generate the inventory according the instances created'''\n        for role in ['masters', 'nodes', 'etcds']:\n            if '%s_count' % role in self.options.keys():\n                with open(self.instances['%s' % role]['file']) as f:\n                    self.instances['%s' % role]['json'] = json.load(f)\n            else:\n                self.instances['%s' % role]['json'] = []\n        self.Cfg.write_inventory(self.instances['masters']['json'], self.instances['nodes']['json'], self.instances['etcds']['json'])\n\n    def create_instances(self):\n        '''Run ansible-playbook for instances creation'''\n        cmd = [\n            playbook_exec, '-i', self.localcfg, '-e',\n            'ansible_connection=local', self.playbook\n        ]\n        if not self.options['assume_yes']:\n            count = 0\n            for role in ['masters', 'nodes', 'etcds']:\n                if '%s_count' % role in self.options.keys():\n                    count = count + self.options['%s_count' % role]\n            if self.options['add_node']:\n                display.warning(\n                    '%s node(s) will be added to the current inventory %s' %\n                    (count, self.inventorycfg)\n                )\n            if not query_yes_no('Create %s instances on %s ?' % (count, self.cloud)):\n                display.display('Aborted', color='red')\n                sys.exit(1)\n        rcode, emsg = run_command('Create %s instances' % self.cloud, cmd)\n        if rcode != 0:\n            self.logger.critical('Cannot create instances: %s' % emsg)\n            sys.exit(1)\n\n\nclass AWS(Cloud):\n\n    def __init__(self, options):\n        Cloud.__init__(self, options, \"aws\")\n        self.options = options\n\n    def gen_ec2_playbook(self):\n        data = self.options\n        data.pop('func')\n        # Options list of ansible EC2 module\n        self.options['image'] = self.options['ami']\n        if 'security_group_id' in self.options.keys():\n            self.options['group_id'] = self.options['security_group_id']\n        if 'security_group_name' in self.options.keys():\n            self.options['group'] = self.options['security_group_name']\n        if 'tags' in self.options:\n            self.options['instance_tags'] = {}\n            for kv in self.options['tags']:\n                k, v = kv.split(\"=\")\n                self.options['instance_tags'][k] = v\n        ec2_options = [\n            'aws_access_key', 'aws_secret_key', 'count', 'group_id',\n            'group', 'instance_type', 'instance_profile_name', 'key_name', 'vpc_subnet_id',\n            'image', 'instance_tags', 'assign_public_ip', 'region'\n        ]\n        # Define EC2 task\n        for role in ['masters', 'nodes', 'etcds']:\n            if '%s_count' % role in self.options.keys():\n                ec2_task = {'ec2': {},\n                            'name': 'Provision EC2 %s instances' % role,\n                            'register': 'ec2_%s' % role}\n                for opt in ec2_options:\n                    if opt in self.options.keys():\n                        d = {opt: self.options[opt]}\n                        ec2_task['ec2'].update(d)\n                ec2_task['ec2'].update({'count': self.options['%s_count' % role]})\n                ec2_task['ec2'].update({'instance_type': self.options['%s_instance_type' % role]})\n                ec2_task['ec2'].update({'instance_profile_name': self.options['%s_instance_profile_name' % role]})\n                ec2_task['ec2'].update({'wait': True})\n                self.pbook_content[0]['tasks'].append(ec2_task)\n                # Write ec2 instances json\n                self.pbook_content[0]['tasks'].append(\n                    {'name': 'Generate a file with ec2 instances list',\n                     'copy':\n                         {'dest': '%s' % self.instances['%s' % role]['file'],\n                          'content': '{{ec2_%s.instances}}' % role}}\n                )\n                # Wait for ssh task\n                if self.options['use_private_ip']:\n                    instance_ip = '{{ item.private_ip }}'\n                else:\n                    instance_ip = '{{ item.public_ip }}'\n                self.pbook_content[0]['tasks'].append(\n                    {'local_action': {'host': '%s' % instance_ip,\n                                      'module': 'wait_for',\n                                      'port': 22,\n                                      'state': 'started',\n                                      'timeout': 600},\n                     'name': 'Wait until SSH is available',\n                     'with_items': '{{ec2_%s.instances}}' % role}\n                )\n        self.write_local_inventory()\n        self.write_playbook()\n\n\nclass GCE(Cloud):\n\n    def __init__(self, options):\n        Cloud.__init__(self, options, \"gce\")\n        self.options = options\n\n    def gen_gce_playbook(self):\n        data = self.options\n        data.pop('func')\n        if 'tags' in self.options:\n            self.options['tags'] = ','.join(self.options['tags'])\n        # Options list of ansible GCE module\n        gce_options = [\n            'machine_type', 'image', 'zone', 'service_account_email',\n            'pem_file', 'credentials_file', 'project_id', 'tags', 'network', 'subnetwork'\n        ]\n        # Define instance names\n        cluster_name = 'k8s-' + get_cluster_name()\n        for role in ['masters', 'nodes', 'etcds']:\n            gce_instance_names = list()\n            if '%s_count' % role in self.options.keys():\n                for x in range(self.options['%s_count' % role]):\n                    if self.options['add_node']:\n                        current_inventory = self.Cfg.read_inventory()\n                        cluster_name = '-'.join(\n                            current_inventory['all']['hosts'][0]['hostname'].split('-')[:-2]\n                        )\n                        gce_instance_names.append(\n                            cluster_name + '-%s' % id_generator()\n                        )\n                    elif 'cluster_name' in self.options.keys():\n                        gce_instance_names.append(\n                            self.options['cluster_name'] + '-%s' % id_generator()\n                        )\n                    else:\n                        gce_instance_names.append(\n                            cluster_name + '-%s' % id_generator()\n                        )\n                gce_instance_names = ','.join(gce_instance_names)\n                # Define GCE task\n                gce_task = {'gce': {},\n                            'name': 'Provision GCE %s instances' % role,\n                            'register': 'gce_%s' % role}\n                for opt in gce_options:\n                    if opt in self.options.keys():\n                        d = {opt: self.options[opt]}\n                        gce_task['gce'].update(d)\n                gce_task['gce'].update({'machine_type': self.options['%s_machine_type' % role]})\n                gce_task['gce'].update({'instance_names': '%s' % gce_instance_names})\n                self.pbook_content[0]['tasks'].append(gce_task)\n                # Write gce instances json\n                self.pbook_content[0]['tasks'].append(\n                    {'name': 'Generate a file with %s list' % role,\n                     'copy':\n                         {'dest': '%s' % self.instances['%s' % role]['file'],\n                          'content': '{{gce_%s.instance_data}}' % role}}\n                )\n                # Wait for ssh task\n                if self.options['use_private_ip']:\n                    instance_ip = '{{ item.private_ip }}'\n                else:\n                    instance_ip = '{{ item.public_ip }}'\n\n                self.pbook_content[0]['tasks'].append(\n                    {'local_action': {'host': '%s' % instance_ip,\n                                      'module': 'wait_for',\n                                      'port': 22,\n                                      'state': 'started',\n                                      'timeout': 600},\n                     'name': 'Wait until SSH is available',\n                     'with_items': '{{gce_%s.instance_data}}' % role}\n                )\n        self.write_local_inventory()\n        self.write_playbook()\n\n\nclass OpenStack(Cloud):\n    def __init__(self, options):\n        Cloud.__init__(self, options, 'openstack')\n        self.options = options\n\n    def gen_openstack_playbook(self):\n        data = self.options\n        data.pop('func')\n\n        openstack_credential_args = ('auth_url', 'username', 'password', 'project_name')\n        openstack_auth = {}\n\n        for cred_arg in openstack_credential_args:\n            openstack_auth.update({cred_arg: self.options['os_%s' % cred_arg]})\n\n        if 'os_domain_name' in self.options:\n            openstack_auth.update({'domain_name': self.options['os_domain_name']})\n\n        if self.options['floating_ip']:\n            ip_type = 'public'\n        else:\n            ip_type = 'private'\n\n        # Define instance names\n        cluster_name = 'k8s-' + get_cluster_name()\n        if 'cluster_name' in self.options.keys():\n            cluster_name = 'k8s-' + self.options['cluster_name']\n        os_security_group_name = cluster_name + '-%s' % id_generator()\n\n        self.pbook_content[0]['tasks'].append(\n            {'name': 'Create security group',\n               'os_security_group': {\n                   'auth': openstack_auth,\n                   'name': os_security_group_name,\n                   'description': 'Contains security rules for the Kubernetes cluster',\n                   'region_name': self.options['os_region_name'],\n                   'state': 'present'}}\n        )\n        self.pbook_content[0]['tasks'].append(\n            {'name': 'Add security rules',\n               'os_security_group_rule': {\n                   'auth': openstack_auth,\n                   'security_group': os_security_group_name,\n                   'protocol': '{{item}}',\n                   'region_name': self.options['os_region_name'],\n                   'state': 'present'},\n               'with_items': ['tcp', 'udp', 'icmp']}\n        )\n\n        for role in ('masters', 'nodes', 'etcds'):\n            os_instance_names = list()\n            if '%s_count' % role in self.options.keys():\n                for x in range(self.options['%s_count' % role]):\n                    if self.options['add_node']:\n                        current_inventory = self.Cfg.read_inventory()\n                        cluster_name = '-'.join(\n                            current_inventory['all']['hosts'][0]['hostname'].split('-')[:-1]\n                        )\n                        os_instance_names.append(\n                            cluster_name + '-%s' % id_generator()\n                        )\n                    else:\n                        os_instance_names.append(\n                            cluster_name + '-%s' % id_generator()\n                        )\n                self.pbook_content[0]['tasks'].append(\n                    {'name': 'Create %s network ports' % role,\n                       'os_port': {\n                           'auth': openstack_auth,\n                           'name': '{{item}}',\n                           'region_name': self.options['os_region_name'],\n                           'network': self.options['network'],\n                           'allowed_address_pairs': [{'ip_address': self.options['kube_network']}],\n                           'security_groups': [os_security_group_name],\n                           'state': 'present'},\n                       'with_items': os_instance_names}\n                )\n                self.pbook_content[0]['tasks'].append(\n                    {'name': 'Provision OS %s instances' % role,\n                       'os_server': {\n                           'auth': openstack_auth,\n                           'name': '{{item}}',\n                           'state': 'present',\n                           'flavor': self.options['%s_flavor' % role],\n                           'key_name': self.options['sshkey'],\n                           'region_name': self.options['os_region_name'],\n                           'auto_ip': self.options['floating_ip'],\n                           'security_groups': [os_security_group_name],\n                           'nics': 'port-name={{ item }}',\n                           'image': self.options['image']},\n                       'register': 'os_%s' % role,\n                       'with_items': os_instance_names}\n                )\n                # Write os instances json\n                self.pbook_content[0]['tasks'].append(\n                    {'name': 'Generate a file with OS %s instances list' % role,\n                     'copy':\n                         {'dest': '%s' % self.instances[role]['file'],\n                          'content': '{{os_%s.results}}' % role}}\n                )\n                # Wait for ssh task\n                self.pbook_content[0]['tasks'].append(\n                    {'name': 'Wait until SSH is available',\n                       'wait_for': {\n                           'host': '{{item.openstack.%s_v4}}' % ip_type,\n                           'port': 22,\n                           'search_regex': 'SSH',\n                           'state': 'started',\n                           'delay': 10},\n                       'with_items': '{{os_%s.results}}' % role}\n                )\n        self.write_local_inventory()\n        self.write_playbook()\n"
  },
  {
    "path": "src/kubespray/common.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Foobar is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    Foobar is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.\n\nimport logging\nimport shutil\nimport requests\nimport random\nimport os\nimport re\nimport netaddr\nimport sys\nimport string\nimport getpass\nfrom ansible.utils.display import Display\nfrom subprocess import PIPE, STDOUT, Popen, CalledProcessError\ndisplay = Display()\n\n\ndef which(program):\n    def is_exe(fpath):\n        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n    fpath, fname = os.path.split(program)\n    if fpath:\n        if is_exe(program):\n            return program\n    else:\n        for path in os.environ[\"PATH\"].split(os.pathsep):\n            path = path.strip('\"')\n            exe_file = os.path.join(path, program)\n            if is_exe(exe_file):\n                return exe_file\n    return None\n\n\ndef read_password():\n    pw = getpass.getpass(prompt=\"API 'kube' password: \")\n    if len(pw) < 6:\n        display.warning('Password is too short')\n    pw2 = getpass.getpass(prompt=\"Confirm password: \")\n    if pw != pw2:\n        display.error(\"Passwords don't match\")\n        sys.exit(1)\n    return(pw)\n\n\ndef query_yes_no(question, default=\"yes\"):\n    \"\"\"Question user input 'Yes' or 'No'\"\"\"\n    valid = {\"yes\": True, \"y\": True, \"no\": False, \"n\": False}\n    if default is None:\n        prompt = \" [y/n] \"\n    elif default == \"yes\":\n        prompt = \" [Y/n] \"\n    elif default == \"no\":\n        prompt = \" [y/N] \"\n    else:\n        raise ValueError(\"Invalid default answer: '%s'\" % default)\n    while True:\n        sys.stdout.write(question + prompt)\n        choice = raw_input().lower()\n        if default is not None and choice == '':\n            return valid[default]\n        elif choice in valid:\n            return valid[choice]\n        else:\n            sys.stdout.write(\n                \"Please answer with 'yes' or 'no' (or 'y' or 'n').\\n\"\n            )\n\n\ndef get_logger(logfile, loglevel):\n    logger = logging.getLogger()\n    handler = logging.FileHandler(logfile)\n    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n    handler.setFormatter(formatter)\n    logger.addHandler(handler)\n    logger.setLevel(getattr(logging, loglevel.upper()))\n    return logger\n\n\ndef get_cluster_name():\n    try:\n        word_site = \"http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain\"\n        response = requests.get(word_site)\n        words = response.content.splitlines()\n        cluster_name = random.choice(words).decode(\"utf-8\")\n    except:\n        cluster_name = id_generator()\n    if not re.match('^(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)$', cluster_name):\n        get_cluster_name()\n    return(cluster_name.lower())\n\n\ndef clone_kubespray_git_repo(options):\n    if not options['add_node']:\n        if (os.path.isdir(options['kubespray_path']) and not options['assume_yes']\n                and not options['noclone']):\n            display.warning(\n                'A directory %s already exists' % options['kubespray_path']\n            )\n            if not query_yes_no(\n                    'Are you sure to overwrite it ?'\n            ):\n                    display.display('Aborted', color='red')\n                    sys.exit(1)\n        if not options['noclone']:\n            clone_git_repo(\n                'kubespray', options['kubespray_path'], options['kubespray_git_repo']\n            )\n\n\ndef clone_git_repo(name, directory, git_repo):\n    if which('git') is None:\n        display.error('Cannot find git binary! check your installation')\n        sys.exit(1)\n    if os.path.isdir(directory):\n        shutil.rmtree(directory)\n    display.banner('CLONING %s GIT REPO' % name.upper())\n    cmd = [\"git\", \"clone\", git_repo, directory]\n    rcode, emsg = run_command('Clone kubespray repository from github', cmd)\n    if rcode != 0:\n        display.error('Cannot clone kubespray repository from github')\n        sys.exit(1)\n    display.display('%s repo cloned' % name, color='green')\n\n\ndef run_command(description, cmd):\n    '''\n    Execute a system command\n    '''\n    try:\n        proc = Popen(\n            cmd, stdout=PIPE, stderr=STDOUT,\n            universal_newlines=True, shell=False\n        )\n        with proc.stdout:\n            for line in iter(proc.stdout.readline, b''):\n                print(line),\n        proc.wait()\n        return(proc.returncode, None)\n    except CalledProcessError as e:\n        display.error('%s: %s' % (description, e.output))\n        emsg = e.message\n        return(proc.returncode, emsg)\n\n\ndef id_generator(size=6, chars=string.ascii_lowercase + string.digits):\n    return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef validate_cidr(cidr, version):\n    \"\"\"\n    Validates that a CIDR is valid. Returns true if valid, false if\n    not. Version can be \"4\", \"6\", None for \"IPv4\", \"IPv6\", or \"either\"\n    respectively.\n    \"\"\"\n    try:\n        ip = netaddr.IPNetwork(cidr, version=version)\n        return True\n    except (netaddr.core.AddrFormatError, ValueError, TypeError):\n        return False\n"
  },
  {
    "path": "src/kubespray/configure.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    Kubespray is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nkubespray.configure\n~~~~~~~~~~~~\n\nConfiguration management for Kubespray\n\"\"\"\nimport sys\nimport os\nimport yaml\nfrom ansible.utils.display import Display\nfrom kubespray.common import read_password\n\n\nclass Config(object):\n\n    def __init__(self, configfile):\n        self.display = Display()\n        self.configfile = configfile\n        self.logfile = None\n        self.loglevel = None\n\n    @property\n    def parse_configfile(self):\n        \"\"\"\n        Retrieve configuration parameters from the config file\n        \"\"\"\n        try:\n            with open(self.configfile, \"r\") as f:\n                config = yaml.load(f)\n        except:\n            self.display.error(\n                \"Can't read configuration file %s\" % self.configfile\n            )\n            sys.exit(1)\n        return config\n\n    def default_values(self, args, config):\n        # Set kubespray_path\n        if 'kubespray_path' not in config.keys() and args.kubespray_path is None:\n            config['kubespray_path'] = os.path.join(os.path.expanduser(\"~\"), '.kubespray')\n        arguments = dict(args._get_kwargs())\n        for key, value in arguments.items():\n            if value is not None:\n                config[key] = value\n        # Set inventory_path\n        if 'inventory_path' not in config.keys() and args.inventory_path is None:\n            config['inventory_path'] = os.path.join(\n                config['kubespray_path'], 'inventory/inventory.cfg'\n            )\n        # Set logfile\n        if 'logfile' not in config.keys():\n            config['logfile'] = os.path.join(config['kubespray_path'], 'kubespray.log')\n        # Set default bool\n        for v in ['use_private_ip', 'assign_public_ip']:\n            if v not in config.keys():\n                config[v] = False\n        # Set default instances type\n        if args.func.__name__ == \"aws\":\n            if 'masters_instance_type' not in config.keys() and args.masters_instance_type is None:\n                config['masters_instance_type'] = 't2.medium'\n            if 'nodes_instance_type' not in config.keys() and args.nodes_instance_type is None:\n                config['nodes_instance_type'] = 't2.large'\n            if 'etcds_instance_type' not in config.keys() and args.etcds_instance_type is None:\n                config['etcds_instance_type'] = 't2.small'\n        # ----GCE\n        if args.func.__name__ == \"gce\":\n            if 'masters_machine_type' not in config.keys() and args.masters_machine_type is None:\n                config['masters_machine_type'] = 'n1-standard-2'\n            if 'nodes_machine_type' not in config.keys() and args.nodes_machine_type is None:\n                config['nodes_machine_type'] = 'n1-standard-4'\n            if 'etcds_machine_type' not in config.keys() and args.etcds_machine_type is None:\n                config['etcds_machine_type'] = 'n1-standard-1'\n        # Conflicting options\n        if args.func.__name__ == \"aws\":\n            if args.security_group_name and 'security_group_id' in config.keys():\n                config.pop('security_group_id')\n            elif args.security_group_id and 'security_group_name' in config.keys():\n                config.pop('security_group_name')\n        # Set kubernetes 'kube' password\n        if 'prompt_pwd' in config.keys() and config['prompt_pwd'] is True:\n            pwd = read_password()\n            config['k8s_passwd'] = pwd\n        return(config)\n"
  },
  {
    "path": "src/kubespray/deploy.py",
    "content": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Foobar is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    Foobar is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nkubespray.deploy\n~~~~~~~~~~~~\n\nDeploy a kubernetes cluster. Run the ansible-playbbook\n\"\"\"\n\nimport re\nimport sys\nimport os\nimport yaml\nimport signal\nimport netaddr\nfrom subprocess import PIPE, STDOUT, Popen, check_output, CalledProcessError\nfrom kubespray.common import get_logger, query_yes_no, run_command, which, validate_cidr\nfrom ansible.utils.display import Display\ndisplay = Display()\nplaybook_exec = which('ansible-playbook')\nansible_exec = which('ansible')\n\n\nclass RunPlaybook(object):\n    '''\n    Run the Ansible playbook to deploy the kubernetes cluster\n    '''\n    def __init__(self, options):\n        self.existing_ssh_agent = False\n        self.options = options\n        self.inventorycfg = options['inventory_path']\n        self.logger = get_logger(\n            options.get('logfile'),\n            options.get('loglevel')\n        )\n        self.logger.debug(\n            'Running ansible-playbook command with the following options: %s'\n            % self.options\n        )\n\n    def kill_ssh_agent(self):\n        if self.existing_ssh_agent:\n            return\n\n        if 'SSH_AGENT_PID' in os.environ:\n            agent_pid = os.environ.get('SSH_AGENT_PID')\n\n            if agent_pid.isdigit():\n                os.kill(int(agent_pid), signal.SIGTERM)\n\n    def ssh_prepare(self):\n        '''\n        Run ssh-agent and store identities\n        '''\n\n        if 'SSH_AUTH_SOCK' in os.environ:\n            self.existing_ssh_agent = True\n            self.logger.info('Using existing ssh agent')\n            return\n\n        try:\n            sshagent = check_output('ssh-agent')\n        except CalledProcessError as e:\n            display.error('Cannot run the ssh-agent : %s' % e.output)\n        # Set environment variables\n        ssh_envars = re.findall('\\w*=[\\w*-\\/.*]*', sshagent)\n        for v in ssh_envars:\n            os.environ[v.split('=')[0]] = v.split('=')[1]\n        # Store ssh identity\n        try:\n            if 'ssh_key' in self.options.keys():\n                cmd = ['ssh-add', os.path.realpath(self.options['ssh_key'])]\n            else:\n                cmd = 'ssh-add'\n            proc = Popen(\n                cmd, stdout=PIPE, stderr=STDOUT, stdin=PIPE\n            )\n            proc.stdin.write('password\\n')\n            proc.stdin.flush()\n            response_stdout, response_stderr = proc.communicate()\n            display.display(response_stdout)\n        except CalledProcessError as e:\n            display.error('Failed to store ssh identity : %s' % e.output)\n            sys.exit(1)\n        except IOError:\n            display.error('Could not find SSH key. Have you run ssh-keygen?')\n        try:\n            check_output(['ssh-add', '-l'])\n        except CalledProcessError as e:\n            display.error('Failed to list identities : %s' % e.output)\n            sys.exit(1)\n        if response_stderr:\n            display.error(response_stderr)\n            self.logger.critical(\n                'Deployment stopped because of ssh credentials'\n                % self.filename\n            )\n            self.kill_ssh_agent()\n            sys.exit(1)\n\n    def check_ping(self):\n        '''\n         Check if hosts are reachable\n        '''\n        display.banner('CHECKING SSH CONNECTIONS')\n        cmd = [\n            ansible_exec, '--ssh-extra-args', '-o StrictHostKeyChecking=no',\n            '-u', '%s' % self.options['ansible_user'],\n            '-b', '--become-user=root', '-m', 'ping', 'all',\n            '-i', self.inventorycfg\n        ]\n        if 'sshkey' in self.options.keys():\n            cmd = cmd + ['--private-key', self.options['sshkey']]\n        if self.options['ask_become_pass']:\n            cmd = cmd + ['--ask-become-pass']\n        if self.options['coreos']:\n            cmd = cmd + ['-e', 'ansible_python_interpreter=/opt/bin/python']\n        display.display(' '.join(cmd))\n        rcode, emsg = run_command('SSH ping hosts', cmd)\n        if rcode != 0:\n            self.logger.critical('Cannot connect to hosts: %s' % emsg)\n            self.kill_ssh_agent()\n            sys.exit(1)\n        display.display('All hosts are reachable', color='green')\n\n    def get_subnets(self):\n        '''Check the subnet value and split into 2 distincts subnets'''\n        svc_pfx = 17\n        pods_pfx = 17\n        net = netaddr.IPNetwork(self.options['kube_network'])\n        pfx_error_msg = (\n            \"You have to choose a network with a prefix length = 16, \"\n            \"Please use Ansible options if you need to configure a different netmask.\"\n        )\n        if net.prefixlen is not 16:\n            display.error(pfx_error_msg)\n            self.kill_ssh_agent()\n            sys.exit(1)\n        subnets = list(net.subnet(pods_pfx))\n        pods_network, remaining = subnets[0:2]\n        net = netaddr.IPNetwork(remaining)\n        svc_network = list(net.subnet(svc_pfx))[0]\n        return(svc_network, pods_network)\n\n    def read_kube_versions(self):\n        \"\"\"\n        Read the kubernetes versions from karo's vars file\n        \"\"\"\n        kube_vers_file = os.path.join(\n            self.options['kubespray_path'] + '/roles/download/vars/kube_versions.yml'\n        )\n        try:\n            with open(kube_vers_file, \"r\") as f:\n                kube_versions_vars = yaml.load(f)\n        except IOError as e:\n            display.error('Cannot read kube_versions file %s: %s'\n                          % (kube_vers_file, e)\n                          )\n            sys.exit(1)\n        kube_versions = list()\n        for i in kube_versions_vars['kube_checksum']:\n            kube_versions.append(i)\n        return kube_versions\n\n    def deploy_kubernetes(self):\n        '''\n        Run the ansible playbook command\n        '''\n        cmd = [\n            playbook_exec, '--ssh-extra-args', '-o StrictHostKeyChecking=no',\n            '-u',  '%s' % self.options['ansible_user'],\n            '-b', '--become-user=root', '-i', self.inventorycfg,\n            os.path.join(self.options['kubespray_path'], 'cluster.yml')\n        ]\n        # Configure network plugin if defined\n        if 'network_plugin' in self.options.keys():\n            cmd = cmd + ['-e',\n                'kube_network_plugin=%s' % self.options['network_plugin']\n                ]\n        # Configure the network subnets pods and k8s services\n        if 'kube_network' in self.options.keys():\n            if not validate_cidr(self.options['kube_network'], version=4):\n                display.error('Invalid Kubernetes network address')\n                self.kill_ssh_agent()\n                sys.exit(1)\n            svc_network, pods_network = self.get_subnets()\n            cmd = cmd + [\n                '-e', 'kube_service_addresses=%s' % svc_network.cidr,\n                '-e', 'kube_pods_subnet=%s' % pods_network\n            ]\n        # Check optional apps\n        if 'apps_enabled' in self.options.keys():\n            for app in self.options['apps_enabled']:\n                if app not in ['helm', 'netchecker', 'efk']:\n                    display.error(\n                        'The application %s is not available, possible values = %s' %\n                        (app, ','.join(self.options['apps_enabled']))\n                    )\n                    sys.exit(1)\n                if app == \"netchecker\":\n                    cmd = cmd + ['-e', 'deploy_netchecker=true']\n                else:\n                    cmd = cmd + ['-e', '%s_enabled=true' % app]\n        # Set kubernetes version\n        if 'kube_version' in self.options.keys():\n            available_kube_versions = self.read_kube_versions()\n            if self.options['kube_version'] not in available_kube_versions:\n                display.error(\n                    'Kubernetes version %s is not supported, available versions = %s' %\n                    (self.options['kube_version'], ','.join(available_kube_versions))\n                )\n                sys.exit(1)\n            cmd = cmd + ['-e', 'kube_version=%s' % self.options['kube_version']]\n        # Bootstrap\n        if 'coreos' in self.options.keys() and self.options['coreos']:\n            cmd = cmd + ['-e', 'bootstrap_os=coreos']\n        elif 'redhat' in self.options.keys() and self.options['redhat']:\n            cmd = cmd + [\n                '-e', 'bootstrap_os=centos', '-e', 'ansible_os_family=RedHat'\n            ]\n        elif 'ubuntu' in self.options.keys() and self.options['ubuntu']:\n            cmd = cmd + ['-e', 'bootstrap_os=ubuntu']\n        # Add root password for the apiserver\n        if 'k8s_passwd' in self.options.keys():\n            cmd = cmd + ['-e', 'kube_api_pwd=%s' % self.options['k8s_passwd']]\n        # Ansible verbose mode\n        if 'verbose' in self.options.keys() and self.options['verbose']:\n            cmd = cmd + ['-vvvv']\n        # Add privilege escalation password\n        if self.options['ask_become_pass']:\n            cmd = cmd + ['--ask-become-pass']\n        # Add any additionnal Ansible option\n        if 'ansible_opts' in self.options.keys():\n            cmd = cmd + self.options['ansible_opts'].split(' ')\n        for cloud in ['aws', 'gce']:\n            if self.options[cloud]:\n                cmd = cmd + ['-e', 'cloud_provider=%s' % cloud]\n        self.check_ping()\n        if 'kube_network' in self.options.keys():\n            display.display(\n                'Kubernetes services network : %s (%s IPs)'\n                % (svc_network.cidr, str(svc_network.size.real - 2)),\n                color='bright gray'\n            )\n            display.display(\n                'Pods network : %s (%s IPs)'\n                % (pods_network.cidr, str(pods_network.size.real - 2)),\n                color='bright gray'\n            )\n        display.display(' '.join(cmd), color='bright blue')\n        if not self.options['assume_yes']:\n            if not query_yes_no(\n                'Run kubernetes cluster deployment with the above command ?'\n            ):\n                display.display('Aborted', color='red')\n                sys.exit(1)\n        display.banner('RUN PLAYBOOK')\n        self.logger.info(\n            'Running kubernetes deployment with the command: %s' % ' '.join(cmd)\n        )\n        rcode, emsg = run_command('Run deployment', cmd)\n        if rcode != 0:\n            self.logger.critical('Deployment failed: %s' % emsg)\n            self.kill_ssh_agent()\n            sys.exit(1)\n        display.display('Kubernetes deployed successfuly', color='green')\n        self.kill_ssh_agent()\n"
  },
  {
    "path": "src/kubespray/files/.kubespray.yml",
    "content": "---\n# Path where the kubespray ansible playbooks will be installed\n# Defaults to current user's home directory if not set\n# kubespray_path: \"~/.kubespray\"\n\n# Default inventory path\nkubespray_git_repo: \"https://github.com/kubespray/kubespray.git\"\n\n# Logging options\nloglevel: \"info\"\n\n# The following options would be overwritten by the command line\n# ---------------------------------------------------------\n#\n# Amazon web services options\n# ---\n# aws_access_key: \"<key>\"\n# aws_secret_key: \"<secret_key>\"\n# key_name: \"<keypair_name>\"\n# ami: \"<aws_ami>\"\n# masters_instance_type: \"<masters_instance_type>\"\n# nodes_instance_type: \"<nodes_instance_type>\"\n# etcds_instance_type: \"<etcds_instance_type>\"\n# security_group_name: \"<security_group_name>\"\n# security_group_id: \"<security_group_id>\"\n# assign_public_ip: True\n# use_private_ip: true\n# vpc_subnet_id: \"<vpc_id>\"\n# region: \"<aws_region>\"\n# tags:\n#   - type: k8s\n#\n# Google Compute Engine options\n# ---\n# image: \"<cloud_image>\"\n# masters_machine_type: \"<masters_type>\n# nodes_machine_type: \"<masters_type>\n# etcds_machine_type: \"<masters_type>\n# service_account_email: \"<gce_service_account_email>\"\n# pem_file: \"<gce_pem_file>\"\n# project_id: \"<gce_project_id>\"\n# network: \"<gce_network_name>\"\n# subnetwork: \"<gce_subnetwork_name>\"\n# use_private_ip: true\n# zone: \"<cloud_region>\"\n# tags:\n#   - k8s\n#\n# OpenStack options\n# ---\n# os_auth_url: \"<os_auth_url>\"\n# os_username: \"<os_username>\"\n# os_password: \"<os_password>\"\n# os_project_name: \"<os_project_name>\"\n# os_region_name: \"<os_region_name>\"\n# os_domain_name: \"<os_domain_name>\"\n# masters_flavor: \"<os_flavor_name_or_id>\"\n# nodes_flavor: \"<os_flavor_name_or_id>\"\n# etcds_flavor: \"<os_flavor_name_or_id>\"\n# image: \"<os_image_name_or_id>\"\n# network: \"<os_network_name_or_id>\"\n# sshkey: \"<os_ssh_key_name>\"\n#\n# All the options to be passed to the 'ansible-playbook' command line\n# Note: 'serial=1' ansible option is a workaround for bug https://github.com/ansible/ansible/issues/17935 which causes installation to hang due to SSH multiplexing\n# ansible-opts:\n#   - 'serial=1'\n#   - '-vvv'\n#   - '-e'\n#   - 'myvar1=bar'\n#   - '-e'\n#   - 'myvar2=foo'\n"
  },
  {
    "path": "src/kubespray/inventory.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This file is part of Kubespray.\n#\n#    Kubespray is free software: you can redistribute it and/or modify\n#    it under the terms of the GNU General Public License as published by\n#    the Free Software Foundation, either version 3 of the License, or\n#    (at your option) any later version.\n#\n#    Foobar is distributed in the hope that it will be useful,\n#    but WITHOUT ANY WARRANTY; without even the implied warranty of\n#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#    GNU General Public License for more details.\n#\n#    You should have received a copy of the GNU General Public License\n#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"\nkubespray.inventory\n~~~~~~~~~~~~\n\nAnsible inventory management for Kubespray\n\"\"\"\n\nimport sys\nimport re\nfrom kubespray.common import get_logger, id_generator, get_cluster_name\nfrom ansible.utils.display import Display\ndisplay = Display()\n\ntry:\n    import configparser\nexcept ImportError:\n    import ConfigParser as configparser\n\n\nclass CfgInventory(object):\n    '''\n    Read classic ansible inventory file.\n    '''\n\n    def __init__(self, options, platform):\n        self.options = options\n        self.platform = platform\n        self.inventorycfg = options['inventory_path']\n        self.logger = get_logger(options.get('logfile'), options.get('loglevel'))\n        self.cparser = configparser.ConfigParser(allow_no_value=True)\n        self.inventory = {'all': {'hosts': []},\n                          'kube-master': {'hosts': []},\n                          'etcd': {'hosts': []},\n                          'kube-node': {'hosts': []},\n                          'k8s-cluster:children': {'hosts': [\n                              {'hostname': 'kube-node', 'hostvars': []},\n                              {'hostname': 'kube-master', 'hostvars': []}\n                          ]},\n                          }\n\n    def read_inventory(self):\n        read_cparser = configparser.ConfigParser(allow_no_value=True)\n        try:\n            read_cparser.read(self.inventorycfg)\n        except IOError as e:\n            display.error('Cannot read configuration %s: %s'\n                          % (self.options['inventory_path'], e)\n                          )\n            sys.exit(1)\n        expected_sections = ['kube-node', 'kube-master', 'all', 'etcd', 'k8s-cluster:children']\n        for k in expected_sections:\n            if k not in read_cparser.sections():\n                display.error(\n                    'The config file %s doesn\\'t have a section named %s'\n                    % (self.options['inventory_path'], k)\n                )\n                sys.exit(1)\n        current_inventory = {'all': {'hosts': []},\n                             'kube-master': {'hosts': []},\n                             'etcd': {'hosts': []},\n                             'kube-node': {'hosts': []},\n                             'k8s-cluster:children': {'hosts': [\n                                 {'hostname': 'kube-node', 'hostvars': []},\n                                 {'hostname': 'kube-master', 'hostvars': []}\n                             ]},\n                             }\n        for section in current_inventory.keys():\n            for line, properties_str in read_cparser.items(section):\n                machine_part = line.split('#', 1)[0]  # get rid of comments parts\n                machine_part = line.split(None, 1)\n                inventory_hostname = machine_part[0]\n                host_dict = {'hostname': '', 'hostvars': []}\n                hostvars = []\n                if len(machine_part) == 2:\n                    if properties_str:\n                        properties_str = machine_part[1] + '=' + properties_str\n                    else:\n                        properties_str = machine_part[1]\n                    for hostvar in properties_str.split():\n                        name, value = hostvar.split('=')\n                        d = {'name': name, 'value': value}\n                        hostvars.append(d)\n                host_dict['hostname'] = inventory_hostname\n                host_dict['hostvars'] = hostvars\n                current_inventory[section]['hosts'].append(host_dict)\n        return(current_inventory)\n\n    def format_inventory(self, masters, nodes, etcds):\n        new_inventory = {'all': {'hosts': []},\n                         'kube-master': {'hosts': []},\n                         'etcd': {'hosts': []},\n                         'kube-node': {'hosts': []},\n                         'k8s-cluster:children': {'hosts': [\n                             {'hostname': 'kube-node', 'hostvars': []},\n                             {'hostname': 'kube-master', 'hostvars': []}\n                             ]},\n                         }\n\n        if self.platform == 'openstack':\n            if self.options['floating_ip']:\n                ip_type = 'public_v4'\n            else:\n                ip_type = 'private_v4'\n            # handle masters\n            new_instances = []\n            for master in masters:\n                new_instances.append({'public_ip': master['openstack'][ip_type],\n                                      'name': master['item']})\n            masters = new_instances\n            # handle nodes\n            new_instances = []\n            for node in nodes:\n                new_instances.append({'public_ip': node['openstack'][ip_type],\n                                      'name': node['item']})\n            nodes = new_instances\n            # handle etcds\n            new_instances = []\n            for etcd in etcds:\n                new_instances.append({'public_ip': etcd['openstack'][ip_type],\n                                      'name': etcd['item']})\n            etcds = new_instances\n\n        if not self.options['add_node']:\n            if not masters and len(nodes) == 1:\n                masters = [nodes[0]]\n            elif not masters:\n                masters = nodes[0:2]\n            if not etcds and len(nodes) >= 3:\n                etcds = nodes[0:3]\n            elif not etcds and len(nodes) < 3:\n                etcds = [nodes[0]]\n            elif etcds and len(etcds) < 3:\n                etcds = [etcds[0]]\n\n        if self.platform in ['aws', 'gce', 'openstack']:\n            if self.options['add_node']:\n                current_inventory = self.read_inventory()\n                cluster_name = '-'.join(\n                    current_inventory['all']['hosts'][0]['hostname'].split('-')[:-1]\n                )\n                new_inventory = current_inventory\n            else:\n                cluster_name = 'k8s-' + get_cluster_name()\n            if self.options['use_private_ip']:\n                instance_ip = 'private_ip'\n            else:\n                instance_ip = 'public_ip'\n            for host in nodes + masters + etcds:\n                if self.platform == 'aws':\n                    host['name'] = \"%s-%s\" % (cluster_name, id_generator(5))\n                new_inventory['all']['hosts'].append(\n                    {'hostname': '%s' % host['name'], 'hostvars': [\n                        {'name': 'ansible_ssh_host', 'value': host[instance_ip]}\n                        ]}\n                )\n            if not self.options['add_node']:\n                for host in nodes:\n                    new_inventory['kube-node']['hosts'].append(\n                        {'hostname': '%s' % host['name'],\n                         'hostvars': []}\n                    )\n                for host in masters:\n                    new_inventory['kube-master']['hosts'].append(\n                        {'hostname': '%s' % host['name'],\n                         'hostvars': []}\n                    )\n                for host in etcds:\n                    new_inventory['etcd']['hosts'].append(\n                        {'hostname': '%s' % host['name'],\n                         'hostvars': []}\n                    )\n        elif self.platform == 'metal':\n            for host in nodes + masters + etcds:\n                if '[' in host:\n                    r = re.search('(^.*)\\[(.*)\\]', host)\n                    inventory_hostname = r.group(1)\n                    var_str = r.group(2)\n                    hostvars = list()\n                    for var in var_str.split(','):\n                        hostvars.append({'name': var.split('=')[0], 'value': var.split('=')[1]})\n                else:\n                    inventory_hostname = host\n                    hostvars = []\n                new_inventory['all']['hosts'].append(\n                    {'hostname': inventory_hostname, 'hostvars': hostvars}\n                )\n            for host in nodes:\n                new_inventory['kube-node']['hosts'].append(\n                    {'hostname': host.split('[')[0], 'hostvars': []}\n                )\n            for host in masters:\n                new_inventory['kube-master']['hosts'].append(\n                    {'hostname': host.split('[')[0], 'hostvars': []}\n                )\n            for host in etcds:\n                new_inventory['etcd']['hosts'].append(\n                    {'hostname': host.split('[')[0], 'hostvars': []}\n                )\n        return(new_inventory)\n\n    def write_inventory(self, masters, nodes, etcds):\n        '''Generates inventory'''\n        inventory = self.format_inventory(masters, nodes, etcds)\n        if not self.options['add_node']:\n            if (('masters_count' in self.options.keys() and len(masters) < 2) or\n               ('masters_count' not in self.options.keys() and len(nodes) < 2)):\n                display.warning('You should set at least 2 masters')\n            if (('etcds_count' in self.options.keys() and len(etcds) < 3) or\n               ('etcds_count' not in self.options.keys() and len(nodes) < 3)):\n                display.warning('You should set at least 3 nodes for etcd clustering')\n        open(self.inventorycfg, 'w').close()\n        for key, value in inventory.items():\n            self.cparser.add_section(key)\n            for host in value['hosts']:\n                hostvars = str()\n                varlist = list()\n                for var in host['hostvars']:\n                    varlist.append(\"%s=%s\" % (var['name'], var['value']))\n                hostvars = \" \".join(varlist)\n                self.cparser.set(key, \"%s\\t\\t%s\" % (host['hostname'], hostvars))\n        with open(self.inventorycfg, 'wb') as configfile:\n            display.banner('WRITTING INVENTORY')\n            self.cparser.write(configfile)\n            self.logger.info(\n                'the inventory %s was successfuly generated'\n                % self.inventorycfg\n            )\n            self.logger.debug(\n                'The following options were used to generate the inventory: %s'\n                % self.options\n            )\n            display.display(\n                'Inventory generated : %s'\n                % self.inventorycfg, color='green'\n            )\n"
  }
]