pax_global_header00006660000000000000000000000064135406701410014513gustar00rootroot0000000000000052 comment=9a7c72a3de4d097af833f816f8e5f4cd6733bca8 lavacli-v0.9.8/000077500000000000000000000000001354067014100133325ustar00rootroot00000000000000lavacli-v0.9.8/.coveragerc000066400000000000000000000001511354067014100154500ustar00rootroot00000000000000[run] source = lavacli branch = True [report] precision = 2 [html] title = lavacli coverage report lavacli-v0.9.8/.gitignore000066400000000000000000000002061354067014100153200ustar00rootroot00000000000000.virtualenv bin dist versiontools-*.egg *.egg-info build .idea *.pyc *~ *.swp tmp*/ _build/ .eggs *.e4p .eric6project/ .pytest_cache/ lavacli-v0.9.8/.gitlab-ci.yml000066400000000000000000000052271354067014100157740ustar00rootroot00000000000000stages: - test - analyze - build - deploy ######## # Test # ######## .test: &test stage: test tags: [amd64] before_script: - apt-get update -qq - apt-get install --no-install-recommends -y python3 python3-jinja2 python3-pytest python3-requests python3-yaml python3-zmq script: - py.test-3 -v --junitxml=lavacli.xml tests artifacts: reports: junit: - lavacli.xml test-debian-8: <<: *test image: debian:8 test-debian-9: <<: *test image: debian:9 test-debian-10: <<: *test image: debian:10 test-debian-11: <<: *test image: debian:bullseye test-ubuntu-18.04: <<: *test image: ubuntu:18.04 test-ubuntu-18.10: <<: *test image: ubuntu:18.10 test-ubuntu-19.04: <<: *test image: ubuntu:19.04 ########### # Analyze # ########### codestyle: stage: analyze image: debian:9 tags: [amd64] before_script: - apt-get update -qq - apt-get install --no-install-recommends -y pycodestyle script: - pycodestyle --ignore=E501,W503 . black: stage: analyze image: debian:buster tags: [amd64] before_script: - apt-get update -qq - apt-get install --no-install-recommends -y python3-pip python3-setuptools - pip3 install black script: - LC_ALL=C.UTF-8 LANG=C.UTF-8 black --check . coverage: stage: analyze image: debian:buster tags: [amd64] before_script: - apt-get update -qq - apt-get install --no-install-recommends -y python3 python3-jinja2 python3-pytest python3-pytest-cov python3-requests python3-yaml python3-zmq coverage: '/^TOTAL.+ (\d+\.\d+)%$/' script: - py.test-3 -v --cov --cov-report=term --cov-report=html tests artifacts: paths: - htmlcov # static analysis with bandit include: template: SAST.gitlab-ci.yml sast: tags: [amd64-dind] stage: analyze variables: DOCKER_DRIVER: overlay2 SAST_DEFAULT_ANALYZERS: "bandit" ######### # Build # ######### sdist: stage: build image: debian:9 tags: [amd64] before_script: - apt-get update -qq - apt-get install --no-install-recommends -y python3 python3-pytest-runner python3-setuptools script: - python3 setup.py sdist doc: stage: build image: debian:9 tags: [amd64] before_script: - apt-get update -qq - apt-get install --no-install-recommends -y make python3 python3-pytest-runner python3-setuptools python3-sphinx script: - make -C doc html artifacts: paths: - doc/_build/html ########## # Deploy # ########## doc-deploy: stage: deploy tags: [deploy] only: refs: - tags dependencies: - doc script: - mkdir -p ${HOME}/docs/lavacli - rsync -av --delete doc/_build/html ${HOME}/docs/lavacli/ environment: name: doc url: https://docs.lavasoftware.org/lavacli lavacli-v0.9.8/LICENSE000066400000000000000000001033301354067014100143370ustar00rootroot00000000000000 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . lavacli-v0.9.8/MANIFEST.in000066400000000000000000000002151354067014100150660ustar00rootroot00000000000000include doc/* include share/lavacli.yaml include tests/* include .coveragerc include .gitlab-ci.yml include LICENSE include requirements.txt lavacli-v0.9.8/debian/000077500000000000000000000000001354067014100145545ustar00rootroot00000000000000lavacli-v0.9.8/debian/changelog000066400000000000000000000070521354067014100164320ustar00rootroot00000000000000lavacli (0.9.8-1) unstable; urgency=medium * New upstream release + Export author email + Fix yaml.dump after recent pyyaml changes + CI: test on debian testing + Ad a git buildpackage configuration file + Add a simple release script + Improve release script -- Remi Duraffort Thu, 19 Sep 2019 14:10:45 +0200 lavacli (0.9.7-1) unstable; urgency=medium * New upstream release + workers: get and set the environment -- Steve McIntyre <93sam@debian.org> Mon, 01 Jul 2019 11:47:23 +0100 lavacli (0.9.6-1) unstable; urgency=medium * New upstream release + utils.templates.render: fix --path option + Do not print token when an exception is raised + Improve error reporting + jobs: allow to cancel many jobs in one call + jobs submit: Don't eat xmlrpc error + utils templates render: allow to specify the context + utils template render: allow to set trim_block + utils.loader: allow to use the safe loader + results: use the CSafeLoader whenether possible + loader: use the helper whenever possible + Add a timeout option for the 'jobs wait' command + Fix lavacli crashes when the server returns a Fault exception + aliases: port to the new API in LAVA 2019.05 + jobs validate: fix crash when validating * fix watch script * fix link to the source repository -- Steve McIntyre <93sam@debian.org> Tue, 05 Mar 2019 17:09:33 +0000 lavacli (0.9.5-1) unstable; urgency=medium * New upstream release + Fix user-agent + When submitting multiple jobs, declare which job failed and continue + jobs.validate: allow to validate job definitions + Allow fallback to yaml.Loader + Create config dir if it doesn't exist * Fix Uploaders: add me, remove Senthil * Moved Debian packaging into the upstream repo, so update the VCS- links to point there -- Steve McIntyre <93sam@debian.org> Tue, 05 Mar 2019 17:09:33 +0000 lavacli (0.9.4-1) unstable; urgency=medium * New upstream release "utils templates render" to render jinja2 templates "jobs queue" to show the current queue for some device-types (needs lava 2019.01) -- Neil Williams Wed, 30 Jan 2019 12:06:40 +0000 lavacli (0.9.3-1) unstable; urgency=medium * New upstream release * a future proof versionning support * use black code format * allow to use --verbose and --since for job listing * Update homepage * Update standards version (no changes) -- Neil Williams Tue, 06 Nov 2018 08:41:22 +0000 lavacli (0.9.2-2) unstable; urgency=medium * Remove build-dep on python3-all (Closes: #911550) -- Neil Williams Thu, 25 Oct 2018 13:50:23 +0100 lavacli (0.9.2-1) unstable; urgency=medium * 0.9.2-1 New upstream release. * Add autopkgtest. * Update X-Python-Version. * Add pytest dependencies for running tests. -- Senthil Kumaran S (stylesen) Tue, 22 May 2018 14:04:24 +0530 lavacli (0.8-1) unstable; urgency=medium * 0.8-1 New upstream release * Add rules to package manpages -- Neil Williams Wed, 18 Apr 2018 09:39:14 +0100 lavacli (0.7-1~bpo9+1) stretch-backports; urgency=medium * Rebuild for stretch-backports. -- Senthil Kumaran S (stylesen) Thu, 22 Mar 2018 08:00:52 +0530 lavacli (0.7-1) unstable; urgency=medium * Initial release. (Closes: #887476: ITP: lavacli -- LAVA XML-RPC command line interface) -- Senthil Kumaran S (stylesen) Thu, 08 Feb 2018 11:42:30 +0530 lavacli-v0.9.8/debian/compat000066400000000000000000000000021354067014100157520ustar00rootroot000000000000009 lavacli-v0.9.8/debian/control000066400000000000000000000027231354067014100161630ustar00rootroot00000000000000Source: lavacli Maintainer: Debian LAVA team Uploaders: Steve McIntyre <93sam@debian.org>, Neil Williams Section: admin Priority: optional Build-Depends: debhelper (>= 10), dh-python, python3, python3-setuptools, python3-requests, python3-yaml, python3-zmq, python3-jinja2, python3-sphinx, python3-pytest-runner, python3-pytest X-Python-Version: >= 3.6 Standards-Version: 4.2.1 Homepage: https://git.lavasoftware.org/lava/lavacli Vcs-Git: https://git.lavasoftware.org/lava/lavacli Vcs-Browser: https://git.lavasoftware.org/lava/lavacli Package: lavacli Architecture: all Depends: ${misc:Depends}, ${python3:Depends} Description: LAVA XML-RPC command line interface LAVA is a continuous integration system for deploying operating systems onto physical and virtual hardware for running tests. Tests can be simple boot testing, bootloader testing and system level testing, although extra hardware may be required for some system tests. Results are tracked over time and data can be exported for further analysis. . This package provides a user space command line interface to any LAVA (Linaro Automated Validation Architecture) instance for submitting test jobs or querying the instance for device and job status over XML-RPC. A user account on the instance is needed to create and use authentication tokens for some calls. The list of calls supported is described on the API section of the LAVA instance. lavacli-v0.9.8/debian/copyright000066400000000000000000001071641354067014100165200ustar00rootroot00000000000000Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: lavacli Source: https://git.lavasoftware.org/lava/lavacli Files: * Copyright: 2018 Linaro Limited 2018 Remi Duraffort License: AGPL-3.0 Files: debian/* Copyright: 2018 Senthil Kumaran S License: MIT License: AGPL-3.0 GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 . Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. . Preamble . The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. . The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. . When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. . Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. . A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. . The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. . An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. . The precise terms and conditions for copying, distribution and modification follow. . TERMS AND CONDITIONS . 0. Definitions. . "This License" refers to version 3 of the GNU Affero General Public License. . "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. . "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. . To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. . A "covered work" means either the unmodified Program or a work based on the Program. . To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. . To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. . An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. . 1. Source Code. . The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. . A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. . The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. . The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. . The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. . The Corresponding Source for a work in source code form is that same work. . 2. Basic Permissions. . All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. . You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. . Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. . 3. Protecting Users' Legal Rights From Anti-Circumvention Law. . No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. . When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. . 4. Conveying Verbatim Copies. . You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. . You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. . 5. Conveying Modified Source Versions. . You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: . a) The work must carry prominent notices stating that you modified it, and giving a relevant date. . b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". . c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. . d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. . A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. . 6. Conveying Non-Source Forms. . You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: . a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. . b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. . c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. . d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. . e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. . A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. . A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. . "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. . If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). . The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. . Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. . 7. Additional Terms. . "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. . When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. . Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: . a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or . b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or . c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or . d) Limiting the use for publicity purposes of names of licensors or authors of the material; or . e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or . f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. . All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. . If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. . Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. . 8. Termination. . You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). . However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. . Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. . Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. . 9. Acceptance Not Required for Having Copies. . You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. . 10. Automatic Licensing of Downstream Recipients. . Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. . An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. . You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. . 11. Patents. . A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". . A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. . Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. . In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. . If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. . If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. . A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. . Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. . 12. No Surrender of Others' Freedom. . If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. . 13. Remote Network Interaction; Use with the GNU General Public License. . Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. . Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. . 14. Revised Versions of this License. . The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. . Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. . If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. . Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. . 15. Disclaimer of Warranty. . THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. . 16. Limitation of Liability. . IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. . 17. Interpretation of Sections 15 and 16. . If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. . END OF TERMS AND CONDITIONS . How to Apply These Terms to Your New Programs . If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. . To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. . Copyright (C) . This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. . You should have received a copy of the GNU Affero General Public License along with this program. If not, see . . Also add information on how to contact you by electronic and paper mail. . If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. . You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . License: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. . THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lavacli-v0.9.8/debian/gbp.conf000066400000000000000000000001321354067014100161670ustar00rootroot00000000000000[buildpackage] upstream-tree = BRANCH upstream-branch = master export-dir = ./build-area/ lavacli-v0.9.8/debian/install000066400000000000000000000000501354067014100161400ustar00rootroot00000000000000share/lavacli.yaml ./usr/share/lavacli/ lavacli-v0.9.8/debian/pydist-overrides000066400000000000000000000001301354067014100200050ustar00rootroot00000000000000PyYaml python3-yaml; PEP386 pyzmq python3-zmq; PEP386 requests python3-requests; PEP386 lavacli-v0.9.8/debian/rules000077500000000000000000000016161354067014100156400ustar00rootroot00000000000000#!/usr/bin/make -f include /usr/share/dpkg/pkg-info.mk # Prevent setuptools/distribute from accessing the internet. export http_proxy = http://127.0.9.1:9 export PYBUILD_NAME=lavacli export BUILD_DATE=$(shell LC_ALL=C date -u "+%B %d, %Y" -d @"$(SOURCE_DATE_EPOCH)") %: dh $@ --with python3 --buildsystem=pybuild override_dh_auto_test: python3 setup.py pytest override_dh_auto_build: python3 setup.py build make -C doc/ man SPHINXBUILD="/usr/share/sphinx/scripts/python3/sphinx-build" SPHINXOPTS="-j 4 -D today=\"$(BUILD_DATE)\"" override_dh_auto_install: python3 setup.py install --root=$(CURDIR)/debian/lavacli/ --install-layout=deb dh_installman -plavacli doc/_build/man/lavacli.1 override_dh_auto_clean:: $(RM) -r lavacli.egg-info/ build/ dist/ .pybuild/ doc/_build find . -name '*.pyc' -exec $(RM) -f {} + find . -name '*.pyo' -exec $(RM) -f {} + find . -name '*~' -exec rm $(RM) {} + lavacli-v0.9.8/debian/source/000077500000000000000000000000001354067014100160545ustar00rootroot00000000000000lavacli-v0.9.8/debian/source/format000066400000000000000000000000141354067014100172620ustar00rootroot000000000000003.0 (quilt) lavacli-v0.9.8/debian/tests/000077500000000000000000000000001354067014100157165ustar00rootroot00000000000000lavacli-v0.9.8/debian/tests/control000066400000000000000000000001201354067014100173120ustar00rootroot00000000000000Tests: testsuite Depends: @, @builddeps@, python3-pytest, python3-pytest-runner lavacli-v0.9.8/debian/tests/testsuite000066400000000000000000000001771354067014100176770ustar00rootroot00000000000000#!/bin/sh set -e TESTDIR=`pwd`/debian/testhome mkdir -p ${TESTDIR} HOME=${TESTDIR} TMPDIR=${TESTDIR} python3 setup.py pytest lavacli-v0.9.8/debian/watch000066400000000000000000000001551354067014100156060ustar00rootroot00000000000000version=4 https://git.lavasoftware.org/lava/lavacli/tags /lava/lavacli/-/archive/v(.+)/lavacli-v.+\.tar\.gz lavacli-v0.9.8/doc/000077500000000000000000000000001354067014100140775ustar00rootroot00000000000000lavacli-v0.9.8/doc/Makefile000066400000000000000000000011341354067014100155360ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = lavacli SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)lavacli-v0.9.8/doc/conf.py000066400000000000000000000122441354067014100154010ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # lavacli documentation build configuration file, created by # sphinx-quickstart on Fri Apr 13 13:28:36 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) import subprocess # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The master toctree document. master_doc = "index" # General information about the project. project = "lavacli" copyright = "2018, Rémi Duraffort" author = "Rémi Duraffort" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # version_str = subprocess.check_output( ["python3", "setup.py", "--version"], stderr=open("/dev/null", "w"), cwd=".." ).decode("utf-8") # The short X.Y version. version = version_str # The full version, including alpha/beta/rc tags. release = version_str # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { "**": [ "relations.html", # needs 'show_related': True theme option to display "searchbox.html", ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = "lavaclidoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, "lavacli.tex", "lavacli Documentation", "Remi Duraffort", "manual") ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "lavacli", "lavacli Documentation", [author], 1)] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "lavacli", "lavacli Documentation", author, "lavacli", "One line description of project.", "Miscellaneous", ) ] lavacli-v0.9.8/doc/configuration.rst000066400000000000000000000044371354067014100175100ustar00rootroot00000000000000.. _configuration: Configuration ############# lavacli can be used with or without a configuration file. Having a configuration file will help when using more than one lava instance. Without a configuration file ============================ When using lavacli without any configuration file, the uri should be passed as a command line argument: .. code-block:: shell lavacli --uri https://validation.linaro.org/RPC2 devices list The authentication can also be passed in the uri: .. code-block:: shell lavacli --uri https://admin:my_secret_token@validation.linaro.org/RPC2 devices list Keep in mind, that any user on the same machine will then see the username and token in the process list. With a configuration file ========================= lavacli configuration file is stored in **~/.config/lavacli.yaml**. This is a YAML dictionary where each key is an *identity*. .. code-block:: yaml default: uri: https://validation.linaro.org/RPC2 validation: uri: https://validation.linaro.org/RPC2 admin@validation: uri: https://validation.linaro.org/RPC2 username: admin token: my_secret_token staging: uri: https://staging.validation.linaro.org/RPC2 events: uri: tcp://staging.validation.linaro.org:5500 When using lavacli, the *identity* can be used with **-i** or **--identity**: .. code-block:: shell lavacli -i admin@validation devices list lavacli -i staging events listen By default, the **default** identity will be used. Hence both commands are identitical: .. code-block:: shell lavacli devices list lavacli -i validation devices list Available options ***************** For each identity, you have to set: * **uri**: the uri of the RPC endpoint. You can also set: * **username**: the api username * **token**: the api token * **version**: the api version to use when talking to this instance * **timeout**: the http timeout (defaults to 20 seconds) * **proxy**: the uri to the proxy * **verify_ssl_cert**: set it to true to ignore SSL certificates errors (defaults to false) * **events**: zmq event configuration The **events** key is a dictionary where you can specify: * **uri**: the uri of the events stream. If not specified, lavacli will ask the server. * **socks_proxy**: uri to the socks proxy, if needed lavacli-v0.9.8/doc/index.rst000066400000000000000000000005731354067014100157450ustar00rootroot00000000000000.. _index: lavacli ####### lavacli is a command line tool to interact with one or many LAVA instances using XML-RPC. Features ======== lavacli allows you to interact with all LAVA objects: * aliases * device-types * devices * events * jobs * results * tags * workers Table of Contents ================= .. toctree:: :maxdepth: 2 install configuration usage lavacli-v0.9.8/doc/install.rst000066400000000000000000000013211354067014100162740ustar00rootroot00000000000000.. _installation: Installation ############ Debian ====== A `Debian package `_ is available for Debian unstable and could be installed with: .. code-block:: shell apt install lavacli PyPi ==== lavacli is also available on `Pypi `_ and can be installed with: .. code-block:: shell pip install lavacli Development versions ===================== It's also possible to use lavacli directly from the sources: .. code-block:: shell git clone https://git.lavasoftware.org/lava/lavacli.git cd lavacli virtualenv -p python3 venv source venv/bin/activate pip install -r requirements.txt python3 -m lavacli lavacli-v0.9.8/doc/usage.rst000066400000000000000000000106231354067014100157370ustar00rootroot00000000000000.. _usage: Usage ##### Here is the list of available commands and sub-commands. Aliases ======= LAVA aliases can be managed by: .. code-block:: shell lavacli aliases add lavacli aliases delete lavacli aliases list lavacli aliases show Device types ============ LAVA device types can be managed by: .. code-block:: shell lavacli device-types add [...] lavacli device-types aliases add lavacli device-types aliases delete lavacli device-types aliases list lavacli device-types health-check get lavacli device-types health-check set lavacli device-types list lavacli device-types show lavacli device-types template get lavacli device-types template set lavacli device-types update [...] Devices ======= LAVA devices can be managed by: .. code-block:: shell lavacli devices add [...] lavacli devices dict get lavacli devices dict set lavacli devices list lavacli devices maintenance lavacli devices show lavacli devices tags add lavacli devices tags delete lavacli devices tags list lavacli devices update [...] Events ====== LAVA events can be used by: .. code-block:: shell lavacli events listen lavacli events wait device [...] lavacli events wait job [...] lavacli events wait worker [...] Identities ========== lavacli identities can be managed by: .. code-block:: shell lavacli identities add [...] lavacli identities delete lavacli identities list lavacli identities show Jobs ==== LAVA jobs can be managed by: .. code-block:: shell lavacli jobs cancel lavacli jobs config lavacli jobs definition lavacli jobs list lavacli jobs logs lavacli jobs queue lavacli jobs resubmit lavacli jobs run lavacli jobs show lavacli jobs submit lavacli jobs validate lavacli jobs wait Results ======= LAVA results can be managed by: .. code-block:: shell lavacli results lavacli results lavacli results System ====== LAVA instance can be managed by: .. code-block:: shell lavacli system active lavacli system api lavacli system export lavacli system maintenance lavacli system methods list lavacli system methods help lavacli system methods signature lavacli system version lavacli system whoami In order to put a full instance into maintenance, an admin could call **system maintenance**. This function will: * set all workers health to *MAINTENANCE* * wait for all jobs to finish If the instance should be put into into maintenance immediately, addind **--force** will: * set all workers health to *MAINTENANCE* * cancel all running jobs * wait for all jobs to finish It also possible to exclude some workers with **--exclude**. When the maintenance is finished, calling **system active** will move every worker into *MAINTENANCE* to *ACTIVE*. Tags ==== LAVA tag can be managed by: .. code-block:: shell lavacli tags add [...] lavacli tags delete lavacli tags list lavacli tags show Utils ===== Some utilities are available with: .. code-block:: shell lavacli utils logs print lavacli utils templates render Printing logs ************* When working with raw logs, lavacli might help by coloring the logs by levels. It's also possible to filter the logs by level. To only print the serial output and the commands sent by LAVA to the board, use: .. code-block:: shell lavacli utils logs print --filter target,input Available log levels are: exception, error, warning, info, debug, target, input, feedback, results. Workers ======= LAVA workers can be managed by: .. code-block:: shell lavacli workers add [...] lavacli workers config get lavacli workers config set lavacli workers env get lavacli workers env set lavacli workers list lavacli workers maintenance lavacli workers update [...] lavacli workers show lavacli-v0.9.8/lavacli/000077500000000000000000000000001354067014100147455ustar00rootroot00000000000000lavacli-v0.9.8/lavacli/__about__.py000066400000000000000000000025361354067014100172330ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see __all__ = [ "__author__", "__author_email__", "__description__", "__license__", "__url__", "__version__", ] def git_describe(): import subprocess try: # git describe? out = subprocess.check_output(["git", "describe"], stderr=subprocess.STDOUT) return out.decode("utf-8").rstrip("\n")[1:] except Exception: return "git" __author__ = "Rémi Duraffort" __author_email__ = "remi.duraffort@linaro.org" __description__ = "LAVA XML-RPC command line interface" __license__ = "AGPLv3+" __url__ = "https://git.lavasoftware.org/lava/lavacli" __version__ = "0.9.8" lavacli-v0.9.8/lavacli/__init__.py000066400000000000000000000200471354067014100170610ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import argparse import os import requests import socket from urllib.parse import urlparse import xmlrpc.client import yaml from .__about__ import __version__ from .utils import loader, parse_version, VERSION_LATEST, exc2str from .commands import ( aliases, devices, device_types, events, identities, jobs, results, system, tags, utils, workers, ) class RequestsTransport(xmlrpc.client.Transport): def __init__(self, scheme, proxy=None, timeout=20.0, verify_ssl_cert=True): super().__init__() self.scheme = scheme # Set the user agent self.user_agent = "lavacli v%s" % __version__ if proxy is None: self.proxies = {} else: self.proxies = {scheme: proxy} self.timeout = timeout self.verify_ssl_cert = verify_ssl_cert if not verify_ssl_cert: from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) def request(self, host, handler, request_body, verbose=False): headers = { "User-Agent": self.user_agent, "Content-Type": "text/xml", "Accept-Encoding": "gzip", } url = "%s://%s%s" % (self.scheme, host, handler) try: response = None response = requests.post( url, data=request_body, headers=headers, timeout=self.timeout, verify=self.verify_ssl_cert, proxies=self.proxies, ) response.raise_for_status() return self.parse_response(response) except requests.RequestException as e: if response is None: raise xmlrpc.client.ProtocolError(url, 500, str(e), "") else: raise xmlrpc.client.ProtocolError( url, response.status_code, str(e), response.headers ) def parse_response(self, response): """ Parse the xmlrpc response. """ p, u = self.getparser() p.feed(response.text) p.close() return u.close() def load_config(identity): # Build the path to the configuration file config_dir = os.environ.get("XDG_CONFIG_HOME", "~/.config") config_filename = os.path.expanduser(os.path.join(config_dir, "lavacli.yaml")) try: with open(config_filename, "r", encoding="utf-8") as f_conf: config = yaml.load( # nosec - loader() returns a safe loader f_conf.read(), Loader=loader() ) return config[identity] except (FileNotFoundError, KeyError, TypeError): return {} def common_parser(): parser_obj = argparse.ArgumentParser(add_help=False) # --help and --version misc = parser_obj.add_argument_group("lavacli") misc.add_argument( "--help", "-h", action="store_true", default=False, help="show this help message and exit", ) misc.add_argument( "--version", action="store_true", default=False, help="print the version number and exit", ) # identity or url url = parser_obj.add_argument_group("identity").add_mutually_exclusive_group() url.add_argument( "--uri", type=str, default=None, help="URI of the lava-server RPC endpoint" ) url.add_argument( "--identity", "-i", metavar="ID", type=str, default="default", help="identity stored in the configuration", ) return parser_obj def parser(parser_obj, commands, version): # The sub commands root = parser_obj.add_subparsers(dest="sub_command", help="Sub commands") keys = list(commands.keys()) keys.sort() for name in keys: cls = commands[name] cls.configure_parser(root.add_parser(name, help=cls.help_string()), version) return parser_obj def main(): # List of known commands commands = { "aliases": aliases, "devices": devices, "device-types": device_types, "events": events, "identities": identities, "jobs": jobs, "results": results, "system": system, "tags": tags, "utils": utils, "workers": workers, } # Parsing is made of two phases as arguments depends on the API version of # the remote server. # 1/ Parse the common arguments parser_obj = common_parser() (options, remaining) = parser_obj.parse_known_args() # Do we have to print the version numer? if options.version: print("lavacli %s" % __version__) return 0 # Print help if lavacli is called without any arguments if not remaining: parser_obj = parser(parser_obj, commands, VERSION_LATEST) parser_obj.print_help() return 0 if options.help else 1 # Load the configuration (if any) uri = options.uri proxy = None version = VERSION_LATEST config = {} # Skip when sub_command is "identities" if remaining[0] not in ["identities", "utils"]: if uri is None: config = load_config(options.identity) if config.get("uri") is None: print("Unknown identity '%s'" % options.identity) return 1 username = config.get("username") token = config.get("token") if username is not None and token is not None: p = urlparse(config["uri"]) uri = "%s://%s:%s@%s%s" % (p.scheme, username, token, p.netloc, p.path) else: uri = config["uri"] try: # Create the Transport object parsed_uri = urlparse(uri) transport = RequestsTransport( parsed_uri.scheme, config.get("proxy"), config.get("timeout", 20.0), config.get("verify_ssl_cert", True), ) # allow_none is True because the server does support it proxy = xmlrpc.client.ServerProxy(uri, allow_none=True, transport=transport) version = proxy.system.version() except (OSError, xmlrpc.client.Error) as exc: print("Unable to connect: %s" % exc2str(exc)) return 1 # Parse version version = parse_version(version) config["version"] = version # Parse the command line parser_obj = parser(parser_obj, commands, version) options = parser_obj.parse_args() options.uri = uri try: # Run the command return commands[options.sub_command].handle(proxy, options, config) except (ConnectionError, socket.gaierror) as exc: print("Unable to connect to '%s': %s" % (options.uri, str(exc))) except KeyboardInterrupt: pass except identities.ConfigurationError as exc: print(exc) return 1 except xmlrpc.client.Error as exc: msg = exc.errmsg if hasattr(exc, "errmsg") else str(exc) if "sub_sub_command" in options: print( "Unable to call '%s.%s': %s" % (options.sub_command, options.sub_sub_command, msg) ) else: print("Unable to call '%s': %s" % (options.sub_command, msg)) except BaseException as exc: print("Unknown error: %s" % str(exc)) return 1 lavacli-v0.9.8/lavacli/__main__.py000066400000000000000000000015541354067014100170440ustar00rootroot00000000000000#!/usr/bin/python3 # -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import sys from . import main if __name__ == "__main__": sys.argv[0] = "lavacli" sys.exit(main()) lavacli-v0.9.8/lavacli/commands/000077500000000000000000000000001354067014100165465ustar00rootroot00000000000000lavacli-v0.9.8/lavacli/commands/__init__.py000066400000000000000000000000001354067014100206450ustar00rootroot00000000000000lavacli-v0.9.8/lavacli/commands/aliases.py000066400000000000000000000077151354067014100205530ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import yaml def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "add" aliases_add = sub.add_parser("add", help="add an alias") aliases_add.add_argument("alias", help="alias name") if version >= (2019, 5): aliases_add.add_argument("device_type", help="device-type") # "delete" aliases_del = sub.add_parser("delete", help="delete an alias") aliases_del.add_argument("alias", help="alias name") # "list" aliases_list = sub.add_parser("list", help="list available aliases") out_format = aliases_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", default=None, action="store_const", const="yaml", help="print as yaml", ) # "show" aliases_show = sub.add_parser("show", help="show alias details") aliases_show.add_argument("alias", help="alias") out_format = aliases_show.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) def help_string(): return "manage device-type aliases" def handle_add(proxy, options, config): if config["version"] >= (2019, 5): proxy.scheduler.aliases.add(options.alias, options.device_type) else: proxy.scheduler.aliases.add(options.alias) return 0 def handle_delete(proxy, options, _): proxy.scheduler.aliases.delete(options.alias) return 0 def handle_list(proxy, options, _): aliases = proxy.scheduler.aliases.list() if options.output_format == "json": print(json.dumps(aliases)) elif options.output_format == "yaml": print(yaml.dump(aliases, default_flow_style=None).rstrip("\n")) else: print("Aliases:") for alias in aliases: print("* %s" % alias) return 0 def handle_show(proxy, options, config): alias = proxy.scheduler.aliases.show(options.alias) if options.output_format == "json": print(json.dumps(alias)) elif options.output_format == "yaml": print(yaml.dump(alias, default_flow_style=None).rstrip("\n")) else: if config["version"] >= (2019, 5): print("name : %s" % alias["name"]) print("device-type: %s" % alias["device_type"]) else: print("name : %s" % alias["name"]) print("device-types:") for dt in alias["device_types"]: print("* %s" % dt) return 0 def handle(proxy, options, config): handlers = { "add": handle_add, "delete": handle_delete, "list": handle_list, "show": handle_show, } return handlers[options.sub_sub_command](proxy, options, config) lavacli-v0.9.8/lavacli/commands/device_types.py000066400000000000000000000254761354067014100216210ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import argparse import json import yaml def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "add" dt_add = sub.add_parser("add", help="add a device type") dt_add.add_argument("name", help="name of the device-type") dt_add.add_argument("--description", default=None, help="device-type description") dt_add.add_argument( "--hide", dest="display", action="store_false", default=True, help="device is hidden in the UI", ) dt_add.add_argument( "--owners-only", action="store_true", default=False, help="devices are only visible to owners", ) dt_health = dt_add.add_argument_group("health check") dt_health.add_argument( "--health-frequency", default=24, type=int, help="how often to run health checks.", ) dt_health.add_argument( "--health-denominator", default="hours", choices=["hours", "jobs"], help="initiate health checks by hours or by jobs.", ) # "aliases" dt_aliases = sub.add_parser( "aliases", help="manage aliases for the given device-type" ) aliases_sub = dt_aliases.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) aliases_sub.required = True aliases_add = aliases_sub.add_parser("add", help="add aliases") aliases_add.add_argument("name", help="name of the device-type") aliases_add.add_argument("alias", help="name of alias") aliases_delete = aliases_sub.add_parser("delete", help="delete aliases") aliases_delete.add_argument("name", help="name of the device-type") aliases_delete.add_argument("alias", help="name of alias") aliases_list = aliases_sub.add_parser( "list", help="list aliases for the device-type" ) aliases_list.add_argument("name", help="device-type") out_format = aliases_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", default=None, action="store_const", const="yaml", help="print as yaml", ) if version >= (2018, 4): # "heath-check" dt_hc = sub.add_parser("health-check", help="device-type health-check") dt_sub = dt_hc.add_subparsers(dest="sub_sub_sub_command", help="Sub commands") dt_sub.required = True dt_get = dt_sub.add_parser("get", help="get the device-type health-check") dt_get.add_argument("name", help="name of the device-type") dt_set = dt_sub.add_parser("set", help="set the device-type health-check") dt_set.add_argument("name", help="name of the device-type") dt_set.add_argument( "definition", type=argparse.FileType("r"), help="health-check definition" ) # "list" dt_list = sub.add_parser("list", help="list available device-types") dt_list.add_argument( "--all", "-a", dest="show_all", default=False, action="store_true", help="show all device types in the database, " "including non-installed ones", ) out_format = dt_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", default=None, action="store_const", const="yaml", help="print as yaml", ) # "show" dt_show = sub.add_parser("show", help="show device-type details") dt_show.add_argument("name", help="name of the device-type") out_format = dt_show.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) # "template" dt_template = sub.add_parser("template", help="device-type template") dt_sub = dt_template.add_subparsers(dest="sub_sub_sub_command", help="Sub commands") dt_sub.required = True dt_get = dt_sub.add_parser("get", help="get the device-type template") dt_get.add_argument("name", help="name of the device-type") dt_set = dt_sub.add_parser("set", help="set the device-type template") dt_set.add_argument("name", help="name of the device-type") dt_set.add_argument("template", type=argparse.FileType("r"), help="template file") # "update" dt_update = sub.add_parser("update", help="update device-type") dt_update.add_argument("name", help="name of the device-type") dt_update.add_argument( "--description", default=None, help="device-type description" ) visibility = dt_update.add_mutually_exclusive_group() visibility.add_argument( "--hide", dest="display", action="store_false", default=None, help="device-type is hidden in the UI", ) visibility.add_argument( "--show", dest="display", action="store_true", help="device-type is visible in the UI", ) owner = dt_update.add_mutually_exclusive_group() owner.add_argument( "--owners-only", action="store_true", dest="owners_only", default=None, help="devices are only visible to owners", ) owner.add_argument( "--public", action="store_false", dest="owners_only", help="devices are visible to all users", ) dt_health = dt_update.add_argument_group("health check") dt_health.add_argument( "--health-frequency", default=None, type=int, help="how often to run health checks.", ) dt_health.add_argument( "--health-denominator", default=None, choices=["hours", "jobs"], help="initiate health checks by hours or by jobs.", ) health = dt_health.add_mutually_exclusive_group() health.add_argument( "--health-disabled", default=None, action="store_true", help="disable health checks", ) health.add_argument( "--health-active", dest="health_disabled", action="store_false", help="activate health checks", ) def help_string(): return "manage device-types" def handle_add(proxy, options): proxy.scheduler.device_types.add( options.name, options.description, options.display, options.owners_only, options.health_frequency, options.health_denominator, ) return 0 def handle_aliases(proxy, options): if options.sub_sub_sub_command == "add": proxy.scheduler.device_types.aliases.add(options.name, options.alias) elif options.sub_sub_sub_command == "list": aliases = proxy.scheduler.device_types.aliases.list(options.name) if options.output_format == "json": print(json.dumps(aliases)) elif options.output_format == "yaml": print(yaml.dump(aliases, default_flow_style=None).rstrip("\n")) else: print("Aliases:") for alias in aliases: print("* %s" % alias) else: assert options.sub_sub_sub_command == "delete" proxy.scheduler.device_types.aliases.delete(options.name, options.alias) return 0 def handle_hc(proxy, options): if options.sub_sub_sub_command == "get": template = proxy.scheduler.device_types.get_health_check(options.name) print(str(template).rstrip("\n")) else: hc = options.definition.read() proxy.scheduler.device_types.set_health_check(options.name, hc) return 0 def handle_list(proxy, options): device_types = proxy.scheduler.device_types.list(options.show_all) if options.output_format == "json": print(json.dumps(device_types)) elif options.output_format == "yaml": print(yaml.dump(device_types, default_flow_style=None).rstrip("\n")) else: print("Device-Types:") for dt in device_types: print("* %s (%s)" % (dt["name"], dt["devices"])) return 0 def handle_show(proxy, options): dt = proxy.scheduler.device_types.show(options.name) if options.output_format == "json": print(json.dumps(dt)) elif options.output_format == "yaml": print(yaml.dump(dt, default_flow_style=None).rstrip("\n")) else: print("name : %s" % dt["name"]) print("description : %s" % dt["description"]) print("display : %s" % dt["display"]) print("owners only : %s" % dt["owners_only"]) print("health disabled : %s" % dt["health_disabled"]) print("aliases : %s" % dt["aliases"]) print("devices : %s" % dt["devices"]) return 0 def handle_template(proxy, options): if options.sub_sub_sub_command == "get": template = proxy.scheduler.device_types.get_template(options.name) print(str(template).rstrip("\n")) else: template = options.template.read() proxy.scheduler.device_types.set_template(options.name, template) return 0 def handle_update(proxy, options): proxy.scheduler.device_types.update( options.name, options.description, options.display, options.owners_only, options.health_frequency, options.health_denominator, options.health_disabled, ) return 0 def handle(proxy, options, _): handlers = { "add": handle_add, "aliases": handle_aliases, "health-check": handle_hc, "list": handle_list, "show": handle_show, "template": handle_template, "update": handle_update, } return handlers[options.sub_sub_command](proxy, options) lavacli-v0.9.8/lavacli/commands/devices.py000066400000000000000000000356401354067014100205520ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import argparse import json import time import yaml from lavacli.utils import loader def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "add" devices_add = sub.add_parser("add", help="add a device") devices_add.add_argument("hostname", help="hostname of the device") devices_add.add_argument("--type", required=True, help="device-type") devices_add.add_argument("--worker", required=True, help="worker hostname") devices_add.add_argument("--description", default=None, help="device description") owner = devices_add.add_mutually_exclusive_group() owner.add_argument("--user", default=None, help="device owner") owner.add_argument("--group", default=None, help="device group owner") if version >= (2018, 1): devices_add.add_argument( "--health", default=None, choices=["GOOD", "UNKNOWN", "LOOPING", "BAD", "MAINTENANCE", "RETIRED"], help="device health", ) else: devices_add.add_argument( "--status", default=None, choices=["OFFLINE", "IDLE", "RUNNING", "OFFLINING", "RETIRED", "RESERVED"], help="device status", ) devices_add.add_argument( "--health", default=None, choices=["UNKNOWN", "PASS", "FAIL", "LOOPING"], help="device health status", ) devices_add.add_argument( "--private", action="store_true", default=False, help="private device [default=public]", ) # "dict" devices_dict = sub.add_parser("dict", help="device dictionary") dict_sub = devices_dict.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) dict_sub.required = True dict_get = dict_sub.add_parser("get", help="get the device dictionary") dict_get.add_argument("hostname", help="hostname of the device") dict_get.add_argument( "field", nargs="?", default=None, help="only show the given sub-fields" ) dict_get.add_argument( "--context", default=None, help="job context for template rendering" ) dict_get.add_argument( "--render", action="store_true", default=False, help="render the dictionary into a configuration", ) dict_set = dict_sub.add_parser("set", help="set the device dictionary") dict_set.add_argument("hostname", help="hostname of the device") dict_set.add_argument( "config", type=argparse.FileType("r"), help="device dictionary file" ) # "list" devices_list = sub.add_parser("list", help="list available devices") devices_list.add_argument( "--all", "-a", action="store_true", default=False, help="list every devices, inluding retired", ) out_format = devices_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", default=None, action="store_const", const="yaml", help="print as yaml", ) # "maintenance" if version >= (2018, 1): devices_maintenance = sub.add_parser( "maintenance", help="maintenance the device" ) devices_maintenance.add_argument("hostname", help="device hostname") devices_maintenance.add_argument( "--force", default=False, action="store_true", help="force device maintenance by canceling running job", ) devices_maintenance.add_argument( "--no-wait", dest="wait", default=True, action="store_false", help="do not wait for the device to be idle", ) # "show" devices_show = sub.add_parser("show", help="show device details") devices_show.add_argument("hostname", help="device hostname") out_format = devices_show.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) # "tags" devices_tags = sub.add_parser("tags", help="manage tags for the given device") tags_sub = devices_tags.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) tags_sub.required = True tags_add = tags_sub.add_parser("add", help="add a tag") tags_add.add_argument("hostname", help="hostname of the device") tags_add.add_argument("tag", help="name of the tag") tags_del = tags_sub.add_parser("delete", help="remove a tag") tags_del.add_argument("hostname", help="hostname of the device") tags_del.add_argument("tag", help="name of the tag") tags_list = tags_sub.add_parser("list", help="list tags for the device") tags_list.add_argument("hostname", help="hostname of the device") out_format = tags_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", help="print as yaml", ) # "update" devices_update = sub.add_parser("update", help="update device properties") devices_update.add_argument("hostname", help="hostname of the device") devices_update.add_argument("--worker", default=None, help="worker hostname") devices_update.add_argument( "--description", default=None, help="device description" ) owner = devices_update.add_mutually_exclusive_group() owner.add_argument("--user", default=None, help="device owner") owner.add_argument("--group", default=None, help="device group owner") if version >= (2018, 1): devices_update.add_argument( "--health", default=None, choices=["GOOD", "UNKNOWN", "LOOPING", "BAD", "MAINTENANCE", "RETIRED"], help="device health", ) else: devices_update.add_argument( "--status", default=None, choices=["OFFLINE", "IDLE", "RUNNING", "OFFLINING", "RETIRED", "RESERVED"], help="device status", ) devices_update.add_argument( "--health", default=None, choices=["UNKNOWN", "PASS", "FAIL", "LOOPING"], help="device health status", ) display = devices_update.add_mutually_exclusive_group() display.add_argument( "--public", default=None, action="store_true", help="make the device public" ) display.add_argument( "--private", dest="public", action="store_false", help="make the device private" ) def help_string(): return "manage devices" def handle_add(proxy, options, config): if config["version"] >= (2018, 1): proxy.scheduler.devices.add( options.hostname, options.type, options.worker, options.user, options.group, not options.private, options.health, options.description, ) else: proxy.scheduler.devices.add( options.hostname, options.type, options.worker, options.user, options.group, not options.private, options.status, options.health, options.description, ) return 0 def _lookups(value, fields): try: for key in fields: if isinstance(value, list): value = value[int(key)] else: value = value[key] except IndexError: print("list index out of range (%d vs %d)" % (int(key), len(value))) return 1 except KeyError: print("Unknow key '%s' for '%s'" % (key, value)) return 1 except TypeError: print("Unable to lookup inside '%s' for '%s'" % (value, key)) return 1 print(value) return 0 def handle_dict(proxy, options, _): if options.sub_sub_sub_command == "get": config = proxy.scheduler.devices.get_dictionary( options.hostname, options.render, options.context ) if not options.field: print(str(config).rstrip("\n")) return 0 if options.render: value = yaml.load( # nosec - loader() returns a safe loader str(config), Loader=loader() ) return _lookups(value, options.field.split(".")) else: # Extract some variables import jinja2 env = jinja2.Environment(autoescape=False) # nosec ast = env.parse(config) field_name = options.field.split(".")[0] # Loop on all assignments for assign in ast.find_all(jinja2.nodes.Assign): if assign.target.name == field_name: value = assign.node.as_const() if options.field == field_name: print(value) return 0 else: return _lookups(value, options.field.split(".")[1:]) print("Unknow field '%s'" % field_name) return 1 else: config = options.config.read() ret = proxy.scheduler.devices.set_dictionary(options.hostname, config) if not ret: print("Unable to set the configuration") return 0 if ret else 1 def handle_list(proxy, options, config): devices = proxy.scheduler.devices.list(options.all) if options.output_format == "json": print(json.dumps(devices)) elif options.output_format == "yaml": print(yaml.dump(devices, default_flow_style=None).rstrip("\n")) else: print("Devices:") for device in devices: if config["version"] >= (2018, 1): print( "* %s (%s): %s,%s" % ( device["hostname"], device["type"], device["state"], device["health"], ) ) else: print( "* %s (%s): %s" % (device["hostname"], device["type"], device["status"]) ) return 0 def handle_maintenance(proxy, options, _): proxy.scheduler.devices.update( options.hostname, None, None, None, None, "MAINTENANCE", None ) device = proxy.scheduler.devices.show(options.hostname) current_job = device["current_job"] if current_job is not None: print("-> waiting for job %s" % current_job) # if --force is passed, cancel the job if options.force: print("--> canceling") proxy.scheduler.jobs.cancel(current_job) while ( options.wait and proxy.scheduler.jobs.show(current_job)["state"] != "Finished" ): print("--> waiting") time.sleep(5) return 0 def handle_show(proxy, options, config): device = proxy.scheduler.devices.show(options.hostname) if options.output_format == "json": print(json.dumps(device)) elif options.output_format == "yaml": print(yaml.dump(device, default_flow_style=None).rstrip("\n")) else: print("name : %s" % device["hostname"]) print("device-type : %s" % device["device_type"]) if config["version"] >= (2018, 1): print("state : %s" % device["state"]) print("health : %s" % device["health"]) else: print("status : %s" % device["status"]) print("user : %s" % device["user"]) print("group : %s" % device["group"]) print("health job : %s" % device["health_job"]) print("description : %s" % device["description"]) print("public : %s" % device["public"]) print("pipeline : %s" % device["pipeline"]) print("device-dict : %s" % device["has_device_dict"]) print("worker : %s" % device["worker"]) print("current job : %s" % device["current_job"]) print("tags : %s" % device["tags"]) return 0 def handle_tags(proxy, options, _): if options.sub_sub_sub_command == "add": proxy.scheduler.devices.tags.add(options.hostname, options.tag) elif options.sub_sub_sub_command == "delete": proxy.scheduler.devices.tags.delete(options.hostname, options.tag) else: tags = proxy.scheduler.devices.tags.list(options.hostname) if options.output_format == "json": print(json.dumps(tags)) elif options.output_format == "yaml": print(yaml.dump(tags, default_flow_style=None).rstrip("\n")) else: print("Tags:") for tag in tags: print("* %s" % tag) return 0 def handle_update(proxy, options, config): if config["version"] >= (2018, 1): proxy.scheduler.devices.update( options.hostname, options.worker, options.user, options.group, options.public, options.health, options.description, ) else: proxy.scheduler.devices.update( options.hostname, options.worker, options.user, options.group, options.public, options.status, options.health, options.description, ) return 0 def handle(proxy, options, config): handlers = { "add": handle_add, "dict": handle_dict, "list": handle_list, "maintenance": handle_maintenance, "show": handle_show, "tags": handle_tags, "update": handle_update, } return handlers[options.sub_sub_command](proxy, options, config) lavacli-v0.9.8/lavacli/commands/events.py000066400000000000000000000213231354067014100204250ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys from urllib.parse import urlparse import zmq from zmq.utils.strtypes import b, u def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "listen" listen_parser = sub.add_parser("listen", help="listen to events") listen_parser.add_argument( "--filter", action="append", default=None, choices=["device", "event", "testjob", "worker"], help="filter by topic type", ) # "wait" if version >= (2018, 1): wait_parser = sub.add_parser("wait", help="wait for a specific event") obj_parser = wait_parser.add_subparsers(dest="object", help="object to wait") obj_parser.required = True # "wait device" device_parser = obj_parser.add_parser("device") device_parser.add_argument("hostname", type=str, help="hostname of the device") device_parser.add_argument( "--state", default=None, choices=["IDLE", "RESERVED", "RUNNING"], help="device state", ) device_parser.add_argument( "--health", default=None, choices=["GOOD", "UNKNOWN", "LOOPING", "BAD", "MAINTENANCE", "RETIRED"], help="device health", ) # "wait job" testjob_parser = obj_parser.add_parser("job") testjob_parser.add_argument("job_id", help="job id") testjob_parser.add_argument( "--state", default=None, choices=[ "SUBMITTED", "SCHEDULING", "SCHEDULED", "RUNNING", "CANCELING", "FINISHED", ], help="job state", ) testjob_parser.add_argument( "--health", default=None, choices=["UNKNOWN", "COMPLETE", "INCOMPLETE", "CANCELED"], help="job health", ) # "wait worker" worker_parser = obj_parser.add_parser("worker") worker_parser.add_argument("hostname", type=str, help="worker hostname") worker_parser.add_argument( "--state", default=None, choices=["ONLINE", "OFFLINE"], help="worker state" ) worker_parser.add_argument( "--health", default=None, choices=["ACTIVE", "MAINTENANCE", "RETIRED"], help="worker health", ) def help_string(): return "listen to events" def _get_zmq_url(proxy, options, config): if config is None or config.get("events", {}).get("uri") is None: url = proxy.scheduler.get_publisher_event_socket() if "*" in url: domain = urlparse(options.uri).netloc if "@" in domain: domain = domain.split("@")[1] domain = domain.split(":")[0] url = url.replace("*", domain) else: url = config["events"]["uri"] return url def handle_listen(proxy, options, config): # Try to find the socket url url = _get_zmq_url(proxy, options, config) if url is None: print("Unable to find the socket url") return 1 context = zmq.Context() sock = context.socket(zmq.SUB) sock.setsockopt(zmq.SUBSCRIBE, b"") # Set the sock proxy (if needed) socks = config.get("events", {}).get("socks_proxy") if socks is not None: print("Listening to %s (socks %s)" % (url, socks)) sock.setsockopt(zmq.SOCKS_PROXY, b(socks)) else: print("Listening to %s" % url) try: sock.connect(url) except zmq.error.ZMQError as exc: print("Unable to connect: %s" % exc) return 1 while True: msg = sock.recv_multipart() try: (topic, _, dt, username, data) = (u(m) for m in msg) except ValueError: print("Invalid message: %s" % msg) continue # If unknown, print the full data msg = data data = json.loads(data) # Print according to the topic topic_end = topic.split(".")[-1] # filter by topic_end if options.filter and topic_end not in options.filter: continue if topic_end == "device": if config["version"] >= (2018, 1): msg = "[%s] <%s> state=%s health=%s" % ( data["device"], data["device_type"], data["state"], data["health"], ) else: msg = "[%s] <%s> %s" % ( data["device"], data["device_type"], data["status"], ) if "job" in data: msg += " for %s" % data["job"] elif topic_end == "testjob": if config["version"] >= (2018, 1): msg = "[%s] <%s> state=%s health=%s (%s)" % ( data["job"], data.get("device", "??"), data["state"], data["health"], data["description"], ) else: msg = "[%s] <%s> %s (%s)" % ( data["job"], data.get("device", "??"), data["status"], data["description"], ) elif topic_end == "worker": msg = "[%s] state=%s health=%s" % ( data["hostname"], data["state"], data["health"], ) elif topic_end == "event": msg = "[%s] message=%s" % (data["job"], data["message"]) if sys.stdout.isatty(): print( "\033[1;30m%s\033[0m \033[1;37m%s\033[0m \033[32m%s\033[0m - %s" % (dt, topic, username, msg) ) else: print("%s %s %s - %s" % (dt, topic, username, msg)) def handle_wait(proxy, options, config): # Try to find the socket url url = _get_zmq_url(proxy, options, config) if url is None: print("Unable to find the socket url") return 1 context = zmq.Context() sock = context.socket(zmq.SUB) # Filter by topic (if needed) sock.setsockopt(zmq.SUBSCRIBE, b(config.get("events", {}).get("topic", ""))) # Set the sock proxy (if needed) socks = config.get("events", {}).get("socks_proxy") if socks is not None: print("Listening to %s (socks %s)" % (url, socks)) sock.setsockopt(zmq.SOCKS_PROXY, b(socks)) else: print("Listening to %s" % url) try: sock.connect(url) except zmq.error.ZMQError as exc: print("Unable to connect: %s" % exc) return 1 # "job" is called "testjob" in the events object_topic = options.object if object_topic == "job": object_topic = "testjob" # Wait for events while True: msg = sock.recv_multipart() try: (topic, _uuid, _dt, _username, data) = (u(m) for m in msg) except ValueError: print("Invalid message: %s" % msg) continue data = json.loads(data) # Filter by object obj = topic.split(".")[-1] if obj != object_topic: continue if object_topic == "device": if data.get("device") != options.hostname: continue elif object_topic == "testjob": if data.get("job") != options.job_id: continue else: if data.get("hostname") != options.hostname: continue # Filter by state if options.state is not None: if data.get("state") != options.state.capitalize(): continue # Filter by health if options.health is not None: if data.get("health") != options.health.capitalize(): continue return 0 def handle(proxy, options, config): handlers = {"listen": handle_listen, "wait": handle_wait} return handlers[options.sub_sub_command](proxy, options, config) lavacli-v0.9.8/lavacli/commands/identities.py000066400000000000000000000103511354067014100212610ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import os import yaml from lavacli.utils import loader class ConfigurationError(Exception): pass def configure_parser(parser, _): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "add" config_add = sub.add_parser("add", help="add an identity") config_add.add_argument("id", type=str, help="identity") config_add.add_argument( "--uri", type=str, required=True, help="URI of the lava-server RPC endpoint" ) config_add.add_argument("--username", type=str, default=None, help="api username") config_add.add_argument("--token", type=str, default=None, help="api token") config_add.add_argument("--proxy", type=str, default=None, help="http proxy") # "delete" config_del = sub.add_parser("delete", help="delete an alias") config_del.add_argument("id", help="identity") # "list" sub.add_parser("list", help="list available identities") # "show" config_show = sub.add_parser("show", help="show identity details") config_show.add_argument("id", type=str, help="identity") def help_string(): return "manage lavacli configuration" def _load_configuration(): config_dir = os.environ.get("XDG_CONFIG_HOME", "~/.config") config_filename = os.path.expanduser(os.path.join(config_dir, "lavacli.yaml")) try: with open(config_filename, "r", encoding="utf-8") as f_conf: data = yaml.load( # nosec - loader() returns a safe loader f_conf.read(), Loader=loader() ) if not isinstance(data, dict): raise ConfigurationError("Invalid configuration file") return data except (FileNotFoundError, KeyError, TypeError): return {} def _save_configuration(config): config_dir = os.environ.get("XDG_CONFIG_HOME", "~/.config") expanded_config_dir = os.path.expanduser(config_dir) config_filename = os.path.expanduser(os.path.join(config_dir, "lavacli.yaml")) if not os.path.exists(expanded_config_dir): os.makedirs(expanded_config_dir) with open(config_filename, "w", encoding="utf-8") as f_conf: f_conf.write(yaml.safe_dump(config, default_flow_style=False).rstrip("\n")) def handle_add(_, options): config = _load_configuration() config[options.id] = {"uri": options.uri} if options.proxy: config[options.id]["proxy"] = options.proxy if options.username: config[options.id]["username"] = options.username if options.token: config[options.id]["token"] = options.token _save_configuration(config) return 0 def handle_delete(_, options): config = _load_configuration() try: del config[options.id] except KeyError: print("Unknown identity '%s'" % options.id) return 1 _save_configuration(config) return 0 def handle_list(_, __): config = _load_configuration() print("Identities:") for identity in sorted(config.keys()): print("* %s" % identity) return 0 def handle_show(_, options): config = _load_configuration() try: conf_str = yaml.safe_dump(config[options.id], default_flow_style=False) print(conf_str.rstrip("\n")) return 0 except KeyError: print("Unknown identity '%s'" % options.id) return 1 def handle(proxy, options, _): handlers = { "add": handle_add, "delete": handle_delete, "list": handle_list, "show": handle_show, } return handlers[options.sub_sub_command](proxy, options) lavacli-v0.9.8/lavacli/commands/jobs.py000066400000000000000000000601621354067014100200620ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import argparse import contextlib import datetime import json import pathlib import sys import time from urllib.parse import urlparse import xmlrpc.client import yaml from lavacli.utils import loader, print_u, exc2str def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "cancel" jobs_cancel = sub.add_parser("cancel", help="cancel a job") jobs_cancel.add_argument("job_id", nargs="+", help="job id") if version >= (2018, 4): # "config" jobs_config = sub.add_parser("config", help="job configuration") jobs_config.add_argument("job_id", help="job id") jobs_config.add_argument( "--dest", default=".", help="save files into this directory" ) # "definition" jobs_definition = sub.add_parser("definition", help="job definition") jobs_definition.add_argument("job_id", help="job id") # "list" jobs_list = sub.add_parser("list", help="list jobs") if version >= (2018, 4): jobs_list.add_argument( "--state", type=str, default=None, choices=[ "SUBMITTED", "SCHEDULING", "SCHEDULED", "RUNNING", "CANCELING", "FINISHED", ], help="filter jobs by state", ) jobs_list.add_argument( "--health", type=str, default=None, choices=["UNKNOWN", "COMPLETE", "INCOMPLETE", "CANCELED"], help="filter jobs by health", ) if version >= (2018, 10): jobs_list.add_argument( "--since", type=int, default=0, help="Filter by jobs which completed in the last N minutes.", ) jobs_list.add_argument( "--verbose", dest="verbose", action="store_true", help="If verbose is True, add extra keys, including error_type.", ) jobs_list.add_argument( "--start", type=int, default=0, help="skip the N first jobs [default=0]" ) jobs_list.add_argument( "--limit", type=int, default=25, help="limit to N jobs [default=25]" ) out_format = jobs_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", default=None, action="store_const", const="yaml", help="print as yaml", ) # "logs" jobs_logs = sub.add_parser("logs", help="get logs") jobs_logs.add_argument("job_id", help="job id") jobs_logs.add_argument( "--no-follow", default=False, action="store_true", help="do not keep polling until the end of the job", ) jobs_logs.add_argument( "--filters", default=None, type=str, help="comma seperated list of levels to show", ) jobs_logs.add_argument( "--polling", default=5, type=int, help="polling interval in seconds [default=5s]", ) jobs_logs.add_argument( "--raw", default=False, action="store_true", help="print raw logs" ) jobs_logs.add_argument( "--start", default=0, type=int, help="start at the given line" ) jobs_logs.add_argument( "--end", default=None, type=int, help="end at the given line" ) # "queue" if version >= (2019, 1): jobs_queue = sub.add_parser("queue", help="job queue") jobs_queue.add_argument( "device_types", nargs="*", help="filter by device-types" ) out_format = jobs_queue.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) jobs_queue.add_argument( "--start", type=int, default=0, help="skip the N first jobs [default=0]" ) jobs_queue.add_argument( "--limit", type=int, default=25, help="limit to N jobs [default=25]" ) # "resubmit" jobs_resubmit = sub.add_parser("resubmit", help="resubmit a job") jobs_resubmit.add_argument("job_id", help="job id") jobs_resubmit.add_argument( "--url", action="store_true", dest="print_url", default=False, help="Print the full url", ) jobs_resubmit.add_argument( "--filters", default=None, type=str, help="comma seperated list of levels to show", ) jobs_resubmit.add_argument( "--follow", default=True, dest="no_follow", action="store_false", help="resubmit and poll for the logs", ) jobs_resubmit.add_argument( "--polling", default=5, type=int, help="polling interval in seconds [default=5s]", ) jobs_resubmit.add_argument( "--raw", default=False, action="store_true", help="print raw logs" ) jobs_resubmit.add_argument( "--start", default=0, type=int, help="start at the given line" ) jobs_resubmit.add_argument( "--end", default=None, type=int, help="end at the given line" ) # "run" jobs_run = sub.add_parser("run", help="run the job") jobs_run.add_argument( "definition", type=argparse.FileType("r"), help="job definition" ) jobs_run.add_argument( "--filters", default=None, type=str, help="comma seperated list of levels to show", ) jobs_run.add_argument( "--no-follow", default=False, action="store_true", help="do not keep polling until the end of the job", ) jobs_run.add_argument( "--polling", default=5, type=int, help="polling interval in seconds [default=5s]", ) jobs_run.add_argument( "--raw", default=False, action="store_true", help="print raw logs" ) jobs_run.add_argument( "--start", default=0, type=int, help="start at the given line" ) jobs_run.add_argument("--end", default=None, type=int, help="end at the given line") # "show" jobs_show = sub.add_parser("show", help="job details") jobs_show.add_argument("job_id", help="job id") out_format = jobs_show.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) # "submit" jobs_submit = sub.add_parser("submit", help="submit a new job") jobs_submit.add_argument( "definition", nargs="+", type=argparse.FileType("r"), help="job definition" ) jobs_submit.add_argument( "--url", action="store_true", dest="print_url", default=False, help="Print the full url", ) if version >= (2019, 3): # "validate" jobs_validate = sub.add_parser("validate", help="validate the job definition") jobs_validate.add_argument( "definition", type=argparse.FileType("r"), help="job definition" ) jobs_validate.add_argument( "--strict", action="store_true", default=False, help="check in strict mode" ) if version >= (2018, 1): # "wait" jobs_wait = sub.add_parser("wait", help="wait for the job to finish") jobs_wait.add_argument("job_id", help="job id") jobs_wait.add_argument( "--polling", default=5, type=int, help="polling interval in seconds [default=5s]", ) jobs_wait.add_argument( "--timeout", default=0, type=int, help="Maximum time to wait in seconds, 0 to disable [default=0s]", ) def help_string(): return "manage jobs" def handle_cancel(proxy, options, _): for job_id in options.job_id: try: proxy.scheduler.jobs.cancel(job_id) except xmlrpc.client.Error as exc: print("Unable to cancel job %s: %s" % (job_id, exc2str(exc))) return 0 def handle_config(proxy, options, _): config = proxy.scheduler.jobs.configuration(options.job_id) definition, device, dispatcher, env, env_dut = config # Create the directory if needed dest = pathlib.Path(options.dest) with contextlib.suppress(FileExistsError): dest.mkdir(mode=0o755) # Save the files with (dest / "definition.yaml").open("w") as f_out: f_out.write(definition) if device is not None: with (dest / "device.yaml").open("w") as f_out: f_out.write(device) if dispatcher is not None: with (dest / "dispatcher.yaml").open("w") as f_out: f_out.write(dispatcher) if env is not None: with (dest / "env.yaml").open("w") as f_out: f_out.write(env) if env_dut is not None: with (dest / "env.dut.yaml").open("w") as f_out: f_out.write(env_dut) return 0 def handle_definition(proxy, options, _): print(proxy.scheduler.jobs.definition(options.job_id)) return 0 def handle_list(proxy, options, config): if config["version"] >= (2018, 10): jobs = proxy.scheduler.jobs.list( options.state, options.health, options.start, options.limit, options.since, options.verbose, ) elif config["version"] >= (2018, 4): jobs = proxy.scheduler.jobs.list( options.state, options.health, options.start, options.limit ) else: jobs = proxy.scheduler.jobs.list(options.start, options.limit) if options.output_format == "json": print(json.dumps(jobs)) elif options.output_format == "yaml": print(yaml.dump(jobs, default_flow_style=None).rstrip("\n")) else: print( "Jobs (from %s to %s):" % (1 + options.start, options.start + options.limit) ) for job in jobs: if config["version"] >= (2018, 10) and options.verbose: if job["error_type"]: print( "* %s: %s,%s [%s] (%s) - %s %s <%s> <%s> %s: %s" % ( job["id"], job["state"], job["health"], job["submitter"], job["description"], job["device_type"], job["actual_device"], job["start_time"], job["end_time"], job["error_type"], job["error_msg"], ) ) else: print( "* %s: %s,%s [%s] (%s) - %s %s <%s> <%s>" % ( job["id"], job["state"], job["health"], job["submitter"], job["description"], job["device_type"], job["actual_device"], job["start_time"], job["end_time"], ) ) elif config["version"] >= (2018, 1): print( "* %s: %s,%s [%s] (%s) - %s" % ( job["id"], job["state"], job["health"], job["submitter"], job["description"], job["device_type"], ) ) else: print( "* %s: %s [%s] (%s) - %s" % ( job["id"], job["status"], job["submitter"], job["description"], job["device_type"], ) ) return 0 if sys.stdout.isatty(): COLORS = { "exception": "\033[1;31m", "error": "\033[1;31m", "warning": "\033[1;33m", "info": "\033[1;37m", "debug": "", "target": "\033[32m", "input": "\033[0;35m", "feedback": "\033[0;33m", "results": "\033[1;34m", "dt": "\033[1;30m", "end": "\033[0m", } else: COLORS = { "exception": "", "error": "", "warning": "", "info": "", "debug": "", "target": "", "input": "", "feedback": "", "results": "", "dt": "", "end": "", } def print_logs(logs, raw, filters): filters = [] if filters is None else filters.split(",") if raw: for line in logs: if filters and not line["lvl"] in filters: continue print_u( "- " + yaml.dump( line, default_flow_style=True, default_style='"', width=10 ** 6, Dumper=yaml.CDumper, )[:-1] ) else: for line in logs: timestamp = line["dt"].split(".")[0] level = line["lvl"] if filters and level not in filters: continue if isinstance(line["msg"], dict) and "sending" in line["msg"].keys(): level = "input" msg = str(line["msg"]["sending"]) elif isinstance(line["msg"], bytes): msg = line["msg"].decode("utf-8", errors="replace") else: msg = str(line["msg"]) msg = msg.rstrip("\n") print_u( COLORS["dt"] + timestamp + COLORS["end"] + " " + COLORS[level] + msg + COLORS["end"] ) def _download_logs(proxy, version, job_id, start, end): if version >= (2018, 6): (finished, data) = proxy.scheduler.jobs.logs(job_id, start, end) logs = yaml.load(str(data), Loader=loader(False)) else: (finished, data) = proxy.scheduler.jobs.logs(job_id, start) logs = yaml.load(str(data), Loader=loader(False)) if end is not None and len(logs) >= end - start: if end < start: end = start logs = logs[: end - start] return (finished, logs) def handle_logs(proxy, options, config): # Loop lines = options.start while True: (finished, logs) = _download_logs( proxy, config["version"], options.job_id, lines, options.end ) if logs: print_logs(logs, options.raw, options.filters) lines += len(logs) # Loop only if the job is not finished if ( finished or options.no_follow or (options.end is not None and lines >= options.end) ): break # Wait some time time.sleep(options.polling) # Print the failure comment if the job is finished if finished: details = proxy.scheduler.jobs.show(options.job_id) if details.get("failure_comment"): print_logs( [ { "dt": datetime.datetime.utcnow().isoformat(), "lvl": "info", "msg": "[lavacli] Failure comment: %s" % details["failure_comment"], } ], options.raw, options.filters, ) return 0 def handle_queue(proxy, options, config): dts = options.device_types if options.device_types else None data = proxy.scheduler.jobs.queue(dts, options.start, options.limit) if options.output_format == "json": print(json.dumps(data)) elif options.output_format == "yaml": print(yaml.dump(data, default_flow_style=None).rstrip("\n")) else: print( "Jobs (from %s to %s):" % (1 + options.start, options.start + options.limit) ) for job in data: print( "* %s: %s (%s) - %s" % ( job["id"], job["submitter"], job["description"] if job["description"] else "", job["requested_device_type"], ) ) return 0 def handle_resubmit(proxy, options, config): job_id = proxy.scheduler.jobs.resubmit(options.job_id) if options.no_follow: prefix = "" if options.print_url: parsed = urlparse(options.uri) host = parsed.netloc.split("@")[-1] prefix = "%s://%s/scheduler/job/" % (parsed.scheme, host) if isinstance(job_id, list): for job in job_id: print(prefix + str(job)) else: print(prefix + str(job_id)) else: print_logs( [ { "dt": datetime.datetime.utcnow().isoformat(), "lvl": "info", "msg": "[lavacli] Job %s submitted" % job_id, } ], options.raw, options.filters, ) # Add the job_id to options for handle_logs # For multinode, print something and loop on all jobs if isinstance(job_id, list): for job in job_id: print_logs( [ { "dt": datetime.datetime.utcnow().isoformat(), "lvl": "info", "msg": "[lavacli] Seeing %s logs" % job, } ], options.raw, options.filters, ) options.job_id = job handle_logs(proxy, options, config) else: options.job_id = str(job_id) handle_logs(proxy, options, config) return 0 def handle_run(proxy, options, config): job_id = proxy.scheduler.jobs.submit(options.definition.read()) print_logs( [ { "dt": datetime.datetime.utcnow().isoformat(), "lvl": "info", "msg": "[lavacli] Job %s submitted" % job_id, } ], options.raw, options.filters, ) # Add the job_id to options for handle_logs # For multinode, print something and loop on all jobs if isinstance(job_id, list): for job in job_id: print_logs( [ { "dt": datetime.datetime.utcnow().isoformat(), "lvl": "info", "msg": "[lavacli] Seeing %s logs" % job, } ], options.raw, options.filters, ) options.job_id = job handle_logs(proxy, options, config) else: options.job_id = job_id handle_logs(proxy, options, config) return 0 def handle_show(proxy, options, config): job = proxy.scheduler.jobs.show(options.job_id) if options.output_format == "json": job["submit_time"] = job["submit_time"].value job["start_time"] = job["start_time"].value job["end_time"] = job["end_time"].value print(json.dumps(job)) elif options.output_format == "yaml": job["submit_time"] = job["submit_time"].value job["start_time"] = job["start_time"].value job["end_time"] = job["end_time"].value print(yaml.dump(job, default_flow_style=None).rstrip("\n")) else: print("id : %s" % job["id"]) print("description : %s" % job["description"]) print("submitter : %s" % job["submitter"]) print("device-type : %s" % job["device_type"]) print("device : %s" % job["device"]) print("health-check: %s" % job["health_check"]) if config["version"] >= (2018, 1): print("state : %s" % job["state"]) print("Health : %s" % job["health"]) else: print("status : %s" % job["status"]) if job.get("failure_comment"): print("failure : %s" % job["failure_comment"]) print("pipeline : %s" % job["pipeline"]) print("tags : %s" % str(job["tags"])) print("visibility : %s" % job["visibility"]) print("submit time : %s" % job["submit_time"]) print("start time : %s" % job["start_time"]) print("end time : %s" % job["end_time"]) return 0 def handle_submit(proxy, options, _): prefix = "" if options.print_url: parsed = urlparse(options.uri) host = parsed.netloc.split("@")[-1] prefix = "%s://%s/scheduler/job/" % (parsed.scheme, host) for definition in options.definition: try: job_id = proxy.scheduler.jobs.submit(definition.read()) if isinstance(job_id, list): for job in job_id: print(prefix + str(job)) else: print(prefix + str(job_id)) except xmlrpc.client.Error as exc: print("Unable to submit %s: %s" % (definition.name, exc2str(exc))) return 0 def handle_validate(proxy, options, _): ret = proxy.scheduler.jobs.validate(options.definition.read(), options.strict) if not ret: return 0 print("key: %s" % ret["path"]) print("msg: %s" % ret["msg"]) return 1 def handle_wait(proxy, options, _): job = proxy.scheduler.jobs.show(options.job_id) old_state = "" time_elapsed = 0 while job["state"] != "Finished": if old_state != job["state"]: if old_state: sys.stdout.write("\n") sys.stdout.write(job["state"]) else: sys.stdout.write(".") sys.stdout.flush() old_state = job["state"] time.sleep(options.polling) job = proxy.scheduler.jobs.show(options.job_id) if options.timeout > 0: time_elapsed = time_elapsed + options.polling if time_elapsed > options.timeout: print("timeout!") return 1 if old_state != job["state"] and old_state: sys.stdout.write("\n") return 0 def handle(proxy, options, config): handlers = { "cancel": handle_cancel, "config": handle_config, "definition": handle_definition, "list": handle_list, "logs": handle_logs, "queue": handle_queue, "resubmit": handle_resubmit, "run": handle_run, "show": handle_show, "submit": handle_submit, "validate": handle_validate, "wait": handle_wait, } return handlers[options.sub_sub_command](proxy, options, config) lavacli-v0.9.8/lavacli/commands/results.py000066400000000000000000000065741354067014100206350ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import yaml from lavacli.utils import loader def configure_parser(parser, _): parser.add_argument("job_id", help="job id") parser.add_argument("test_suite", nargs="?", default=None, help="test suite") parser.add_argument("test_case", nargs="?", default=None, help="test case") out_format = parser.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", default=None, action="store_const", const="yaml", help="print as yaml", ) def help_string(): return "manage results" def handle(proxy, options, _): if options.test_case is not None: data = proxy.results.get_testcase_results_yaml( options.job_id, options.test_suite, options.test_case ) elif options.test_suite is not None: data = proxy.results.get_testsuite_results_yaml( options.job_id, options.test_suite ) else: data = proxy.results.get_testjob_results_yaml(options.job_id) results = yaml.load(data, Loader=loader()) # nosec - loader() returns a safe loader if options.output_format == "json": print(json.dumps(results)) elif options.output_format == "yaml": print(yaml.dump(results, default_flow_style=None).rstrip("\n")) else: # Only print the result if options.test_case is not None: for res in results: if not sys.stdout.isatty(): print("%s" % res["result"]) elif res["result"] == "pass": print("\033[1;32mpass\033[0m") elif res["result"] == "fail": print("\033[1;31mfail\033[0m") else: print("%s" % res["result"]) # A list to print else: print("Results:") for res in results: if not sys.stdout.isatty(): print("* %s.%s [%s]" % (res["suite"], res["name"], res["result"])) elif res["result"] == "pass": print( "* %s.%s [\033[1;32mpass\033[0m]" % (res["suite"], res["name"]) ) elif res["result"] == "fail": print( "* %s.%s [\033[1;31mfail\033[0m]" % (res["suite"], res["name"]) ) else: print("* %s.%s [%s]" % (res["suite"], res["name"], res["result"])) return 0 lavacli-v0.9.8/lavacli/commands/system.py000066400000000000000000000224311354067014100204460ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import contextlib import pathlib import shutil import time import xmlrpc.client import yaml def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "active" if version >= (2017, 12): sub.add_parser("active", help="activate the system") # "api" sub.add_parser("api", help="print server API version") # "export" sys_export = sub.add_parser("export", help="export server configuration") sys_export.add_argument("name", help="name of the export") sys_export.add_argument( "--full", default=False, action="store_true", help="do a full export, including retired devices", ) # "import" # sub.add_parser("import", help="import server configuration") # "maintenance" if version >= (2017, 12): sys_maintenance = sub.add_parser("maintenance", help="maintenance the system") sys_maintenance.add_argument( "--force", default=False, action="store_true", help="force maintenance by canceling jobs", ) sys_maintenance.add_argument( "--exclude", default=None, help="comma seperated list of workers to keep untouched", ) # "methods" sys_methods = sub.add_parser("methods", help="list methods") sys_sub = sys_methods.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) sys_sub.required = True sys_sub.add_parser("list", help="list available methods") sys_help = sys_sub.add_parser("help", help="method help") sys_help.add_argument("method", help="method name") sys_signature = sys_sub.add_parser("signature", help="method signature") sys_signature.add_argument("method", help="method name") # "version" sub.add_parser("version", help="print the server version") # "whoami" sub.add_parser("whoami", help="print the current username") def help_string(): return "system information" def handle_active(proxy, _, __): print("Activate workers:") workers = proxy.scheduler.workers.list() for worker in workers: print("* %s" % worker) proxy.scheduler.workers.update(worker, None, "ACTIVE") return 0 def handle_api(proxy, _, __): print(proxy.system.api_version()) return 0 def handle_export(proxy, options, config): print("Export to %s" % options.name) dest = pathlib.Path(options.name) with contextlib.suppress(FileNotFoundError): shutil.rmtree(str(dest)) with contextlib.suppress(FileExistsError): dest.mkdir(mode=0o755) print("Listing aliases") aliases = [] for alias in proxy.scheduler.aliases.list(): print("* %s" % alias) aliases.append(proxy.scheduler.aliases.show(alias)) print("Listing tags") tags = [] for tag in proxy.scheduler.tags.list(): print("* %s" % tag["name"]) tags.append(tag) print("Listing workers") workers = [] for worker in proxy.scheduler.workers.list(): print("* %s" % worker) w = proxy.scheduler.workers.show(worker) if config["version"] >= (2017, 12): workers.append( { "hostname": w["hostname"], "description": w["description"], "state": w["state"], "health": w["health"], } ) else: workers.append( { "hostname": w["hostname"], "description": w["description"], "master": w["master"], "hidden": w["hidden"], } ) print("Listing device-types") (dest / "device-types").mkdir(mode=0o755) device_types = [] for device_type in proxy.scheduler.device_types.list(): print("* %s" % device_type["name"]) dt = proxy.scheduler.device_types.show(device_type["name"]) device_types.append( { "name": dt["name"], "description": dt["description"], "display": dt["display"], "health_disabled": dt["health_disabled"], "owners_only": dt["owners_only"], "aliases": dt["aliases"], } ) try: dt_template = proxy.scheduler.device_types.get_template(dt["name"]) except xmlrpc.client.Fault as exc: if exc.faultCode == 404: print(" => No template found") continue raise with (dest / "device-types" / ("%s.jinja2" % dt["name"])).open( "w", encoding="utf-8" ) as f_out: f_out.write(str(dt_template)) print("Listing devices") (dest / "devices").mkdir(mode=0o755) devices = [] for device in proxy.scheduler.devices.list(options.full): print("* %s" % device["hostname"]) d = proxy.scheduler.devices.show(device["hostname"]) devices.append( { "hostname": d["hostname"], "description": d["description"], "device_type": d["device_type"], "pipeline": d["pipeline"], "worker": d["worker"], "state": d["state"], "health": d["health"], "public": d["public"], "user": d["user"], "group": d["group"], "tags": d["tags"], } ) try: device_dict = proxy.scheduler.devices.get_dictionary(device["hostname"]) except xmlrpc.client.Fault as exc: if exc.faultCode == 404: print(" => No device dict found") continue raise with (dest / "devices" / ("%s.jinja2" % device["hostname"])).open( "w", encoding="utf-8" ) as f_out: f_out.write(str(device_dict)) export = { "aliases": aliases, "devices": devices, "device-types": device_types, "tags": tags, "workers": workers, } # Dump the configuration with (dest / "instance.yaml").open("w", encoding="utf-8") as f_out: f_out.write(yaml.dump(export, default_flow_style=None).rstrip("\n")) return 0 def handle_maintenance(proxy, options, _): print("Maintenance workers:") workers = proxy.scheduler.workers.list() excluded_workers = [] if options.exclude: excluded_workers = options.exclude.split(",") for worker in workers: if worker in excluded_workers: print("* %s [SKIP]" % worker) continue print("* %s" % worker) proxy.scheduler.workers.update(worker, None, "MAINTENANCE") excluded_devices = [] if excluded_workers: for worker in excluded_workers: excluded_devices.extend(proxy.scheduler.workers.show(worker)["devices"]) print("Wait for devices:") devices = proxy.scheduler.devices.list() for device in devices: if device["hostname"] in excluded_devices: continue print("* %s" % device["hostname"]) current_job = device["current_job"] if current_job is not None: print("--> waiting for job %s" % current_job) # if --force is passed, cancel the job if options.force: print("---> canceling") proxy.scheduler.jobs.cancel(current_job) while proxy.scheduler.jobs.show(current_job)["state"] != "Finished": print("---> waiting") time.sleep(5) return 0 def handle_methods(proxy, options, _): if options.sub_sub_sub_command == "help": print(proxy.system.methodHelp(options.method)) elif options.sub_sub_sub_command == "signature": print(proxy.system.methodSignature(options.method)) else: # Fallback to "list" methods = proxy.system.listMethods() for method in methods: print(method) return 0 def handle_version(proxy, _, __): print(proxy.system.version()) return 0 def handle_whoami(proxy, _, __): username = proxy.system.whoami() if username is None: print("") else: print(username) return 0 def handle(proxy, options, config): handlers = { "active": handle_active, "api": handle_api, "export": handle_export, "maintenance": handle_maintenance, "methods": handle_methods, "version": handle_version, "whoami": handle_whoami, } return handlers[options.sub_sub_command](proxy, options, config) lavacli-v0.9.8/lavacli/commands/tags.py000066400000000000000000000072351354067014100200650ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import yaml def configure_parser(parser, _): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "add" tags_add = sub.add_parser("add", help="add a tag") tags_add.add_argument("tag", help="tag name") tags_add.add_argument("--description", default=None, help="tag description") # "delete" tags_delete = sub.add_parser("delete", help="delete a tag") tags_delete.add_argument("tag", help="tag name") # "list" tags_list = sub.add_parser("list", help="list tags") out_format = tags_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", help="print as yaml", ) # "show" tags_show = sub.add_parser("show", help="show tag details") tags_show.add_argument("tag", help="tag name") out_format = tags_show.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", help="print as yaml", ) def help_string(): return "manage device tags" def handle_add(proxy, options): proxy.scheduler.tags.add(options.tag, options.description) return 0 def handle_delete(proxy, options): proxy.scheduler.tags.delete(options.tag) return 0 def handle_list(proxy, options): tags = proxy.scheduler.tags.list() if options.output_format == "json": print(json.dumps(tags)) elif options.output_format == "yaml": print(yaml.dump(tags, default_flow_style=None).rstrip("\n")) else: print("Tags:") for tag in tags: if tag["description"]: print("* %s (%s)" % (tag["name"], tag["description"])) else: print("* %s" % tag["name"]) return 0 def handle_show(proxy, options): tag = proxy.scheduler.tags.show(options.tag) if options.output_format == "json": print(json.dumps(tag)) elif options.output_format == "yaml": print(yaml.dump(tag, default_flow_style=None).rstrip("\n")) else: print("name : %s" % tag["name"]) print("description: %s" % tag["description"]) print("devices :") for device in tag["devices"]: print("* %s" % device) return 0 def handle(proxy, options, _): handlers = { "add": handle_add, "delete": handle_delete, "list": handle_list, "show": handle_show, } return handlers[options.sub_sub_command](proxy, options) lavacli-v0.9.8/lavacli/commands/utils.py000066400000000000000000000075001354067014100202620ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import argparse import jinja2 import yaml from lavacli.utils import loader from . import jobs def configure_parser(parser, _): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "logs" logs = sub.add_parser("logs", help="log helpers") logs_sub = logs.add_subparsers(dest="sub_sub_sub_command", help="Sub commands") logs_sub.required = True # "logs.print" logs_print = logs_sub.add_parser("print", help="print log file") logs_print.add_argument("filename", type=argparse.FileType("r"), help="log file") logs_print.add_argument( "--filters", default=None, type=str, help="comma seperated list of levels to show", ) logs_print.add_argument( "--raw", default=False, action="store_true", help="print raw logs" ) # "templates" templates = sub.add_parser("templates", help="template helpers") templates_sub = templates.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) templates_sub.required = True # "templates.render" # TODO: add an option to be strict about undefined variables templates_render = templates_sub.add_parser("render", help="render jinja2 template") templates_render.add_argument( "filename", type=argparse.FileType("r"), help="template" ) templates_render.add_argument( "--path", type=str, action="append", help="templates lookup path" ) templates_render.add_argument( "--context", type=str, action="append", default=[], help="context variables" ) templates_render.add_argument( "--trim", action="store_true", default=False, help="trim blocks" ) def help_string(): return "utility functions" def handle_logs(_, options): try: logs = yaml.load(options.filename.read(), Loader=loader(False)) except yaml.YAMLError: print("Invalid yaml file") else: jobs.print_logs(logs, options.raw, options.filters) def handle_templates(_, options): assert options.sub_sub_sub_command == "render" # Set the default value here # If we give it to argparse, then it's always present even when --path is # passed. if options.path is None: options.path = ["/etc/lava-server/dispatcher-config/device-types"] env = jinja2.Environment( # nosec - used to render yaml autoescape=False, trim_blocks=options.trim, loader=jinja2.FileSystemLoader(options.path), ) data = options.filename.read() template = env.from_string(data) # Build the context try: context = {k.split("=")[0]: k.split("=")[1] for k in options.context} except Exception: print("Invalid context variable") print("Should be of the form key=value") return 1 try: print(template.render(**context)) return 0 except jinja2.TemplateNotFound: print("Unable to find the templates") return 1 def handle(proxy, options, _): handlers = {"logs": handle_logs, "templates": handle_templates} return handlers[options.sub_sub_command](proxy, options) lavacli-v0.9.8/lavacli/commands/workers.py000066400000000000000000000225241354067014100206210ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import argparse import json import time import yaml def configure_parser(parser, version): sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands") sub.required = True # "add" workers_add = sub.add_parser("add", help="add a worker") workers_add.add_argument("hostname", type=str, help="worker hostname") workers_add.add_argument( "--description", type=str, default=None, help="worker description" ) workers_add.add_argument( "--disabled", action="store_true", default=False, help="create a disabled worker", ) # "config" workers_config = sub.add_parser("config", help="worker configuration") config_sub = workers_config.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) config_sub.required = True config_get = config_sub.add_parser("get", help="get the worker configuration") config_get.add_argument("hostname", type=str, help="worker hostname") config_set = config_sub.add_parser("set", help="set the worker configuration") config_set.add_argument("hostname", type=str, help="worker hostname") config_set.add_argument( "config", type=argparse.FileType("r"), help="configuration file" ) if version >= (2019, 6): # "env" workers_env = sub.add_parser("env", help="worker environment") env_sub = workers_env.add_subparsers( dest="sub_sub_sub_command", help="Sub commands" ) env_sub.required = True env_get = env_sub.add_parser("get", help="get the worker environment") env_get.add_argument("hostname", type=str, help="worker hostname") env_set = env_sub.add_parser("set", help="set the worker environment") env_set.add_argument("hostname", type=str, help="worker hostname") env_set.add_argument( "env", type=argparse.FileType("r"), help="environment file" ) # "list" workers_list = sub.add_parser("list", help="list workers") out_format = workers_list.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) # "maintenance" workers_maintenance = sub.add_parser("maintenance", help="maintenance the worker") workers_maintenance.add_argument("hostname", type=str, help="worker hostname") workers_maintenance.add_argument( "--force", default=False, action="store_true", help="force worker maintenance by canceling running jobs", ) workers_maintenance.add_argument( "--no-wait", dest="wait", default=True, action="store_false", help="do not wait for the devices to be idle", ) # "show" workers_show = sub.add_parser("show", help="show worker details") workers_show.add_argument("hostname", help="worker hostname") out_format = workers_show.add_mutually_exclusive_group() out_format.add_argument( "--json", dest="output_format", default=None, action="store_const", const="json", help="print as json", ) out_format.add_argument( "--yaml", dest="output_format", action="store_const", const="yaml", default=None, help="print as yaml", ) # "update" update_parser = sub.add_parser("update", help="update worker properties") update_parser.add_argument("hostname", type=str, help="worker hostname") update_parser.add_argument( "--description", type=str, default=None, help="worker description" ) if version >= (2017, 12): update_parser.add_argument( "--health", type=str, default=None, choices=["ACTIVE", "MAINTENANCE", "RETIRED"], help="worker health", ) else: display = update_parser.add_mutually_exclusive_group() display.add_argument( "--disable", action="store_false", default=None, dest="display", help="disable the worker", ) display.add_argument( "--enable", action="store_true", default=None, dest="display", help="enable the worker", ) def help_string(): return "manage workers" def handle_add(proxy, options, _): proxy.scheduler.workers.add(options.hostname, options.description, options.disabled) return 0 def handle_config(proxy, options, _): if options.sub_sub_sub_command == "get": config = proxy.scheduler.workers.get_config(options.hostname) print(str(config).rstrip("\n")) else: config = options.config.read() ret = proxy.scheduler.workers.set_config(options.hostname, config) if not ret: print("Unable to store worker configuration") return 1 return 0 def handle_env(proxy, options, _): if options.sub_sub_sub_command == "get": env = proxy.scheduler.workers.get_env(options.hostname) print(str(env).rstrip("\n")) else: env = options.env.read() ret = proxy.scheduler.workers.set_env(options.hostname, env) if not ret: print("Unable to store worker environment") return 1 return 0 def handle_list(proxy, options, _): workers = proxy.scheduler.workers.list() if options.output_format == "json": print(json.dumps(workers)) elif options.output_format == "yaml": print(yaml.dump(workers, default_flow_style=None).rstrip("\n")) else: print("Workers:") for worker in workers: print("* %s" % worker) return 0 def handle_maintenance(proxy, options, _): proxy.scheduler.workers.update(options.hostname, None, "MAINTENANCE") if options.force or options.wait: worker_devices = proxy.scheduler.workers.show(options.hostname)["devices"] for device in proxy.scheduler.devices.list(): if device["hostname"] not in worker_devices: continue current_job = device["current_job"] if current_job is not None: print("-> waiting for job %s" % current_job) # if --force is passed, cancel the job if options.force: print("--> canceling") proxy.scheduler.jobs.cancel(current_job) while ( options.wait and proxy.scheduler.jobs.show(current_job)["state"] != "Finished" ): print("--> waiting") time.sleep(5) return 0 def handle_show(proxy, options, config): worker = proxy.scheduler.workers.show(options.hostname) if options.output_format == "json": if "last_ping" in worker: worker["last_ping"] = worker["last_ping"].value print(json.dumps(worker)) elif options.output_format == "yaml": if "last_ping" in worker: worker["last_ping"] = worker["last_ping"].value print(yaml.dump(worker, default_flow_style=None).rstrip("\n")) else: print("hostname : %s" % worker["hostname"]) print("description : %s" % worker["description"]) if config["version"] >= (2017, 12): print("state : %s" % worker["state"]) print("health : %s" % worker["health"]) else: print("master : %s" % worker["master"]) print("hidden : %s" % worker["hidden"]) if config["version"] >= (2018, 1): print("devices : %s" % ", ".join(worker["devices"])) print("last ping : %s" % worker["last_ping"]) else: print("devices : %d" % worker["devices"]) return 0 def handle_update(proxy, options, config): if config["version"] >= (2017, 12): proxy.scheduler.workers.update( options.hostname, options.description, options.health ) else: proxy.scheduler.workers.update( options.hostname, options.description, not options.display ) return 0 def handle(proxy, options, config): handlers = { "add": handle_add, "config": handle_config, "env": handle_env, "list": handle_list, "maintenance": handle_maintenance, "show": handle_show, "update": handle_update, } return handlers[options.sub_sub_command](proxy, options, config) lavacli-v0.9.8/lavacli/utils.py000066400000000000000000000031351354067014100164610ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import re import xmlrpc.client import yaml def print_u(string): try: print(string) except UnicodeEncodeError: print(string.encode("ascii", errors="replace").decode("ascii")) VERSION_LATEST = (3000, 1) def parse_version(version): pattern = re.compile(r"(?P20\d{2})\.(?P\d{1,2})") if not isinstance(version, str): version = str(version) m = pattern.match(version) if m is None: return VERSION_LATEST res = m.groupdict() return (int(res["major"]), int(res["minor"])) def loader(safe=True): try: return yaml.CSafeLoader if safe else yaml.CLoader except AttributeError: # TODO log a warning on stderr return yaml.SafeLoader if safe else yaml.Loader def exc2str(exc): if isinstance(exc, xmlrpc.client.ProtocolError): return exc.errmsg return str(exc) lavacli-v0.9.8/requirements.txt000066400000000000000000000000351354067014100166140ustar00rootroot00000000000000jinja2 PyYAML pyzmq requests lavacli-v0.9.8/setup.py000066400000000000000000000045771354067014100150610ustar00rootroot00000000000000#!/usr/bin/python3 # -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see from setuptools import setup # grab metadata without importing the module metadata = {} with open("lavacli/__about__.py", encoding="utf-8") as fp: exec(fp.read(), metadata) # Setup the package setup( name="lavacli", version=metadata["__version__"], description=metadata["__description__"], author=metadata["__author__"], author_email=metadata["__author_email__"], license=metadata["__license__"], url=metadata["__url__"], project_urls={ "Bug Tracker": "https://git.lavasoftware.org/lava/lavacli/issues/", "Documentation": "https://docs.lavasoftware.org/lavacli/", "Source Code": "https://git.lavasoftware.org/lava/lavacli/", }, python_requires=">=3.4", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3 :: Only", "Topic :: Communications", "Topic :: Software Development :: Testing", "Topic :: System :: Networking", ], packages=["lavacli", "lavacli.commands"], entry_points={"console_scripts": ["lavacli = lavacli:main"]}, install_requires=["jinja2", "PyYAML", "pyzmq", "requests"], setup_requires=["pytest-runner"], tests_require=["pytest"], zip_safe=True, ) lavacli-v0.9.8/share/000077500000000000000000000000001354067014100144345ustar00rootroot00000000000000lavacli-v0.9.8/share/lavacli.yaml000066400000000000000000000015061354067014100167350ustar00rootroot00000000000000validation: uri: https://validation.linaro.org/RPC2 # proxy: https://:@my.proxy:3128/ # : '' # force a direct connection # By default, lavacli, uses the https_proxy env variable # timeout: 20.0 # connection timeout # verify_ssl_cert: true # check SSL certificates events: uri: tcp://validation.linaro.org:5510 # socks_proxy: localhost:8081 user@validation: uri: https://validation.linaro.org/RPC2 username: token: # It's also possible to include the username and the token in the uri directly. # uri: https://:@validation.linaro.org/RPC2 staging: uri: https://staging.valiation.linaro.org/RPC2 events: uri: tcp://staging.validation.linaro.org:5500 localhost: uri: https://localhost/RPC2 timeout: 30.0 verify_ssl_cert: false lavacli-v0.9.8/share/release.sh000077500000000000000000000036011354067014100164130ustar00rootroot00000000000000#!/bin/bash set -eu ########### # Helpers # ########### show_help() { cat << EOF Usage: [-c] [-p] [-b] [-u] VERSION Prepare, build and upload a new release -c clean the current directory -p prepare the release -b build artefacts (pypi and debian) -u upload the release EOF } ######################## # Command line parsing # ######################## FULL=1 CLEAN=0 PREPARE=0 BUILD=0 UPLOAD=0 while getopts "bcpuh" opt; do case $opt in c) CLEAN=1 FULL=0 ;; p) PREPARE=1 FULL=0 ;; b) BUILD=1 FULL=0 ;; u) UPLOAD=1 FULL=0 ;; h) show_help exit 0 ;; ?) show_help >&2 exit 1 esac done shift "$((OPTIND-1))" if [ "$FULL" = "1" ] then BUILD=1 CLEAN=1 PREPARE=1 UPLOAD=1 fi TAG="$*" if [ "$PREPARE" = "1" -a "$TAG" = "" ] then echo "Missing version" >&2 show_help >&2 exit 1 fi # clean if [ "$CLEAN" = "1" ] then echo "Cleaning..." rm -rf build-area dist lavacli.egg-info echo "done" echo fi # Prepare the release if [ "$PREPARE" = "1" ] then echo "Preparing..." echo "* debian/changelog" read gbp dch --new-version="$TAG-1" --release --commit --commit-msg="Prepare for release v$TAG" echo "* lavacli/__about__.py version" read edit lavacli/__about__.py git commit --amend lavacli/__about__.py --message="Prepare for release v$TAG" echo "* git tag" read git tag --annotate --sign "v$TAG" echo "done" echo fi # Build the release artefacts if [ "$BUILD" = "1" ] then echo "Building..." python3 setup.py sdist gbp buildpackage -us -uc echo "done" echo fi if [ "$UPLOAD" = "1" ] then echo "Uploading..." # Push the release echo "* git push --tags origin master" read git push --tags origin master # Uploading to pypi.org echo "* twine upload dist" read twine upload dist echo "done" echo fi lavacli-v0.9.8/tests/000077500000000000000000000000001354067014100144745ustar00rootroot00000000000000lavacli-v0.9.8/tests/__init__.py000066400000000000000000000000001354067014100165730ustar00rootroot00000000000000lavacli-v0.9.8/tests/conftest.py000066400000000000000000000034301354067014100166730ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2017 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import pytest import xmlrpc.client import yaml class RecordingProxyFactory(object): def __new__(self, proxy_data): class RecordingProxy(object): data = proxy_data def __init__(self, uri, allow_none, transport): self.request = [] def __call__(self, *args): request = ".".join(self.request) self.request = [] data = self.data.pop(0) assert request == data["request"] # nosec assert args == data["args"] # nosec return data["ret"] def __getattr__(self, attr): self.request.append(attr) return self return RecordingProxy @pytest.fixture def setup(monkeypatch, tmpdir): monkeypatch.setenv("XDG_CONFIG_HOME", str(tmpdir)) with (tmpdir / "lavacli.yaml").open("w") as f_conf: f_conf.write(yaml.dump({"default": {"uri": "https://lava.example.com/RPC2"}})) monkeypatch.setattr(xmlrpc.client, "ServerProxy", RecordingProxyFactory(None)) lavacli-v0.9.8/tests/test_aliases.py000066400000000000000000000214561354067014100175360ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import xmlrpc.client from lavacli import main def test_aliases_add_before_2019_05(setup, monkeypatch, capsys): version = "2019.04" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "add", "new_alias"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.aliases.add", "args": ("new_alias",), "ret": None}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_aliases_add(setup, monkeypatch, capsys): version = "2019.05" monkeypatch.setattr( sys, "argv", ["lavacli", "aliases", "add", "new_alias", "device-type"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.add", "args": ("new_alias", "device-type"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_aliases_delete(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "delete", "new_alias"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.delete", "args": ("new_alias",), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_aliases_list_empty(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.aliases.list", "args": (), "ret": []}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Aliases:\n" # nosec def test_aliases_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.list", "args": (), "ret": ["first-alias", "second-alias"], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Aliases:\n* first-alias\n* second-alias\n" ) def test_aliases_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "list", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.list", "args": (), "ret": ["first-alias", "second-alias"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == '["first-alias", "second-alias"]\n' # nosec def test_aliases_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "list", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.list", "args": (), "ret": ["first-alias", "second-alias"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "[first-alias, second-alias]\n" # nosec def test_aliases_show_before_2019_05(setup, monkeypatch, capsys): version = "2019.04" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "show", "my_alias"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.show", "args": ("my_alias",), "ret": {"name": "my_alias", "device_types": ["qemu", "kvm"]}, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "name : my_alias\ndevice-types:\n* qemu\n* kvm\n" ) def test_aliases_show(setup, monkeypatch, capsys): version = "2019.05" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "show", "my_alias"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.show", "args": ("my_alias",), "ret": {"name": "my_alias", "device_type": "qemu"}, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "name : my_alias\ndevice-type: qemu\n" ) def test_aliases_show_json_before_2019_05(setup, monkeypatch, capsys): version = "2019.04" monkeypatch.setattr( sys, "argv", ["lavacli", "aliases", "show", "my_alias", "--json"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.show", "args": ("my_alias",), "ret": {"name": "my_alias", "device_types": ["qemu", "kvm"]}, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "name": "my_alias", "device_types": ["qemu", "kvm"], } def test_aliases_show_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "aliases", "show", "kvm", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.show", "args": ("kvm",), "ret": {"name": "kvm", "device_type": "qemu"}, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "name": "kvm", "device_type": "qemu", } def test_aliases_show_yaml_before_2019_05(setup, monkeypatch, capsys): version = "2019.04" monkeypatch.setattr( sys, "argv", ["lavacli", "aliases", "show", "my_alias", "--yaml"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.show", "args": ("my_alias",), "ret": {"name": "my_alias", "device_types": ["qemu", "kvm"]}, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "device_types: [qemu, kvm]\nname: my_alias\n" ) def test_aliases_show_yaml(setup, monkeypatch, capsys): version = "2019.05" monkeypatch.setattr( sys, "argv", ["lavacli", "aliases", "show", "my_alias", "--yaml"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.aliases.show", "args": ("my_alias",), "ret": {"name": "my_alias", "device_type": "qemu"}, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "{device_type: qemu, name: my_alias}\n" # nosec lavacli-v0.9.8/tests/test_device_types.py000066400000000000000000000474431354067014100206040ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import pytest import sys import xmlrpc.client import yaml from lavacli import main def test_dt_add(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "device-types", "add", "mydt"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.add", "args": ("mydt", None, True, False, 24, "hours"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_add_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "device-types", "add", "mydt", "--description", "my new dt", "--hide", "--owners-only", "--health-frequency", "12", "--health-denominator", "jobs", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.add", "args": ("mydt", "my new dt", False, True, 12, "jobs"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_aliases_add(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "aliases", "add", "mydt", "myalias"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.aliases.add", "args": ("mydt", "myalias"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_aliases_delete(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "aliases", "delete", "mydt", "myalias"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.aliases.delete", "args": ("mydt", "myalias"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_aliases_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "aliases", "list", "mydt"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.aliases.list", "args": ("mydt",), "ret": ["first alias", "second alias"], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Aliases:\n* first alias\n* second alias\n" ) def test_dt_aliases_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "aliases", "list", "mydt", "--json"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.aliases.list", "args": ("mydt",), "ret": ["first alias", "second alias"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == '["first alias", "second alias"]\n' # nosec def test_dt_aliases_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "aliases", "list", "mydt", "--yaml"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.aliases.list", "args": ("mydt",), "ret": ["first alias", "second alias"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "[first alias, second alias]\n" # nosec def test_dt_aliases_list_empty(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "aliases", "list", "mydt"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.aliases.list", "args": ("mydt",), "ret": [], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Aliases:\n" # nosec def test_dt_hc_get_before_2018_4(setup, monkeypatch, capsys): version = "2018.2" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "health-check", "get", "mydt"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": None, "args": (), "ret": []}, ], ) with pytest.raises(SystemExit): main() assert ( # nosec capsys.readouterr()[1] == """usage: lavacli device-types [-h] {add,aliases,list,show,template,update} ... lavacli device-types: error: argument sub_sub_command: invalid choice: 'health-check' (choose from 'add', 'aliases', 'list', 'show', 'template', 'update') """ ) def test_dt_hc_set_before_2018_4(setup, monkeypatch, capsys): version = "2018.2" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "health-check", "set", "mydt"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": None, "args": (), "ret": []}, ], ) with pytest.raises(SystemExit): main() assert ( # nosec capsys.readouterr()[1] == """usage: lavacli device-types [-h] {add,aliases,list,show,template,update} ... lavacli device-types: error: argument sub_sub_command: invalid choice: 'health-check' (choose from 'add', 'aliases', 'list', 'show', 'template', 'update') """ ) def test_dt_hc_get_after_2018_4(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "health-check", "get", "mydt"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.get_health_check", "args": ("mydt",), "ret": "definition.yaml", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "definition.yaml\n" # nosec def test_dt_hc_set_after_2018_4(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "hc.yaml").open("w") as f_hc: f_hc.write("definition") monkeypatch.setattr( sys, "argv", [ "lavacli", "device-types", "health-check", "set", "mydt", str(tmpdir / "hc.yaml"), ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.set_health_check", "args": ("mydt", "definition"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "device-types", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.list", "args": (False,), "ret": [ {"name": "bbb", "devices": 0, "installed": True, "template": True}, {"name": "qemu", "devices": 3, "installed": True, "template": True}, ], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Device-Types:\n* bbb (0)\n* qemu (3)\n" # nosec def test_dt_list_all(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "device-types", "list", "--all"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.list", "args": (True,), "ret": [ {"name": "bbb", "devices": 0, "installed": False, "template": True}, {"name": "qemu", "devices": 3, "installed": True, "template": True}, ], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Device-Types:\n* bbb (0)\n* qemu (3)\n" # nosec def test_dt_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "device-types", "list", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.list", "args": (False,), "ret": [ {"name": "bbb", "devices": 0, "installed": True, "template": True}, {"name": "qemu", "devices": 3, "installed": True, "template": True}, ], }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec {"name": "bbb", "devices": 0, "installed": True, "template": True}, {"name": "qemu", "devices": 3, "installed": True, "template": True}, ] def test_dt_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "device-types", "list", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.list", "args": (False,), "ret": [ {"name": "bbb", "devices": 0, "installed": True, "template": True}, {"name": "qemu", "devices": 3, "installed": True, "template": True}, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {devices: 0, installed: true, name: bbb, template: true} - {devices: 3, installed: true, name: qemu, template: true} """ ) def test_dt_show(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "device-types", "show", "qemu"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.show", "args": ("qemu",), "ret": { "name": "qemu", "description": None, "display": True, "owners_only": False, "health_disabled": False, "aliases": ["kvm"], "devices": ["qemu01", "qemu02"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """name : qemu description : None display : True owners only : False health disabled : False aliases : ['kvm'] devices : ['qemu01', 'qemu02'] """ ) def test_dt_show_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "show", "qemu", "--json"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.show", "args": ("qemu",), "ret": { "name": "qemu", "description": None, "display": True, "owners_only": False, "health_disabled": False, "aliases": ["kvm"], "devices": ["qemu01", "qemu02"], }, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "name": "qemu", "description": None, "display": True, "owners_only": False, "health_disabled": False, "aliases": ["kvm"], "devices": ["qemu01", "qemu02"], } def test_dt_show_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "show", "qemu", "--yaml"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.show", "args": ("qemu",), "ret": { "name": "qemu", "description": None, "display": True, "owners_only": False, "health_disabled": False, "aliases": ["kvm"], "devices": ["qemu01", "qemu02"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """aliases: [kvm] description: null devices: [qemu01, qemu02] display: true health_disabled: false name: qemu owners_only: false """ ) def test_dt_template_get(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "template", "get", "bbb"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.get_template", "args": ("bbb",), "ret": "template content", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "template content\n" # nosec def test_dt_template_set(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "template.jinja2").open("w") as f_hc: f_hc.write("template definition") monkeypatch.setattr( sys, "argv", [ "lavacli", "device-types", "template", "set", "bbb", str(tmpdir / "template.jinja2"), ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.set_template", "args": ("bbb", "template definition"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_update(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "update", "bbb", "--description", "hello"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.update", "args": ("bbb", "hello", None, None, None, None, None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_update_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "device-types", "update", "bbb", "--hide"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.update", "args": ("bbb", None, False, None, None, None, None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_update_2(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "device-types", "update", "bbb", "--public", "--health-denominator", "hours", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.update", "args": ("bbb", None, None, False, None, "hours", None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_dt_update_3(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "device-types", "update", "bbb", "--health-frequency", "12", "--health-active", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.device_types.update", "args": ("bbb", None, None, None, 12, None, False), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec lavacli-v0.9.8/tests/test_devices.py000066400000000000000000001145441354067014100175400ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import time import xmlrpc.client import yaml from lavacli import main def test_devices_add_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "add", "qemu01", "--type", "qemu", "--worker", "worker01", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.add", "args": ( "qemu01", "qemu", "worker01", None, None, True, None, None, None, ), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_add_1_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "add", "qemu01", "--type", "qemu", "--worker", "worker01", "--status", "IDLE", "--health", "PASS", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.add", "args": ( "qemu01", "qemu", "worker01", None, None, True, "IDLE", "PASS", None, ), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_add_2_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "add", "qemu01", "--type", "qemu", "--worker", "worker01", "--user", "self", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.add", "args": ( "qemu01", "qemu", "worker01", "self", None, True, None, None, None, ), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_add_after_2018_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "add", "qemu01", "--type", "qemu", "--worker", "worker01", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.add", "args": ("qemu01", "qemu", "worker01", None, None, True, None, None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_add_1_after_2018_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "add", "qemu01", "--type", "qemu", "--worker", "worker01", "--health", "GOOD", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.add", "args": ("qemu01", "qemu", "worker01", None, None, True, "GOOD", None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_add_2_after_2018_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "add", "qemu01", "--type", "qemu", "--worker", "worker01", "--user", "me", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.add", "args": ("qemu01", "qemu", "worker01", "me", None, True, None, None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_dict_get(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "dict", "get", "qemu01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", False, None), "ret": "yaml_dict", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "yaml_dict\n" # nosec def test_devices_dict_get_render_field(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "--render", "qemu01", "hello.0.world"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", True, None), "ret": yaml.dump({"hello": [{"world": "as usual"}, "my"]}), }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "as usual\n" # nosec def test_devices_dict_get_render_field_out_of_range(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "--render", "qemu01", "hello.2.world"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", True, None), "ret": yaml.dump({"hello": [{"world": "as usual"}, "my"]}), }, ], ) assert main() == 1 # nosec assert capsys.readouterr()[0] == "list index out of range (2 vs 2)\n" # nosec def test_devices_dict_get_render_field_missing(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "--render", "qemu01", "hello.0.worl"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", True, None), "ret": yaml.dump({"hello": [{"world": "as usual"}, "my"]}), }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == "Unknow key 'worl' for '{'world': 'as usual'}'\n" ) def test_devices_dict_get_render_field_missing_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "--render", "qemu01", "hello.0.world.0"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", True, None), "ret": yaml.dump({"hello": [{"world": "as usual"}, "my"]}), }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == "Unable to lookup inside 'as usual' for '0'\n" ) def test_devices_dict_get_render_field_missing_2(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "dict", "get", "--render", "qemu01", "hello.0.world.missing", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", True, None), "ret": yaml.dump({"hello": [{"world": "as usual"}, "my"]}), }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == "Unable to lookup inside 'as usual' for 'missing'\n" ) def test_devices_dict_get_jinja2_field(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "qemu01", "hello"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", False, None), "ret": "{% set hello = 'bla' %}", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "bla\n" # nosec def test_devices_dict_get_jinja2_field_2(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "qemu01", "hello.0.bla"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", False, None), "ret": "{% set hello = [{'bla': 'something'}] %}", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "something\n" # nosec def test_devices_dict_get_jinja2_field_missing(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "get", "qemu01", "world"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01", False, None), "ret": "{% set hello = 'bla' %}", }, ], ) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unknow field 'world'\n" # nosec def test_devices_dict_set(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "dict.jinja2").open("w") as f_conf: f_conf.write("{% set exclusive = True %}") monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "set", "qemu01", str(tmpdir / "dict.jinja2")], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.set_dictionary", "args": ("qemu01", "{% set exclusive = True %}"), "ret": True, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_dict_set_error(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "dict.jinja2").open("w") as f_conf: f_conf.write("{% set exclusive = True %}") monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "dict", "set", "qemu01", str(tmpdir / "dict.jinja2")], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.set_dictionary", "args": ("qemu01", "{% set exclusive = True %}"), "ret": False, }, ], ) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unable to set the configuration\n" # nosec def test_devices_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.list", "args": (False,), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "qemu02", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb01", "type": "bbb", "health": "Maintenance", "state": "Idle", "current_job": None, "pipeline": True, }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Devices: * qemu01 (qemu): Idle,Good * qemu02 (qemu): Running,Good * bbb01 (bbb): Idle,Maintenance """ ) def test_devices_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "list", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.list", "args": (False,), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "qemu02", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb01", "type": "bbb", "health": "Maintenance", "state": "Idle", "current_job": None, "pipeline": True, }, ], }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "qemu02", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb01", "type": "bbb", "health": "Maintenance", "state": "Idle", "current_job": None, "pipeline": True, }, ] def test_devices_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "list", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.list", "args": (False,), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "qemu02", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb01", "type": "bbb", "health": "Maintenance", "state": "Idle", "current_job": None, "pipeline": True, }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {current_job: null, health: Good, hostname: qemu01, pipeline: true, state: Idle, type: qemu} - {current_job: 1234, health: Good, hostname: qemu02, pipeline: true, state: Running, type: qemu} - {current_job: null, health: Maintenance, hostname: bbb01, pipeline: true, state: Idle, type: bbb} """ ) def test_devices_list_before_2018_1(setup, monkeypatch, capsys, tmpdir): version = "2017.12" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.list", "args": (False,), "ret": [ { "hostname": "qemu01", "type": "qemu", "status": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "qemu02", "type": "qemu", "status": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb01", "type": "bbb", "status": "Maintenance", "current_job": None, "pipeline": True, }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Devices: * qemu01 (qemu): Idle * qemu02 (qemu): Running * bbb01 (bbb): Maintenance """ ) def test_devices_maintenance(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "maintenance", "qemu01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.update", "args": ("qemu01", None, None, None, None, "MAINTENANCE", None), "ret": None, }, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": 1234, "tags": ["a", "b"], }, }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Running", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "-> waiting for job 1234\n--> waiting\n" # nosec def test_devices_maintenance_force(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "maintenance", "qemu01", "--force"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.update", "args": ("qemu01", None, None, None, None, "MAINTENANCE", None), "ret": None, }, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": 1234, "tags": ["a", "b"], }, }, {"request": "scheduler.jobs.cancel", "args": (1234,), "ret": None}, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "-> waiting for job 1234\n--> canceling\n" # nosec def test_devices_maintenance_without_current_job(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "maintenance", "qemu01", "--force"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.update", "args": ("qemu01", None, None, None, None, "MAINTENANCE", None), "ret": None, }, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": ["a", "b"], }, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_show(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "show", "qemu01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": ["a", "b"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """name : qemu01 device-type : qemu state : Idle health : Good user : None group : group01 health job : True description : None public : True pipeline : True device-dict : True worker : worker01 current job : None tags : ['a', 'b'] """ ) def test_devices_show_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "show", "qemu01", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": ["a", "b"], }, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": ["a", "b"], } def test_devices_show_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "show", "qemu01", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": ["a", "b"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """current_job: null description: null device_type: qemu group: group01 has_device_dict: true health: Good health_job: true hostname: qemu01 pipeline: true public: true state: Idle tags: [a, b] user: null worker: worker01 """ ) def test_devices_show_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "show", "qemu01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "status": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": ["a", "b"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """name : qemu01 device-type : qemu status : Idle user : None group : group01 health job : True description : None public : True pipeline : True device-dict : True worker : worker01 current job : None tags : ['a', 'b'] """ ) def test_devices_tags_add(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "tags", "add", "qemu01", "hdd"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.tags.add", "args": ("qemu01", "hdd"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_tags_delete(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "tags", "delete", "qemu01", "hdd"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.tags.delete", "args": ("qemu01", "hdd"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_tags_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "tags", "list", "qemu01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.tags.list", "args": ("qemu01",), "ret": ["hdd", "virt"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Tags:\n* hdd\n* virt\n" # nosec def test_devices_tags_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "tags", "list", "--json", "qemu01"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.tags.list", "args": ("qemu01",), "ret": ["hdd", "virt"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == '["hdd", "virt"]\n' # nosec def test_devices_tags_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "devices", "tags", "list", "--yaml", "qemu01"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.tags.list", "args": ("qemu01",), "ret": ["hdd", "virt"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "[hdd, virt]\n" # nosec def test_devices_update(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "update", "qemu01", "--worker", "worker01", "--health", "UNKNOWN", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.update", "args": ("qemu01", "worker01", None, None, None, "UNKNOWN", None), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_devices_update_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" monkeypatch.setattr( sys, "argv", [ "lavacli", "devices", "update", "qemu01", "--worker", "worker01", "--status", "IDLE", "--health", "UNKNOWN", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.devices.update", "args": ( "qemu01", "worker01", None, None, None, "IDLE", "UNKNOWN", None, ), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec lavacli-v0.9.8/tests/test_events.py000066400000000000000000000633021354067014100174150ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import xmlrpc.client import zmq from lavacli import main class DummySocket(object): data = [] url = "tcp://lava.example.com:5500" def setsockopt(self, key, value): assert key == zmq.SUBSCRIBE # nosec assert value == b"" # nosec def connect(self, url): assert url == self.url # nosec def recv_multipart(self): return self.data.pop(0) class DummyContext(object): def socket(self, sock_type): assert sock_type == zmq.SUB # nosec return DummySocket() def test_events_listen(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "events", "listen"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Running", "health": "Good", "job": "1234", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ("invalid message"), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-01", "state": "Active", "health": "Maintenance"} ), ), ( "v.l.o.event", "uuid", "2018-01-31", "lavaserver", json.dumps({"message": "hello from the job", "job": "1245"}), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == """Listening to tcp://lava.example.com:5500 \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] state=Idle health=Good \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] state=Running health=Good for 1234 \033[1;30m2018-01-30\033[0m \033[1;37mv.l.o.testjob\033[0m \033[32mlava-health\033[0m - [1234] state=Running health=Unknown (a nice job) Invalid message: invalid message \033[1;30m2018-01-31\033[0m \033[1;37mv.l.o.worker\033[0m \033[32madmin\033[0m - [worker-01] state=Active health=Maintenance \033[1;30m2018-01-31\033[0m \033[1;37mv.l.o.event\033[0m \033[32mlavaserver\033[0m - [1245] message=hello from the job Unknown error: pop from empty list """ ) def test_events_listen_before_2018_1(setup, monkeypatch, capsys, tmpdir): version = "2017.12" monkeypatch.setattr(sys, "argv", ["lavacli", "events", "listen"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps({"device": "bbb-01", "device_type": "bbb", "status": "Idle"}), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "status": "Running", "job": "1234", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "status": "Running", "description": "a nice job", } ), ), ("invalid message"), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == """Listening to tcp://lava.example.com:5500 \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] Idle \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] Running for 1234 \033[1;30m2018-01-30\033[0m \033[1;37mv.l.o.testjob\033[0m \033[32mlava-health\033[0m - [1234] Running (a nice job) Invalid message: invalid message Unknown error: pop from empty list """ ) def test_events_listen_config(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "--uri", "https://admin:12345@localhost:456/RPC2", "events", "listen", ], ) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) monkeypatch.setattr(DummySocket, "url", "tcp://localhost:5501") monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5501", }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == """Listening to tcp://localhost:5501 Unknown error: pop from empty list """ ) def test_events_listen_config_2(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "events", "listen"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) monkeypatch.setattr(DummySocket, "url", "tcp://localhost:789") with (tmpdir / "lavacli.yaml").open("w") as f_conf: f_conf.write( "default:\n username: admin\n token: 12345\n uri: https://localhost:456/RPC2\n events:\n uri: tcp://localhost:789\n" ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [{"request": "system.version", "args": (), "ret": version}], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == """Listening to tcp://localhost:789 Unknown error: pop from empty list """ ) def test_events_listen_filter(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "events", "listen", "--filter", "device"] ) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Running", "health": "Good", "job": "1234", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ("invalid message"), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-01", "state": "Active", "health": "Maintenance"} ), ), ( "v.l.o.event", "uuid", "2018-01-31", "lavaserver", json.dumps({"message": "hello from the job", "job": "1245"}), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == """Listening to tcp://lava.example.com:5500 \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] state=Idle health=Good \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] state=Running health=Good for 1234 Invalid message: invalid message Unknown error: pop from empty list """ ) def test_events_listen_filter_2(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "events", "listen", "--filter", "device", "--filter", "worker"], ) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Running", "health": "Good", "job": "1234", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ("invalid message"), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-01", "state": "Active", "health": "Maintenance"} ), ), ( "v.l.o.event", "uuid", "2018-01-31", "lavaserver", json.dumps({"message": "hello from the job", "job": "1245"}), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 1 # nosec assert ( # nosec capsys.readouterr()[0] == """Listening to tcp://lava.example.com:5500 \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] state=Idle health=Good \033[1;30m2018-01-29\033[0m \033[1;37mv.l.o.device\033[0m \033[32mlava-health\033[0m - [bbb-01] state=Running health=Good for 1234 Invalid message: invalid message \033[1;30m2018-01-31\033[0m \033[1;37mv.l.o.worker\033[0m \033[32madmin\033[0m - [worker-01] state=Active health=Maintenance Unknown error: pop from empty list """ ) def test_events_wait_device(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "events", "wait", "device", "bbb-02"]) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-02", "device_type": "bbb", "state": "Running", "health": "Good", "job": "1234", } ), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Listening to tcp://lava.example.com:5500\n" ) assert DummySocket.data == [] # nosec def test_events_wait_device_state(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "events", "wait", "device", "bbb-01", "--state", "RUNNING"], ) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Running", "health": "Good", "job": "1234", } ), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Listening to tcp://lava.example.com:5500\n" ) assert DummySocket.data == [] # nosec def test_events_wait_device_health(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "events", "wait", "device", "bbb-01", "--health", "MAINTENANCE"], ) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Maintenance", } ), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Listening to tcp://lava.example.com:5500\n" ) assert DummySocket.data == [] # nosec def test_events_wait_job(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "events", "wait", "job", "1234"]) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1233", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Listening to tcp://lava.example.com:5500\n" ) assert DummySocket.data == [] # nosec def test_events_wait_worker(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "events", "wait", "worker", "worker-01"] ) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1233", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1234", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-02", "state": "Active", "health": "Maintenance"} ), ), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-01", "state": "Active", "health": "Maintenance"} ), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Listening to tcp://lava.example.com:5500\n" ) assert DummySocket.data == [] # nosec def test_events_wait_worker_invalid_message(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "events", "wait", "worker", "worker-01"] ) monkeypatch.setattr(zmq, "Context", lambda: DummyContext()) DummySocket.data = [ ( "v.l.o.device", "uuid", "2018-01-29", "lava-health", json.dumps( { "device": "bbb-01", "device_type": "bbb", "state": "Idle", "health": "Good", } ), ), ( "v.l.o.testjob", "uuid", "2018-01-30", "lava-health", json.dumps( { "job": "1233", "device": "bbb-01", "state": "Running", "health": "Unknown", "description": "a nice job", } ), ), ("strange"), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-02", "state": "Active", "health": "Maintenance"} ), ), ( "v.l.o.worker", "uuid", "2018-01-31", "admin", json.dumps( {"hostname": "worker-01", "state": "Active", "health": "Maintenance"} ), ), ] monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.get_publisher_event_socket", "args": (), "ret": "tcp://*:5500", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "Listening to tcp://lava.example.com:5500\nInvalid message: strange\n" ) assert DummySocket.data == [] # nosec lavacli-v0.9.8/tests/test_helpers.py000066400000000000000000000025041354067014100175500ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see from lavacli.utils import parse_version, VERSION_LATEST def test_parse_version(): assert parse_version("2018.5.post1-2~bpo9+1.1debian9.1") == (2018, 5) # nosec assert parse_version("2018.5.post1-1+stretch") == (2018, 5) # nosec assert parse_version("2018.4-1-1") == (2018, 4) # nosec assert parse_version("2018.4.post2-1+stretch") == (2018, 4) # nosec assert parse_version("2019.01.post2-1+stretch") == (2019, 1) # nosec def test_parse_version_errors(): assert parse_version(1) == VERSION_LATEST # nosec assert parse_version("201812") == VERSION_LATEST # nosec lavacli-v0.9.8/tests/test_identities.py000066400000000000000000000171521354067014100202540ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import sys import xmlrpc.client import yaml from lavacli import main def test_identities_add(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "identities", "add", "v.l.o", "--uri", "https://validation.linaro.org/RPC2", ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert set(data.keys()) == set(["default", "v.l.o"]) # nosec assert data["default"] == {"uri": "https://lava.example.com/RPC2"} # nosec assert data["v.l.o"] == {"uri": "https://validation.linaro.org/RPC2"} # nosec def test_identities_add_1(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "identities", "add", "v.l.o", "--uri", "https://validation.linaro.org/RPC2", "--proxy", "http://proxy:3128", "--username", "admin", "--token", "12345", ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert set(data.keys()) == set(["default", "v.l.o"]) # nosec assert data["default"] == {"uri": "https://lava.example.com/RPC2"} # nosec assert data["v.l.o"] == { # nosec "uri": "https://validation.linaro.org/RPC2", "proxy": "http://proxy:3128", "username": "admin", "token": "12345", } def test_identities_add_empty_config(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "identities", "add", "v.l.o", "--uri", "https://validation.linaro.org/RPC2", ], ) (tmpdir / "lavacli.yaml").remove() assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert set(data.keys()) == set(["v.l.o"]) # nosec assert data["v.l.o"] == {"uri": "https://validation.linaro.org/RPC2"} # nosec def test_identities_delete(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "delete", "v.l.o"]) with (tmpdir / "lavacli.yaml").open("w") as f_conf: f_conf.write( "default:\n uri: https://lava.example.com/RPC2\nv.l.o:\n uri: https://validation.linaro.org/RPC" ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert list(data.keys()) == ["default"] # nosec assert data["default"] == {"uri": "https://lava.example.com/RPC2"} # nosec def test_identities_delete_empty_config(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "delete", "v.l.o"]) (tmpdir / "lavacli.yaml").remove() assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unknown identity 'v.l.o'\n" # nosec assert not (tmpdir / "lavacli.yaml").exists() # nosec def test_identities_delete_missing_key(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "delete", "v.l.o"]) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unknown identity 'v.l.o'\n" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert list(data.keys()) == ["default"] # nosec assert data["default"] == {"uri": "https://lava.example.com/RPC2"} # nosec def test_identities_list(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "list"]) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Identities:\n* default\n" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert list(data.keys()) == ["default"] # nosec assert data["default"] == {"uri": "https://lava.example.com/RPC2"} # nosec def test_identities_list_1(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "list"]) with (tmpdir / "lavacli.yaml").open("w") as f_conf: f_conf.write( "default:\n uri: https://lava.example.com/RPC2\nv.l.o:\n uri: https://validation.linaro.org/RPC2" ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Identities:\n* default\n* v.l.o\n" # nosec with (tmpdir / "lavacli.yaml").open() as f_in: data = yaml.safe_load(f_in) assert set(data.keys()) == set(["default", "v.l.o"]) # nosec assert data["default"] == {"uri": "https://lava.example.com/RPC2"} # nosec assert data["v.l.o"] == {"uri": "https://validation.linaro.org/RPC2"} # nosec def test_identities_list_2(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "list"]) (tmpdir / "lavacli.yaml").remove() assert main() == 0 # nosec assert capsys.readouterr()[0] == "Identities:\n" # nosec assert not (tmpdir / "lavacli.yaml").exists() # nosec def test_identities_show(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "default"]) assert main() == 0 # nosec assert capsys.readouterr()[0] == "uri: https://lava.example.com/RPC2\n" # nosec def test_identities_show_missing(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "missing"]) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unknown identity 'missing'\n" # nosec def test_identities_show_no_config(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "default"]) (tmpdir / "lavacli.yaml").remove() assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unknown identity 'default'\n" # nosec def test_identities_show_invalid_config(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "default"]) with (tmpdir / "lavacli.yaml").open("w") as f_conf: f_conf.write("hello") assert main() == 1 # nosec assert capsys.readouterr()[0] == "Invalid configuration file\n" # nosec lavacli-v0.9.8/tests/test_jobs.py000066400000000000000000001743321354067014100170540ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import time import xmlrpc.client import yaml from lavacli import main def test_jobs_cancel(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "cancel", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.jobs.cancel", "args": ("1234",), "ret": None}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_jobs_config(setup, monkeypatch, capsys, tmpdir): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "config", "1234", "--dest", str(tmpdir)] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.configuration", "args": ("1234",), "ret": ["definition", "device", "dispatcher", "env", "env.dut"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec with (tmpdir / "definition.yaml").open() as f_in: assert f_in.read() == "definition" # nosec with (tmpdir / "device.yaml").open() as f_in: assert f_in.read() == "device" # nosec with (tmpdir / "dispatcher.yaml").open() as f_in: assert f_in.read() == "dispatcher" # nosec with (tmpdir / "env.yaml").open() as f_in: assert f_in.read() == "env" # nosec with (tmpdir / "env.dut.yaml").open() as f_in: assert f_in.read() == "env.dut" # nosec def test_jobs_definition(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "definition", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.definition", "args": ("1234",), "ret": "definition", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "definition\n" # nosec def test_jobs_list_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (0, 25), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "status": "Complete", "submitter": "lava", }, { "id": "15", "description": "world", "device_type": "qemu", "status": "Incomplete", "submitter": "lab", }, { "id": "14", "description": "health", "device_type": "docker", "status": "Canceled", "submitter": "lava-health", }, { "id": "12", "description": "something", "device_type": "", "status": "Running", "submitter": "admin", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Jobs (from 1 to 25): * 16: Complete [lava] (hello) - bbb * 15: Incomplete [lab] (world) - qemu * 14: Canceled [lava-health] (health) - docker * 12: Running [admin] (something) - \n""" ) def test_jobs_list_before_2018_4(setup, monkeypatch, capsys): version = "2018.2" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (0, 25), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Runished", "submitter": "lava", }, { "id": "15", "description": "world", "device_type": "qemu", "health": "Incomplete", "state": "Finished", "submitter": "lab", }, { "id": "14", "description": "health", "device_type": "docker", "health": "Canceled", "state": "Finished", "submitter": "lava-health", }, { "id": "12", "description": "something", "device_type": "", "health": "Unknown", "state": "Running", "submitter": "admin", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Jobs (from 1 to 25): * 16: Runished,Complete [lava] (hello) - bbb * 15: Finished,Incomplete [lab] (world) - qemu * 14: Finished,Canceled [lava-health] (health) - docker * 12: Running,Unknown [admin] (something) - \n""" ) def test_jobs_list_before_2018_10(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (None, None, 0, 25), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Rinished", "submitter": "lava", }, { "id": "15", "description": "world", "device_type": "qemu", "health": "Incomplete", "state": "Finished", "submitter": "lab", }, { "id": "14", "description": "health", "device_type": "docker", "health": "Canceled", "state": "Finished", "submitter": "lava-health", }, { "id": "12", "description": "something", "device_type": "", "health": "Unknown", "state": "Running", "submitter": "admin", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Jobs (from 1 to 25): * 16: Rinished,Complete [lava] (hello) - bbb * 15: Finished,Incomplete [lab] (world) - qemu * 14: Finished,Canceled [lava-health] (health) - docker * 12: Running,Unknown [admin] (something) - \n""" ) def test_jobs_list(setup, monkeypatch, capsys): version = "2018.10" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (None, None, 0, 25, 0, False), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Rinished", "submitter": "lava", }, { "id": "12", "description": "something", "device_type": "", "health": "Unknown", "state": "Running", "submitter": "admin", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Jobs (from 1 to 25): * 16: Rinished,Complete [lava] (hello) - bbb * 12: Running,Unknown [admin] (something) - \n""" ) def test_jobs_list_since_verbose(setup, monkeypatch, capsys): version = "2018.10" monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "list", "--verbose", "--since", "5"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (None, None, 0, 25, 5, True), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Rinished", "submitter": "lava", "actual_device": "bbb-01", "start_time": "12", "end_time": "13", "error_msg": None, "error_type": None, }, { "id": "12", "description": "something", "device_type": "docker", "health": "Unknown", "state": "Running", "submitter": "admin", "actual_device": "docker-01", "start_time": "45", "end_time": "46", "error_msg": "job error", "error_type": "something is wrong", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Jobs (from 1 to 25): * 16: Rinished,Complete [lava] (hello) - bbb bbb-01 <12> <13> * 12: Running,Unknown [admin] (something) - docker docker-01 <45> <46> something is wrong: job error\n""" ) def test_jobs_list_json(setup, monkeypatch, capsys): version = "2018.10" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (None, None, 0, 25, 0, False), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Rinished", "submitter": "lava", }, { "id": "15", "description": "world", "device_type": "qemu", "health": "Incomplete", "state": "Finished", "submitter": "lab", }, { "id": "14", "description": "health", "device_type": "docker", "health": "Canceled", "state": "Finished", "submitter": "lava-health", }, { "id": "12", "description": "something", "device_type": "", "health": "Unknown", "state": "Running", "submitter": "admin", }, ], }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Rinished", "submitter": "lava", }, { "id": "15", "description": "world", "device_type": "qemu", "health": "Incomplete", "state": "Finished", "submitter": "lab", }, { "id": "14", "description": "health", "device_type": "docker", "health": "Canceled", "state": "Finished", "submitter": "lava-health", }, { "id": "12", "description": "something", "device_type": "", "health": "Unknown", "state": "Running", "submitter": "admin", }, ] def test_jobs_list_yaml(setup, monkeypatch, capsys): version = "2018.10" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (None, None, 0, 25, 0, False), "ret": [ { "id": "16", "description": "hello", "device_type": "bbb", "health": "Complete", "state": "Rinished", "submitter": "lava", }, { "id": "15", "description": "world", "device_type": "qemu", "health": "Incomplete", "state": "Finished", "submitter": "lab", }, { "id": "14", "description": "health", "device_type": "docker", "health": "Canceled", "state": "Finished", "submitter": "lava-health", }, { "id": "12", "description": "something", "device_type": "", "health": "Unknown", "state": "Running", "submitter": "admin", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {description: hello, device_type: bbb, health: Complete, id: '16', state: Rinished, submitter: lava} - {description: world, device_type: qemu, health: Incomplete, id: '15', state: Finished, submitter: lab} - {description: health, device_type: docker, health: Canceled, id: '14', state: Finished, submitter: lava-health} - {description: something, device_type: '', health: Unknown, id: '12', state: Running, submitter: admin} """ ) def test_jobs_list_filtering(setup, monkeypatch, capsys): version = "2018.10" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "list", "--state", "RUNNING"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": ("RUNNING", None, 0, 25, 0, False), "ret": [], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Jobs (from 1 to 25):\n" # nosec def test_jobs_list_filtering2(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "jobs", "list", "--health", "CANCELED", "--start", "45", "--limit", "56", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.list", "args": (None, "CANCELED", 45, 56), "ret": [], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Jobs (from 46 to 101):\n" # nosec # TODO: test with 2018.6 and also --start/--end def test_jobs_logs(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "logs", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.logs", "args": ("1234", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("1234", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec lines = capsys.readouterr()[0].split("\n") assert ( # nosec lines[0] == "2018-04-23T12:07:02 lava-dispatcher, installed at version: 2018.4-1" ) assert lines[1][:20] == "2018-04-23T12:07:02 " # nosec assert yaml.safe_load(lines[1][20:]) == { # nosec "case": "validate", "definition": "lava", "result": "pass", } assert ( # nosec lines[2] == "2018-04-23T12:07:02 start: 1.1 download-retry (timeout 00:02:00) [common]" ) def test_jobs_logs_failure_comment_and_polling(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 10 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "logs", "--polling", "10", "1234"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.logs", "args": ("1234", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("1234", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Incomplete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": "A small issue was found", }, }, ], ) assert main() == 0 # nosec lines = capsys.readouterr()[0].split("\n") assert ( # nosec lines[0] == "2018-04-23T12:07:02 lava-dispatcher, installed at version: 2018.4-1" ) assert lines[1][:20] == "2018-04-23T12:07:02 " # nosec assert yaml.safe_load(lines[1][20:]) == { # nosec "case": "validate", "definition": "lava", "result": "pass", } assert ( # nosec lines[2] == "2018-04-23T12:07:02 start: 1.1 download-retry (timeout 00:02:00) [common]" ) assert lines[3].endswith( # nosec "lavacli] Failure comment: A small issue was found" ) def test_jobs_logs_filtering(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "logs", "1234", "--filters", "info,debug"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.logs", "args": ("1234", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("1234", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """2018-04-23T12:07:02 lava-dispatcher, installed at version: 2018.4-1 2018-04-23T12:07:02 start: 1.1 download-retry (timeout 00:02:00) [common] """ ) def test_jobs_logs_raw(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "logs", "1234", "--raw"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.logs", "args": ("1234", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("1234", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"} - {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"} """ ) def test_jobs_logs_raw_filter(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "logs", "1234", "--raw", "--filters", "debug,results"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.logs", "args": ("1234", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("1234", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"} """ ) def test_jobs_queue(setup, monkeypatch, capsys): version = "2019.01" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "queue"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.queue", "args": (None, 0, 25), "ret": [ { "id": 12, "description": None, "requested_device_type": "qemu", "submitter": "lava-health", }, { "id": 14, "description": "qemu health", "requested_device_type": "qemu", "submitter": "lava-health", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Jobs (from 1 to 25): * 12: lava-health () - qemu * 14: lava-health (qemu health) - qemu """ ) def test_jobs_queue_json(setup, monkeypatch, capsys): version = "2019.01" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "queue", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.queue", "args": (None, 0, 25), "ret": [ { "id": 12, "description": None, "requested_device_type": "qemu", "submitter": "lava-health", }, { "id": 14, "description": "qemu health", "requested_device_type": "qemu", "submitter": "lava-health", }, ], }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec { "id": 12, "description": None, "requested_device_type": "qemu", "submitter": "lava-health", }, { "id": 14, "description": "qemu health", "requested_device_type": "qemu", "submitter": "lava-health", }, ] def test_jobs_queue_yaml(setup, monkeypatch, capsys): version = "2019.01" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "queue", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.queue", "args": (None, 0, 25), "ret": [ { "id": 12, "description": None, "requested_device_type": "qemu", "submitter": "lava-health", }, { "id": 14, "description": "qemu health", "requested_device_type": "qemu", "submitter": "lava-health", }, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {description: null, id: 12, requested_device_type: qemu, submitter: lava-health} - {description: qemu health, id: 14, requested_device_type: qemu, submitter: lava-health} """ ) def test_jobs_queue_filtering(setup, monkeypatch, capsys): version = "2019.01" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "queue", "qemu"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.jobs.queue", "args": (["qemu"], 0, 25), "ret": []}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Jobs (from 1 to 25):\n" # nosec monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "queue", "qemu", "panda"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.queue", "args": (["qemu", "panda"], 0, 25), "ret": [], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Jobs (from 1 to 25):\n" # nosec version = "2019.01" monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "queue", "--start", "1", "--limit", "3", "qemu"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.jobs.queue", "args": (["qemu"], 1, 3), "ret": []}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Jobs (from 2 to 4):\n" # nosec def test_jobs_resubmit(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "resubmit", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.jobs.resubmit", "args": ("1234",), "ret": 1234}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "1234\n" # nosec def test_jobs_resubmit_url(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "--uri", "https://localhost:8000/RPC2", "jobs", "resubmit", "1234", "--url", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.jobs.resubmit", "args": ("1234",), "ret": 1234}, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "https://localhost:8000/scheduler/job/1234\n" ) def test_jobs_resubmit_mutlinode(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "resubmit", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.resubmit", "args": ("1234",), "ret": [1234, 1235], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "1234\n1235\n" # nosec def test_jobs_resubmit_mutlinode_url(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "--uri", "https://example.com/RPC2", "jobs", "resubmit", "1234", "--url", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.resubmit", "args": ("1234",), "ret": [1234, 1345], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "https://example.com/scheduler/job/1234\nhttps://example.com/scheduler/job/1345\n" ) def test_jobs_resubmit_follow(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "resubmit", "1234", "--follow", "--filters", "info,debug"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.jobs.resubmit", "args": ("1234",), "ret": 1234}, { "request": "scheduler.jobs.logs", "args": ("1234", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("1234", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec lines = capsys.readouterr()[0].split("\n") assert lines[0].endswith("[lavacli] Job 1234 submitted") # nosec assert ( # nosec lines[1] == "2018-04-23T12:07:02 lava-dispatcher, installed at version: 2018.4-1" ) assert ( # nosec lines[2] == "2018-04-23T12:07:02 start: 1.1 download-retry (timeout 00:02:00) [common]" ) def test_jobs_run(setup, monkeypatch, capsys, tmpdir): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition") monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "run", str(tmpdir / "job.yaml")] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition",), "ret": "4567", }, { "request": "scheduler.jobs.logs", "args": ("4567", 0), "ret": ( False, '- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2018.4-1"}', ), }, { "request": "scheduler.jobs.logs", "args": ("4567", 1), "ret": ( True, """- {"dt": "2018-04-23T12:07:02.572789", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}} - {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}""", ), }, { "request": "scheduler.jobs.show", "args": ("4567",), "ret": { "id": "4567", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec lines = capsys.readouterr()[0].split("\n") assert lines[0].endswith("[lavacli] Job 4567 submitted") # nosec assert ( # nosec lines[1] == "2018-04-23T12:07:02 lava-dispatcher, installed at version: 2018.4-1" ) assert lines[2][:20] == "2018-04-23T12:07:02 " # nosec assert yaml.safe_load(lines[2][20:]) == { # nosec "case": "validate", "definition": "lava", "result": "pass", } assert ( # nosec lines[3] == "2018-04-23T12:07:02 start: 1.1 download-retry (timeout 00:02:00) [common]" ) def test_jobs_show_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" now = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "show", "789"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.show", "args": ("789",), "ret": { "id": "789", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "status": "Complete", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """id : 789 description : desc submitter : lava-admin device-type : qemu device : qemu01 health-check: False status : Complete pipeline : True tags : [] visibility : Publicly visible submit time : 20180128T01:01:01 start time : 20180128T01:01:01 end time : 20180128T01:01:01 """ ) def test_jobs_show(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "show", "789"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.show", "args": ("789",), "ret": { "id": "789", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """id : 789 description : desc submitter : lava-admin device-type : qemu device : qemu01 health-check: False state : Finished Health : Complete pipeline : True tags : [] visibility : Publicly visible submit time : 20180128T01:01:01 start time : 20180128T01:01:01 end time : 20180128T01:01:01 """ ) def test_jobs_show_failure_comment(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "show", "789"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.show", "args": ("789",), "ret": { "id": "789", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Incomplete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": "Something went wrong", }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """id : 789 description : desc submitter : lava-admin device-type : qemu device : qemu01 health-check: False state : Finished Health : Incomplete failure : Something went wrong pipeline : True tags : [] visibility : Publicly visible submit time : 20180128T01:01:01 start time : 20180128T01:01:01 end time : 20180128T01:01:01 """ ) def test_jobs_show_json(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "show", "789", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.show", "args": ("789",), "ret": { "id": "789", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "id": "789", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": "20180128T01:01:01", "start_time": "20180128T01:01:01", "end_time": "20180128T01:01:01", "tags": [], "visibility": "Publicly visible", "failure_comment": None, } def test_jobs_show_yaml(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "show", "789", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.show", "args": ("789",), "ret": { "id": "789", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """description: desc device: qemu01 device_type: qemu end_time: 20180128T01:01:01 failure_comment: null health: Complete health_check: false id: '789' pipeline: true start_time: 20180128T01:01:01 state: Finished submit_time: 20180128T01:01:01 submitter: lava-admin tags: [] visibility: Publicly visible """ ) def test_jobs_submit(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition as yaml") monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "submit", str(tmpdir / "job.yaml")] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition as yaml",), "ret": 5689, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "5689\n" # nosec def test_jobs_submit_url(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition as yaml") monkeypatch.setattr( sys, "argv", [ "lavacli", "--uri", "https://localhost:8000/RPC2", "jobs", "submit", str(tmpdir / "job.yaml"), "--url", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition as yaml",), "ret": 5689, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "https://localhost:8000/scheduler/job/5689\n" ) def test_jobs_submit_url_identity_default(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition as yaml") monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "submit", str(tmpdir / "job.yaml"), "--url"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition as yaml",), "ret": 5689, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "https://lava.example.com/scheduler/job/5689\n" ) def test_jobs_submit_url_identity_admin(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition as yaml") with (tmpdir / "lavacli.yaml").open("w") as f_conf: f_conf.write( yaml.dump( { "default": {"uri": "https://lava.example.com/RPC2"}, "admin": {"uri": "https://localhost:8001/RPC2"}, } ) ) monkeypatch.setattr( sys, "argv", ["lavacli", "-i", "admin", "jobs", "submit", str(tmpdir / "job.yaml"), "--url"], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition as yaml",), "ret": 5689, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "https://localhost:8001/scheduler/job/5689\n" ) def test_jobs_submit_multiple(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job1.yaml").open("w") as f_out: f_out.write("first job definition as yaml") with (tmpdir / "job2.yaml").open("w") as f_out: f_out.write("second job definition as yaml") with (tmpdir / "job3.yaml").open("w") as f_out: f_out.write("third job definition as yaml") monkeypatch.setattr( sys, "argv", [ "lavacli", "jobs", "submit", str(tmpdir / "job1.yaml"), str(tmpdir / "job2.yaml"), str(tmpdir / "job3.yaml"), ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("first job definition as yaml",), "ret": 5689, }, { "request": "scheduler.jobs.submit", "args": ("second job definition as yaml",), "ret": 5690, }, { "request": "scheduler.jobs.submit", "args": ("third job definition as yaml",), "ret": [5691, 5692], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "5689\n5690\n5691\n5692\n" # nosec def test_jobs_submit_multinode(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition as yaml") monkeypatch.setattr( sys, "argv", ["lavacli", "jobs", "submit", str(tmpdir / "job.yaml")] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition as yaml",), "ret": [5689, 5698], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "5689\n5698\n" # nosec def test_jobs_submit_multinode_url(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "job.yaml").open("w") as f_out: f_out.write("job definition as yaml") monkeypatch.setattr( sys, "argv", [ "lavacli", "--uri", "https://localhost:8000/RPC2", "jobs", "submit", str(tmpdir / "job.yaml"), "--url", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.submit", "args": ("job definition as yaml",), "ret": [5689, 5698], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "https://localhost:8000/scheduler/job/5689\nhttps://localhost:8000/scheduler/job/5698\n" ) def test_jobs_wait(setup, monkeypatch, capsys): version = "2018.4" now = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "wait", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Submitted", "submitter": "lava-admin", "submit_time": now, "start_time": None, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Running", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Running", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, { "request": "scheduler.jobs.show", "args": ("1234",), "ret": { "id": "1234", "description": "desc", "device": "qemu01", "device_type": "qemu", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-admin", "submit_time": now, "start_time": now, "end_time": now, "tags": [], "visibility": "Publicly visible", "failure_comment": None, }, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "Submitted\nRunning.\n" # nosec lavacli-v0.9.8/tests/test_lavacli.py000066400000000000000000000033001354067014100175140ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import sys import xmlrpc.client from lavacli import main from lavacli.__about__ import __version__ def test_lavacli_version(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "--version"]) assert main() == 0 # nosec assert capsys.readouterr()[0] == "lavacli %s\n" % __version__ # nosec def test_lavacli_missing_arguments(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "--help"]) assert main() == 0 # nosec help_out = capsys.readouterr()[0] monkeypatch.setattr(sys, "argv", ["lavacli"]) assert main() == 1 # nosec assert capsys.readouterr()[0] == help_out # nosec def test_lavacli_wrong_identity(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "-i", "bla", "devices" "list"]) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unknown identity 'bla'\n" # nosec lavacli-v0.9.8/tests/test_results.py000066400000000000000000000310701354067014100176070ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import xmlrpc.client import yaml from lavacli import main def test_results_job(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testjob_results_yaml", "args": ("1234",), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Results: * lava.validate [pass] * lava.job [fail] """ ) def test_results_job_isatty(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testjob_results_yaml", "args": ("1234",), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "boot", "result": "skip"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Results: * lava.validate [\033[1;32mpass\033[0m] * lava.boot [skip] * lava.job [\033[1;31mfail\033[0m] """ ) def test_results_job_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testjob_results_yaml", "args": ("1234",), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec {"name": "validate", "result": "pass", "suite": "lava"}, {"name": "job", "result": "fail", "suite": "lava"}, ] def test_results_job_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testjob_results_yaml", "args": ("1234",), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {name: validate, result: pass, suite: lava} - {name: job, result: fail, suite: lava} """ ) def test_results_suite(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testsuite_results_yaml", "args": ("1234", "lava"), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Results: * lava.validate [pass] * lava.job [fail] """ ) def test_results_suite_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testsuite_results_yaml", "args": ("1234", "lava"), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec {"name": "validate", "result": "pass", "suite": "lava"}, {"name": "job", "result": "fail", "suite": "lava"}, ] def test_results_suite_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testsuite_results_yaml", "args": ("1234", "lava"), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "job", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {name: validate, result: pass, suite: lava} - {name: job, result: fail, suite: lava} """ ) def test_results_case(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "validate"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [{"suite": "lava", "name": "validate", "result": "pass"}] ), }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "pass\n" # nosec def test_results_case_isatty_pass(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "validate"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [{"suite": "lava", "name": "validate", "result": "pass"}] ), }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "\033[1;32mpass\033[0m\n" # nosec def test_results_case_isatty_fail(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "validate"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [{"suite": "lava", "name": "validate", "result": "fail"}] ), }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "\033[1;31mfail\033[0m\n" # nosec def test_results_case_isatty_skip(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "validate"]) monkeypatch.setattr(sys.stdout, "isatty", lambda: True) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [{"suite": "lava", "name": "validate", "result": "skip"}] ), }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "skip\n" # nosec def test_results_case_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "results", "1234", "lava", "validate"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [ {"suite": "lava", "name": "validate", "result": "pass"}, {"suite": "lava", "name": "validate", "result": "fail"}, ] ), }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "pass\nfail\n" # nosec def test_results_case_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "results", "1234", "lava", "validate", "--json"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [{"suite": "lava", "name": "validate", "result": "pass"}] ), }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec {"name": "validate", "result": "pass", "suite": "lava"} ] def test_results_case_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "results", "1234", "lava", "validate", "--yaml"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "results.get_testcase_results_yaml", "args": ("1234", "lava", "validate"), "ret": yaml.dump( [{"suite": "lava", "name": "validate", "result": "pass"}] ), }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "- {name: validate, result: pass, suite: lava}\n" ) lavacli-v0.9.8/tests/test_system.py000066400000000000000000000621701354067014100174370ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import sys import time import xmlrpc.client from lavacli import main def test_system_active(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "system", "active"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, { "request": "scheduler.workers.update", "args": ("worker01", None, "ACTIVE"), "ret": None, }, { "request": "scheduler.workers.update", "args": ("worker02", None, "ACTIVE"), "ret": None, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Activate workers: * worker01 * worker02 """ ) def test_system_api(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "system", "api"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "system.api_version", "args": (), "ret": 2}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "2\n" # nosec def test_system_export(setup, monkeypatch, capsys, tmpdir): last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr( sys, "argv", ["lavacli", "system", "export", str(tmpdir / "export")] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "scheduler.aliases.list", "args": (), "ret": ["alias01", "alias02"], }, { "request": "scheduler.aliases.show", "args": ("alias01",), "ret": {"name": "alias01", "device_types": ["qemu", "kvm"]}, }, { "request": "scheduler.aliases.show", "args": ("alias02",), "ret": {"name": "alias02", "device_types": []}, }, { "request": "scheduler.tags.list", "args": (), "ret": [ {"name": "hdd", "description": "drive attached"}, {"name": "tag1", "description": None}, ], }, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": last_ping, }, }, { "request": "scheduler.workers.show", "args": ("worker02",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": [], "last_ping": last_ping, }, }, { "request": "scheduler.device_types.list", "args": (), "ret": [ {"name": "bbb", "devices": 1, "installed": True, "template": True}, {"name": "qemu", "devices": 1, "installed": True, "template": True}, ], }, { "request": "scheduler.device_types.show", "args": ("bbb",), "ret": { "name": "bbb", "description": None, "display": True, "owners_only": False, "health_disabled": False, "aliases": [], "devices": ["bbb-01"], }, }, { "request": "scheduler.device_types.get_template", "args": ("bbb",), "ret": "bbb device-type template", }, { "request": "scheduler.device_types.show", "args": ("qemu",), "ret": { "name": "qemu", "description": None, "display": True, "owners_only": False, "health_disabled": False, "aliases": [], "devices": ["qemu01"], }, }, { "request": "scheduler.device_types.get_template", "args": ("qemu",), "ret": "qemu device-type template", }, { "request": "scheduler.devices.list", "args": (False,), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "bbb-01", "type": "bbb", "health": "Maintenance", "state": "Idle", "current_job": None, "pipeline": True, }, ], }, { "request": "scheduler.devices.show", "args": ("qemu01",), "ret": { "hostname": "qemu01", "device_type": "qemu", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": [], }, }, { "request": "scheduler.devices.get_dictionary", "args": ("qemu01",), "ret": "qemu01 device dict", }, { "request": "scheduler.devices.show", "args": ("bbb-01",), "ret": { "hostname": "bbb-01", "device_type": "bbb", "health": "Good", "state": "Idle", "health_job": True, "description": None, "public": True, "pipeline": True, "has_device_dict": True, "worker": "worker01", "user": None, "group": "group01", "current_job": None, "tags": [], }, }, { "request": "scheduler.devices.get_dictionary", "args": ("bbb-01",), "ret": "bbb-01 device dict", }, ], ) assert main() == 0 # nosec lines = capsys.readouterr()[0].split("\n") assert lines[0] == "Export to %s" % str(tmpdir / "export") # nosec assert ( # nosec "\n".join(lines[1:]) == """Listing aliases * alias01 * alias02 Listing tags * hdd * tag1 Listing workers * worker01 * worker02 Listing device-types * bbb * qemu Listing devices * qemu01 * bbb-01 """ ) def test_system_maintenance(setup, monkeypatch, capsys): last_ping = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "system", "maintenance"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, { "request": "scheduler.workers.update", "args": ("worker01", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.workers.update", "args": ("worker02", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.devices.list", "args": (), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "bbb-01", "type": "bbb", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb-02", "type": "bbb", "health": "Good", "state": "Running", "current_job": 1235, "pipeline": True, }, ], }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Running", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, { "request": "scheduler.jobs.show", "args": (1235,), "ret": { "id": "1235", "description": "basic testing", "device": "bbb-02", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Maintenance workers: * worker01 * worker02 Wait for devices: * qemu01 * bbb-01 --> waiting for job 1234 ---> waiting * bbb-02 --> waiting for job 1235 """ ) def test_system_maintenance_exclude(setup, monkeypatch, capsys): last_ping = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "system", "maintenance", "--exclude", "worker01"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, { "request": "scheduler.workers.update", "args": ("worker02", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-02"], "last_ping": last_ping, }, }, { "request": "scheduler.devices.list", "args": (), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "bbb-01", "type": "bbb", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb-02", "type": "bbb", "health": "Good", "state": "Running", "current_job": 1235, "pipeline": True, }, ], }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Running", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Maintenance workers: * worker01 [SKIP] * worker02 Wait for devices: * bbb-01 --> waiting for job 1234 ---> waiting """ ) def test_system_maintenance_force(setup, monkeypatch, capsys): last_ping = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "system", "maintenance", "--force"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, { "request": "scheduler.workers.update", "args": ("worker01", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.workers.update", "args": ("worker02", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.devices.list", "args": (), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "bbb-01", "type": "bbb", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb-02", "type": "bbb", "health": "Good", "state": "Running", "current_job": 1235, "pipeline": True, }, ], }, {"request": "scheduler.jobs.cancel", "args": (1234,), "ret": None}, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, {"request": "scheduler.jobs.cancel", "args": (1235,), "ret": None}, { "request": "scheduler.jobs.show", "args": (1235,), "ret": { "id": "1235", "description": "basic testing", "device": "bbb-02", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Maintenance workers: * worker01 * worker02 Wait for devices: * qemu01 * bbb-01 --> waiting for job 1234 ---> canceling * bbb-02 --> waiting for job 1235 ---> canceling """ ) def test_system_methods_list(setup, monkeypatch, capsys): monkeypatch.setattr(sys, "argv", ["lavacli", "system", "methods", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "system.listMethods", "args": (), "ret": [ "scheduler.job_details", "scheduler.job_health", "scheduler.job_list_status", ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == "scheduler.job_details\nscheduler.job_health\nscheduler.job_list_status\n" ) def test_system_methods_help(setup, monkeypatch, capsys): monkeypatch.setattr( sys, "argv", ["lavacli", "system", "methods", "help", "system.version"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "system.methodHelp", "args": ("system.version",), "ret": """Name ---- `system.version` () Description ----------- Return the lava-server version string Arguments --------- None Return value ------------ lava-server version string""", }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Name ---- `system.version` () Description ----------- Return the lava-server version string Arguments --------- None Return value ------------ lava-server version string """ ) def test_system_methods_signature(setup, monkeypatch, capsys): monkeypatch.setattr( sys, "argv", ["lavacli", "system", "methods", "signature", "system.version"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": "2018.6"}, { "request": "system.methodSignature", "args": ("system.version",), "ret": "undef", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "undef\n" # nosec def test_system_version(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "system", "version"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "system.version", "args": (), "ret": version}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "2018.4\n" # nosec def test_system_whoami(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "system", "whoami"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "system.whoami", "args": (), "ret": "lava-admin"}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "lava-admin\n" # nosec def test_system_whoami_anonymous(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "system", "whoami"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "system.whoami", "args": (), "ret": None}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "\n" # nosec lavacli-v0.9.8/tests/test_tags.py000066400000000000000000000146561354067014100170570ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import xmlrpc.client from lavacli import main def test_tags_add(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "add", "hdd"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.tags.add", "args": ("hdd", None), "ret": None}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_tags_delete(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "delete", "hdd"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, {"request": "scheduler.tags.delete", "args": ("hdd",), "ret": None}, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_tags_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.tags.list", "args": (), "ret": [ {"name": "hdd", "description": "drive attached"}, {"name": "tag1", "description": None}, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Tags: * hdd (drive attached) * tag1 """ ) def test_tags_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "list", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.tags.list", "args": (), "ret": [ {"name": "hdd", "description": "drive attached"}, {"name": "tag1", "description": None}, ], }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == [ # nosec {"name": "hdd", "description": "drive attached"}, {"name": "tag1", "description": None}, ] def test_tags_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "list", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.tags.list", "args": (), "ret": [ {"name": "hdd", "description": "drive attached"}, {"name": "tag1", "description": None}, ], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """- {description: drive attached, name: hdd} - {description: null, name: tag1} """ ) def test_tags_show(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "show", "hdd"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.tags.show", "args": ("hdd",), "ret": { "name": "hdd", "description": "drive attached", "devices": ["aemu01", "bbb-01"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """name : hdd description: drive attached devices : * aemu01 * bbb-01 """ ) def test_tags_show_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "show", "--json", "hdd"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.tags.show", "args": ("hdd",), "ret": { "name": "hdd", "description": "drive attached", "devices": ["aemu01", "bbb-01"], }, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "name": "hdd", "description": "drive attached", "devices": ["aemu01", "bbb-01"], } def test_tags_show_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "tags", "show", "--yaml", "hdd"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.tags.show", "args": ("hdd",), "ret": { "name": "hdd", "description": "drive attached", "devices": ["aemu01", "bbb-01"], }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """description: drive attached devices: [aemu01, bbb-01] name: hdd """ ) lavacli-v0.9.8/tests/test_workers.py000066400000000000000000000541531354067014100176110ustar00rootroot00000000000000# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2018 Rémi Duraffort # This file is part of lavacli. # # lavacli is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # lavacli is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with lavacli. If not, see import json import sys import time import xmlrpc.client import yaml from lavacli import main def test_workers_add(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "add", "worker01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.add", "args": ("worker01", None, False), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_workers_add_1(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "workers", "add", "worker01", "--description", "my worker", "--disabled", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.add", "args": ("worker01", "my worker", True), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_workers_config_get(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "config", "get", "worker01"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.get_config", "args": ("worker01",), "ret": "config content", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "config content\n" # nosec def test_workers_config_set(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "config.yaml").open("w") as f_conf: f_conf.write("config content") monkeypatch.setattr( sys, "argv", [ "lavacli", "workers", "config", "set", "worker01", str(tmpdir / "config.yaml"), ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.set_config", "args": ("worker01", "config content"), "ret": True, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_workers_config_set_error(setup, monkeypatch, capsys, tmpdir): version = "2018.4" with (tmpdir / "config.yaml").open("w") as f_conf: f_conf.write("config content") monkeypatch.setattr( sys, "argv", [ "lavacli", "workers", "config", "set", "worker01", str(tmpdir / "config.yaml"), ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.set_config", "args": ("worker01", "config content"), "ret": False, }, ], ) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unable to store worker configuration\n" # nosec def test_workers_env_get(setup, monkeypatch, capsys): version = "2019.6" monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "env", "get", "worker01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.get_env", "args": ("worker01",), "ret": "env content", }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "env content\n" # nosec def test_workers_env_set(setup, monkeypatch, capsys, tmpdir): version = "2019.6" with (tmpdir / "env.yaml").open("w") as f_conf: f_conf.write("env content") monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "env", "set", "worker01", str(tmpdir / "env.yaml")], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.set_env", "args": ("worker01", "env content"), "ret": True, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_workers_env_set_error(setup, monkeypatch, capsys, tmpdir): version = "2019.6" with (tmpdir / "env.yaml").open("w") as f_conf: f_conf.write("env content") monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "env", "set", "worker01", str(tmpdir / "env.yaml")], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.set_env", "args": ("worker01", "env content"), "ret": False, }, ], ) assert main() == 1 # nosec assert capsys.readouterr()[0] == "Unable to store worker environment\n" # nosec def test_workers_list(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "list"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """Workers: * worker01 * worker02 """ ) def test_workers_list_json(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "list", "--json"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == '["worker01", "worker02"]\n' # nosec def test_workers_list_yaml(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "list", "--yaml"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.list", "args": (), "ret": ["worker01", "worker02"], }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "[worker01, worker02]\n" # nosec def test_workers_maintenance(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "maintenance", "worker01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.update", "args": ("worker01", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": last_ping, }, }, { "request": "scheduler.devices.list", "args": (), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "bbb-01", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, { "hostname": "bbb-02", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1235, "pipeline": True, }, ], }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Unknown", "state": "Running", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": None, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Complete", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "-> waiting for job 1234\n--> waiting\n" # nosec def test_workers_maintenance_nowait(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") def sleep(duration): assert duration == 5 # nosec monkeypatch.setattr(time, "sleep", sleep) monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "maintenance", "worker01", "--no-wait"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.update", "args": ("worker01", None, "MAINTENANCE"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_workers_maintenance_force(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "maintenance", "worker01", "--force"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.update", "args": ("worker01", None, "MAINTENANCE"), "ret": None, }, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": last_ping, }, }, { "request": "scheduler.devices.list", "args": (), "ret": [ { "hostname": "qemu01", "type": "qemu", "health": "Good", "state": "Idle", "current_job": None, "pipeline": True, }, { "hostname": "bbb-01", "type": "qemu", "health": "Good", "state": "Running", "current_job": 1234, "pipeline": True, }, ], }, {"request": "scheduler.jobs.cancel", "args": (1234,), "ret": None}, { "request": "scheduler.jobs.show", "args": (1234,), "ret": { "id": "1234", "description": "basic testing", "device": "bbb-01", "device_type": "bbb", "health_check": False, "pipeline": True, "health": "Canceled", "state": "Finished", "submitter": "lava-bot", "submit_time": last_ping, "start_time": last_ping, "end_time": last_ping, "tags": [], "visibility": "Publicly visible", "failure_comment": "", }, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "-> waiting for job 1234\n--> canceling\n" # nosec def test_workers_show_before_2017_12(setup, monkeypatch, capsys): version = "2017.11" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "show", "worker01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "master": False, "hidden": False, "devices": 2, "last_ping": last_ping, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """hostname : worker01 description : None master : False hidden : False devices : 2 """ ) def test_workers_show_before_2018_1(setup, monkeypatch, capsys): version = "2017.12" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "show", "worker01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": 2, "last_ping": last_ping, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """hostname : worker01 description : None state : Idle health : Active devices : 2 """ ) def test_workers_show(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "show", "worker01"]) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": last_ping, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """hostname : worker01 description : None state : Idle health : Active devices : qemu01, bbb-01 last ping : 20180128T01:01:01 """ ) def test_workers_show_json(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "show", "worker01", "--json"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": last_ping, }, }, ], ) assert main() == 0 # nosec assert json.loads(capsys.readouterr()[0]) == { # nosec "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": "20180128T01:01:01", } def test_workers_show_yaml(setup, monkeypatch, capsys): version = "2018.4" last_ping = xmlrpc.client.DateTime("20180128T01:01:01") monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "show", "worker01", "--yaml"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.show", "args": ("worker01",), "ret": { "hostname": "worker01", "description": None, "state": "Idle", "health": "Active", "devices": ["qemu01", "bbb-01"], "last_ping": last_ping, }, }, ], ) assert main() == 0 # nosec assert ( # nosec capsys.readouterr()[0] == """description: null devices: [qemu01, bbb-01] health: Active hostname: worker01 last_ping: 20180128T01:01:01 state: Idle """ ) def test_workers_update_before_2017_12(setup, monkeypatch, capsys): version = "2017.11" monkeypatch.setattr( sys, "argv", ["lavacli", "workers", "update", "worker01", "--disable"] ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.update", "args": ("worker01", None, True), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec def test_workers_update(setup, monkeypatch, capsys): version = "2018.4" monkeypatch.setattr( sys, "argv", [ "lavacli", "workers", "update", "worker01", "--description", "worker", "--health", "ACTIVE", ], ) monkeypatch.setattr( xmlrpc.client.ServerProxy, "data", [ {"request": "system.version", "args": (), "ret": version}, { "request": "scheduler.workers.update", "args": ("worker01", "worker", "ACTIVE"), "ret": None, }, ], ) assert main() == 0 # nosec assert capsys.readouterr()[0] == "" # nosec