pax_global_header 0000666 0000000 0000000 00000000064 15172666047 0014530 g ustar 00root root 0000000 0000000 52 comment=e65055fd095b539f556402bbfa18521b8d46505d
lavacli-2.8/ 0000775 0000000 0000000 00000000000 15172666047 0013014 5 ustar 00root root 0000000 0000000 lavacli-2.8/.coveragerc 0000664 0000000 0000000 00000000151 15172666047 0015132 0 ustar 00root root 0000000 0000000 [run]
source =
lavacli
branch = True
[report]
precision = 2
[html]
title = lavacli coverage report
lavacli-2.8/.gitignore 0000664 0000000 0000000 00000000125 15172666047 0015002 0 ustar 00root root 0000000 0000000 .coverage
.eggs
_build/
__pycache__/
dist/
lavacli.egg-info/
coverage.xml
report.xml
lavacli-2.8/.gitlab-ci.yml 0000664 0000000 0000000 00000006001 15172666047 0015445 0 ustar 00root root 0000000 0000000 stages:
- test
- analyze
- build
- deploy
#############
# Templates #
#############
.analyze:
stage: analyze
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
image: registry.gitlab.com/lava/ci-images/amd64/analyze
.test:
stage: test
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
before_script:
- apt-get update -qq
- apt-get install --no-install-recommends -y make python3 python3-aiohttp python3-jinja2 python3-pytest python3-requests python3-ruamel.yaml python3-zmq python3-voluptuous
script:
- make test
artifacts:
reports:
junit:
- lavacli.xml
#########
# Tests #
#########
test-debian-11:
extends: .test
image: debian:bullseye
test-debian-12:
extends: .test
image: debian:bookworm
test-debian-13:
extends: .test
image: debian:trixie
test-ubuntu-22.04:
extends: .test
image: ubuntu:22.04
test-ubuntu-24.04:
extends: .test
image: ubuntu:24.04
test-ubuntu-25.04:
extends: .test
image: ubuntu:25.04
test-ubuntu-25.10:
extends: .test
image: ubuntu:25.10
###########
# Analyze #
###########
pylint:
extends: .analyze
script:
- make pylint
black:
extends: .analyze
script:
- make black
coverage:
extends: .analyze
image: debian:bullseye
before_script:
- apt-get update -qq
- apt-get install --no-install-recommends -y make python3 python3-aiohttp python3-jinja2 python3-pytest python3-pytest-cov python3-requests python3-ruamel.yaml python3-zmq python3-voluptuous
coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/'
script:
- make coverage
#artifacts:
# reports:
# coverage_report:
# coverage_format: cobertura
# path: coverage.xml
#########
# Build #
#########
sdist:
stage: build
image: debian:bookworm
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
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:bookworm
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
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 #
##########
pages:
stage: deploy
rules:
- if: $CI_COMMIT_TAG
dependencies:
- doc
script:
- mv doc/_build/html public
artifacts:
paths:
- public
publish-pages:
stage: deploy
rules:
- if: $CI_COMMIT_TAG
needs:
- pages
trigger: lava/lava-docs
variables:
PARENT_PROJECT_NAME: $CI_PROJECT_NAME
PARENT_PROJECT_REF: $CI_COMMIT_REF_NAME
lavacli-2.8/LICENSE 0000664 0000000 0000000 00000103330 15172666047 0014021 0 ustar 00root root 0000000 0000000 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-2.8/MANIFEST.in 0000664 0000000 0000000 00000000215 15172666047 0014550 0 ustar 00root root 0000000 0000000 include doc/*
include share/lavacli.yaml
include tests/*
include .coveragerc
include .gitlab-ci.yml
include LICENSE
include requirements.txt
lavacli-2.8/Makefile 0000664 0000000 0000000 00000001337 15172666047 0014460 0 ustar 00root root 0000000 0000000 .PHONY: doc server
doc:
$(MAKE) -C doc html
clean:
$(MAKE) -C doc clean
serve:
sphinx-autobuild doc doc/_build/html
check: black pylint
black:
LC_ALL=C.UTF-8 LANG=C.UTF-8 black --check --diff .
pylint:
pylint --disable=all --enable=elif,exceptions,stdlib,imports,variables,string,string_constant,logging,newstyle,classes --disable=C0411,C0412,E0401,E0611,E0202,R0201,R0401,W --enable=E0102,R1707,R1714,R1715,R1716,W0235,W0404,W0611,W0612,W0622,W0631,W0632,W0641,W0642,W1401,W1402,W1403,W1505 lavacli tests
test:
python3 -m pytest -v --junitxml=lavacli.xml tests
coverage:
python3 -m pytest -v --cov --cov-fail-under=70 --cov-report html --cov-report term-missing --cov-report=xml:coverage.xml --junitxml=report.xml tests
lavacli-2.8/debian/ 0000775 0000000 0000000 00000000000 15172666047 0014236 5 ustar 00root root 0000000 0000000 lavacli-2.8/debian/changelog 0000664 0000000 0000000 00000025652 15172666047 0016122 0 ustar 00root root 0000000 0000000 lavacli (2.8-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Fri, 24 Apr 2026 15:11:56 +0200
lavacli (2.7-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Tue, 20 Jan 2026 15:06:08 +0100
lavacli (2.6-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Tue, 20 Jan 2026 13:25:15 +0100
lavacli (2.5-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Fri, 10 Oct 2025 14:33:42 +0200
lavacli (2.4-1) unstable; urgency=medium
[ Rémi Duraffort ]
* Update documentation
-- Thu, 12 Jun 2025 09:20:13 +0200
lavacli (2.3.1-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Thu, 10 Apr 2025 12:40:53 +0200
lavacli (2.3.0-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Tue, 08 Apr 2025 10:25:06 +0200
lavacli (2.2.0-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Wed, 25 Oct 2023 15:22:08 +0200
lavacli (2.1.1-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Tue, 12 Sep 2023 20:31:55 +0200
lavacli (2.1.0-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Mon, 04 Sep 2023 11:39:13 +0200
lavacli (2.0.2-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Wed, 07 Jun 2023 11:12:28 +0200
lavacli (2.0.1-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Wed, 07 Jun 2023 09:33:13 +0200
lavacli (2.0-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Tue, 06 Jun 2023 12:04:44 +0200
lavacli (1.9-1) unstable; urgency=medium
[ Chase Qi ]
* New upstream release
-- Wed, 19 Apr 2023 09:55:55 +0200
lavacli (1.8-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Wed, 12 Apr 2023 17:49:12 +0200
lavacli (1.7-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Fri, 07 Apr 2023 14:34:51 +0200
lavacli (1.6-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Fri, 24 Feb 2023 16:31:59 +0100
lavacli (1.5.3-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
+ requests: retry on 502
-- Mon, 13 Feb 2023 10:09:51 +0100
lavacli (1.5.2-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
+ requests: use a session and add automatic retries
-- Mon, 05 Dec 2022 18:34:28 +0100
lavacli (1.5.1-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
+ lab.apply: fix crash
+ CI: only test on ubuntu LTSs
-- Tue, 27 Sep 2022 17:18:44 +0200
lavacli (1.5-1) unstable; urgency=medium
[ Rémi Duraffort ]
* Fix missing dependency on ruamel.yaml
* New upstream release
+ lab apply: fix wrong diff when using default templates/env/env-dut/...
+ lab: print file diff as unified diffs
-- Mon, 30 May 2022 15:29:01 +0200
lavacli (1.4-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
+ Allow to delete env, env-dut, worker config, template and dict
+ CI: improve test coverage among python3 versions
+ Use ruamel.yaml everywhere
+ CI: do not test on ubuntu 16.04 as yaml.ruamel is too old
+ add "lab apply|import" command
+ doc: add usage for "lavacli lab"
-- Tue, 10 May 2022 14:23:04 +0200
lavacli (1.3-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
+ Add support for get/set worker env-dut
+ events: set websocket hearbeat to 30s
-- Tue, 01 Mar 2022 11:20:30 +0100
lavacli (1.2-1) unstable; urgency=medium
[ Remi Duraffort ]
* New upstream release
+ Make yaml.CDumper optional
+ jobs logs: Ignore intermediary errors 500
+ logs: improve feedback printing
+ utils: fix variable split
+ CI: add more debian and ubuntu versions
+ Fix job show error when specify yaml/json.
[ Antonio Terceiro ]
* Build and test against all Python versions
* debian/rules: drop homemade build/install/test commands
* Add missing build dependency on python3-aiohttp
* Bump Standards-Version to 4.6.0 (no changes needed)
-- Remi Duraffort Thu, 09 Dec 2021 16:05:44 +0100
lavacli (1.1-1) unstable; urgency=medium
* New upstream release
+ CI: also test on ubuntu 19.10
+ CI: fix coverage report
+ device-types: fix crash with recent versions of LAVA
+ CI: drop ubuntu 18.04
+ CI: drop ubuntu 18.10, not 18.04
+ ci: only test on Ubuntu LTS releases
+ workers: get/set certificates
+ system: add a command to get master certificate
+ utils: use the new device-type template directory
+ Use codespell to fix spelling errors
+ Documentation: fix error about verify_ssl_cert for lavacli.yaml
+ workers: print the version after 2020.06
+ events: listen for events using websockets
+ CI: add missing python-aiohttp
+ events: do not use f-strings
+ CI: drop debian 8
+ CI: add missing package for coverage
+ workers: print the token if available
+ worker certificates are removed in 2020.09
+ events: websocket is available in LAVA 2020.09
+ Add dependency on aiohttp
-- Remi Duraffort Mon, 02 Nov 2020 10:41:21 +0100
lavacli (1.0-1) unstable; urgency=medium
[ Antonio Terceiro ]
* autopkgtest: improve testsuite script
* autopkgtest: reduce set of test dependencies
* autopkgtest: allow output on stderr (Closes: #950220)
* gbp.conf: fix settings to build from git repository
[ Rémi Duraffort ]
* New upstream release
+ workers: allow one to get and set worker job limit
-- Remi Duraffort Wed, 29 Jan 2020 14:39:48 +0100
lavacli (0.9.9-1) unstable; urgency=medium
* New upstream release
+ Fix upload to pypi in release script
+ CI: use hub.lavasoftware.org/lava/ci-images/amd64/analyze image
+ devices: fix crash with lava >= 2019.09
+ devices: rename "hostname" to "name"
+ workers: rename "hostname" to "name"
+ events: rename "hostname" to "name"
+ logs: set the debug color to 0;37 while info is in 1;37
+ jobs: consolidate logging options in one place
+ jobs resubmit: extract log watching into its own function
+ jobs submit: add option to follow the logs
+ jobs logs: improve color code for timestamps
-- Remi Duraffort Wed, 13 Nov 2019 15:23:02 +0100
lavacli (0.9.8-1) unstable; urgency=medium
[ Remi Duraffort ]
* New upstream release
+ Export author email
+ Fix yaml.dump after recent pyyaml changes (Closes: #934269)
+ CI: test on debian testing
+ Ad a git buildpackage configuration file
+ Add a simple release script
+ Improve release script
[ Antonio Terceiro ]
* Set Remi and myself as Uploaders:
* Bump Standards-Version to 4.4.0; no changes needed
* debian/rules: handle DEB_BUILD_OPTIONS=nocheck
* debian/control: run wrap-and-sort
* Drop debian/compat and replace it with a dependency on debhelper-compat 12
* debian/copyright: use https for spec URL
-- 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 versioning 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-2.8/debian/control 0000664 0000000 0000000 00000003260 15172666047 0015642 0 ustar 00root root 0000000 0000000 Source: lavacli
Maintainer: Debian LAVA team
Uploaders: Remi Duraffort ,
Antonio Terceiro
Section: admin
Priority: optional
Build-Depends: debhelper-compat (= 12),
dh-python,
python3,
python3-all,
python3-aiohttp,
python3-jinja2,
python3-pytest,
python3-pytest-runner,
python3-requests,
python3-ruamel.yaml,
python3-setuptools,
python3-sphinx,
python3-zmq
X-Python-Version: >= 3.6
Standards-Version: 4.6.0
Homepage: https://gitlab.com/lava/lavacli
Vcs-Git: https://gitlab.com/lava/lavacli
Vcs-Browser: https://gitlab.com/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-2.8/debian/copyright 0000664 0000000 0000000 00000107153 15172666047 0016200 0 ustar 00root root 0000000 0000000 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: lavacli
Source: https://gitlab.com/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-2.8/debian/gbp.conf 0000664 0000000 0000000 00000000160 15172666047 0015652 0 ustar 00root root 0000000 0000000 [buildpackage]
upstream-tree = TAG
upstream-tag = v%(version)s
pristine-tar = False
export-dir = ../build-area/
lavacli-2.8/debian/install 0000664 0000000 0000000 00000000050 15172666047 0015622 0 ustar 00root root 0000000 0000000 share/lavacli.yaml ./usr/share/lavacli/
lavacli-2.8/debian/pydist-overrides 0000664 0000000 0000000 00000000144 15172666047 0017474 0 ustar 00root root 0000000 0000000 pyzmq python3-zmq; PEP386
requests python3-requests; PEP386
ruamel.yaml python3-ruamel.yaml; PEP386
lavacli-2.8/debian/rules 0000775 0000000 0000000 00000001102 15172666047 0015310 0 ustar 00root root 0000000 0000000 #!/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_build:
dh_auto_build
make -C doc/ man SPHINXBUILD="/usr/share/sphinx/scripts/python3/sphinx-build" SPHINXOPTS="-j 4 -D today=\"$(BUILD_DATE)\""
override_dh_auto_install:
dh_auto_install
dh_installman -plavacli doc/_build/man/lavacli.1
lavacli-2.8/debian/source/ 0000775 0000000 0000000 00000000000 15172666047 0015536 5 ustar 00root root 0000000 0000000 lavacli-2.8/debian/source/format 0000664 0000000 0000000 00000000014 15172666047 0016744 0 ustar 00root root 0000000 0000000 3.0 (quilt)
lavacli-2.8/debian/tests/ 0000775 0000000 0000000 00000000000 15172666047 0015400 5 ustar 00root root 0000000 0000000 lavacli-2.8/debian/tests/control 0000664 0000000 0000000 00000000107 15172666047 0017001 0 ustar 00root root 0000000 0000000 Tests: testsuite
Depends: @, python3-pytest
Restrictions: allow-stderr
lavacli-2.8/debian/tests/testsuite 0000664 0000000 0000000 00000000422 15172666047 0017352 0 ustar 00root root 0000000 0000000 #!/bin/sh
set -eu
TESTDIR=${AUTOPKGTEST_TMP:-}
if [ -z "${TESTDIR}" ]; then
TESTDIR=`pwd`/debian/testhome
trap "rm -rf ${TESTDIR}" INT TERM EXIT
fi
mkdir -p ${TESTDIR}
cp -r tests/ ${TESTDIR}/
export HOME=${TESTDIR}
export TMPDIR=${TESTDIR}
cd ${TESTDIR}
pytest-3
lavacli-2.8/debian/watch 0000664 0000000 0000000 00000000143 15172666047 0015265 0 ustar 00root root 0000000 0000000 version=4
https://gitlab.com/lava/lavacli/tags /lava/lavacli/-/archive/v(.+)/lavacli-v.+\.tar\.gz
lavacli-2.8/doc/ 0000775 0000000 0000000 00000000000 15172666047 0013561 5 ustar 00root root 0000000 0000000 lavacli-2.8/doc/Makefile 0000664 0000000 0000000 00000001134 15172666047 0015220 0 ustar 00root root 0000000 0000000 # 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-2.8/doc/conf.py 0000664 0000000 0000000 00000012213 15172666047 0015057 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
#
# 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-2.8/doc/configuration.rst 0000664 0000000 0000000 00000004437 15172666047 0017172 0 ustar 00root root 0000000 0000000 .. _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 false to ignore SSL certificates errors (defaults to true)
* **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-2.8/doc/index.rst 0000664 0000000 0000000 00000000573 15172666047 0015427 0 ustar 00root root 0000000 0000000 .. _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-2.8/doc/install.rst 0000664 0000000 0000000 00000001307 15172666047 0015762 0 ustar 00root root 0000000 0000000 .. _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://gitlab.com/lava/lavacli.git
cd lavacli
virtualenv -p python3 venv
source venv/bin/activate
pip install -r requirements.txt
python3 -m lavacli
lavacli-2.8/doc/usage.rst 0000664 0000000 0000000 00000013623 15172666047 0015424 0 ustar 00root root 0000000 0000000 .. _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 control (on|off|reset|connect) [--dry-run]
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 [...]
The **control** command allows controlling the device power and serial
connection directly from the workstation, using the commands defined in the
device dictionary:
* **on**: turn the device on (``commands.power_on``)
* **off**: turn the device off (``commands.power_off``)
* **reset**: hard reset the device (``commands.hard_reset``)
* **connect**: connect to the device primary serial port (``commands.connections..connect``)
Use ``--dry-run`` (or ``-n``) to print the command that would be run without
executing it.
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 [...]
Groups
======
LAVA groups can be managed by:
.. code-block:: shell
lavacli add [...]
lavacli delete
lavacli list
lavacli perms add [...]
lavacli perms list
lavacli perms delete [...]
lavacli show
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
lavacli jobs find-errors
Lab
===
LAVA lab can be managed by:
.. code-block:: shell
lavacli lab apply
lavacli lab import
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
Tokens
======
Manage user remote artifact tokens:
.. code-block:: shell
lavacli add [...]
lavacli delete
lavacli list
lavacli show
Users
=====
Manage LAVA users with:
.. code-block:: shell
lavacli add [...]
lavacli delete
lavacli groups add [...]
lavacli groups list
lavacli groups delete [...]
lavacli perms add [...]
lavacli perms list
lavacli perms delete [...]
lavacli list
lavacli show
lavacli update [...]
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-2.8/lavacli/ 0000775 0000000 0000000 00000000000 15172666047 0014427 5 ustar 00root root 0000000 0000000 lavacli-2.8/lavacli/__about__.py 0000664 0000000 0000000 00000002466 15172666047 0016717 0 ustar 00root root 0000000 0000000 # 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 subprocess
__all__ = [
"__author__",
"__author_email__",
"__description__",
"__license__",
"__url__",
"__version__",
]
def git_describe():
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://gitlab.com/lava/lavacli"
__version__ = "2.8"
lavacli-2.8/lavacli/__init__.py 0000664 0000000 0000000 00000023114 15172666047 0016541 0 ustar 00root root 0000000 0000000 # 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 socket
import sys
import xml
import xmlrpc.client
from urllib.parse import urlparse
import requests
from requests.adapters import HTTPAdapter
from requests.packages import urllib3
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests.packages.urllib3.util.retry import Retry
from .__about__ import __version__
from .commands import (
aliases,
device_types,
devices,
events,
groups,
identities,
jobs,
lab,
results,
system,
tags,
tokens,
users,
utils,
workers,
)
from .utils import VERSION_LATEST, exc2str, parse_version, safe_yaml
class RequestsTransport(xmlrpc.client.Transport):
def __init__(self, scheme, proxy=None, timeout=20.0, verify_ssl_cert=True):
super().__init__()
self.scheme = scheme
# Create a session
self.session = requests.Session()
if urllib3.__version__ >= "1.26":
allowed_methods = "allowed_methods"
else:
allowed_methods = "method_whitelist" # pragma: no cover
retry_strategy = Retry(
total=3,
status_forcelist=[413, 429, 500, 502, 503, 504],
backoff_factor=1,
**{allowed_methods: ["HEAD", "OPTIONS", "GET", "POST"]},
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.session.mount("https://", adapter)
self.session.mount("http://", adapter)
# 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:
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 = f"{self.scheme}://{host}{handler}"
try:
response = None
response = self.session.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
)
except xml.parsers.expat.ExpatError as e:
raise xmlrpc.client.ProtocolError(
url, 500, f"Invalid response format, check your endpoint URL: {e}", ""
)
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, encoding="utf-8") as f_conf:
config = safe_yaml.load(f_conf.read())
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,
"groups": groups,
"identities": identities,
"jobs": jobs,
"lab": lab,
"results": results,
"system": system,
"tags": tags,
"tokens": tokens,
"users": users,
"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 number?
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 = {}
lab_validate = False
if len(remaining) > 2 and remaining[0] == "lab" and remaining[1] == "validate":
lab_validate = True
# Skip when not needed.
if remaining[0] not in ["identities", "utils"] and not lab_validate:
if uri is None:
config = load_config(options.identity)
if config.get("uri") is None:
print("Unknown identity '%s'" % options.identity, file=sys.stderr)
return 1
username = config.get("username")
token = config.get("token")
if username is not None and token is not None:
p = urlparse(config["uri"])
path = "" if p.path == "/" else p.path
uri = f"{p.scheme}://{username}:{token}@{p.netloc}{path}"
else:
p = urlparse(config["uri"])
path = "" if p.path == "/" else p.path
uri = f"{p.scheme}://{p.netloc}{path}"
else:
p = urlparse(uri)
path = "" if p.path == "/" else p.path
uri = f"{p.scheme}://{p.netloc}{path}"
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(f"Unable to connect: {exc2str(exc, options.uri)}", file=sys.stderr)
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(f"Unable to connect to '{options.uri}': {exc}", file=sys.stderr)
return 1
except KeyboardInterrupt:
pass
except identities.ConfigurationError as exc:
print(exc, file=sys.stderr)
return 1
except xmlrpc.client.Error as exc:
if "sub_sub_command" in options:
print(
f"Unable to call '{options.sub_command}.{options.sub_sub_command}': {exc2str(exc, options.uri)}",
file=sys.stderr,
)
else:
print(
f"Unable to call '{options.sub_command}': {exc2str(exc, options.uri)}",
file=sys.stderr,
)
except BaseException as exc:
print("Unknown error: %s" % str(exc), file=sys.stderr)
return 1
lavacli-2.8/lavacli/__main__.py 0000664 0000000 0000000 00000001523 15172666047 0016522 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# 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-2.8/lavacli/colors.py 0000664 0000000 0000000 00000000157 15172666047 0016305 0 ustar 00root root 0000000 0000000 cyan = "\033[36m"
green = "\033[32m"
red = "\033[91m"
white = "\033[37m"
yellow = "\033[33m"
reset = "\033[0m"
lavacli-2.8/lavacli/commands/ 0000775 0000000 0000000 00000000000 15172666047 0016230 5 ustar 00root root 0000000 0000000 lavacli-2.8/lavacli/commands/__init__.py 0000664 0000000 0000000 00000000000 15172666047 0020327 0 ustar 00root root 0000000 0000000 lavacli-2.8/lavacli/commands/aliases.py 0000664 0000000 0000000 00000007641 15172666047 0020233 0 ustar 00root root 0000000 0000000 # 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 lavacli.utils import safe_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":
safe_yaml.dump(aliases, sys.stdout)
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":
safe_yaml.dump(alias, sys.stdout)
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-2.8/lavacli/commands/device_types.py 0000664 0000000 0000000 00000036042 15172666047 0021272 0 ustar 00root root 0000000 0000000 # 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 sys
from lavacli.utils import safe_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",
)
# "devices"
if version >= (2025, 10):
dt_devices = sub.add_parser("devices", help="list devices for the device-type")
dt_devices.add_argument("name", help="Device-type")
dt_devices.add_argument(
"--health",
type=str,
default=None,
choices=["GOOD", "UNKNOWN", "LOOPING", "BAD", "MAINTENANCE"],
help="filter devices by health",
)
out_format = dt_devices.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",
)
# "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
if version >= (2022, 4):
dt_delete = dt_sub.add_parser(
"delete", help="delete the device-type health-check"
)
dt_delete.add_argument("name", help="name of the device-type")
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",
)
# "perms"
if version >= (2023, 3):
dt_perms = sub.add_parser("perms", help="permissions")
perms_sub = dt_perms.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
perms_sub.required = True
perms_add = perms_sub.add_parser("add", help="add permissions")
perms_add.add_argument("name", help="name of the device-type")
perms_add.add_argument("group", help="group")
perms_add.add_argument("permission", help="permission")
perms_delete = perms_sub.add_parser("delete", help="delete permissions")
perms_delete.add_argument("name", help="name of the device-type")
perms_delete.add_argument("group", help="group")
perms_delete.add_argument("permission", help="permission")
perms_list = perms_sub.add_parser("list", help="list permissions")
perms_list.add_argument("name", help="name of the device-type")
out_format = perms_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
if version >= (2022, 4):
dt_delete = dt_sub.add_parser(
"delete", help="delete the custom device-type template"
)
dt_delete.add_argument("name", help="name of the device-type")
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":
safe_yaml.dump(aliases, sys.stdout)
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 == "delete":
template = proxy.scheduler.device_types.set_health_check(options.name, "")
elif 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_devices(proxy, options, _):
devices = proxy.scheduler.device_types.devices(options.name, options.health)
if options.output_format == "json":
print(json.dumps(devices))
elif options.output_format == "yaml":
safe_yaml.dump(devices, sys.stdout)
else:
print("Devices:")
for d in devices:
print(f"* {d['hostname']} : {d['state']},{d['health']}")
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":
safe_yaml.dump(device_types, sys.stdout)
else:
print("Device-Types:")
for dt in device_types:
print(f"* {dt['name']} ({dt['devices']})")
return 0
def handle_perms(proxy, options, _):
if options.sub_sub_sub_command == "add":
proxy.scheduler.device_types.perms_add(
options.name, options.group, options.permission
)
elif options.sub_sub_sub_command == "delete":
proxy.scheduler.device_types.perms_delete(
options.name, options.group, options.permission
)
elif options.sub_sub_sub_command == "list":
perms = proxy.scheduler.device_types.perms_list(options.name)
if options.output_format == "json":
print(json.dumps(perms))
elif options.output_format == "yaml":
safe_yaml.dump(perms, sys.stdout)
else:
print("Permissions:")
for perm in perms:
print("* %s %s" % (perm["group"], perm["name"]))
return 0
def handle_show(proxy, options, config):
dt = proxy.scheduler.device_types.show(options.name)
if options.output_format == "json":
print(json.dumps(dt))
elif options.output_format == "yaml":
safe_yaml.dump(dt, sys.stdout)
else:
print("name : %s" % dt["name"])
print("description : %s" % dt["description"])
print("display : %s" % dt["display"])
if config["version"] <= (2019, 7):
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 == "delete":
template = proxy.scheduler.device_types.set_template(options.name, "")
elif 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, config):
handlers = {
"add": handle_add,
"aliases": handle_aliases,
"devices": handle_devices,
"health-check": handle_hc,
"list": handle_list,
"perms": handle_perms,
"show": handle_show,
"template": handle_template,
"update": handle_update,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/devices.py 0000664 0000000 0000000 00000043651 15172666047 0020235 0 ustar 00root root 0000000 0000000 # 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 json
import subprocess
import sys
import time
import jinja2
from lavacli.utils import safe_yaml
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("name", help="name of the device")
devices_add.add_argument("--type", required=True, help="device-type")
devices_add.add_argument("--worker", required=True, help="worker name")
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")
devices_add.add_argument(
"--health",
default=None,
choices=["GOOD", "UNKNOWN", "LOOPING", "BAD", "MAINTENANCE", "RETIRED"],
help="device health",
)
devices_add.add_argument(
"--private",
action="store_true",
default=False,
help="private device [default=public]",
)
# "control"
devices_control = sub.add_parser("control", help="control device power and serial")
devices_control.add_argument("name", help="name of the device")
devices_control.add_argument(
"action",
choices=("on", "off", "reset", "connect"),
help='"on" turns the device on; "off" turns the device off; '
'"reset" hard resets the device; "connect" connects to the device serial port',
)
devices_control.add_argument(
"-n",
"--dry-run",
action="store_true",
default=False,
help="print command instead of running it",
)
# "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
if version >= (2022, 4):
dict_delete = dict_sub.add_parser("delete", help="delete the device dictionary")
dict_delete.add_argument("name", help="name of the device")
dict_get = dict_sub.add_parser("get", help="get the device dictionary")
dict_get.add_argument("name", help="name 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("name", help="name 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, including 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"
devices_maintenance = sub.add_parser("maintenance", help="maintenance the device")
devices_maintenance.add_argument("name", help="device name")
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",
)
# "perms"
if version >= (2023, 3):
devices_perms = sub.add_parser("perms", help="permissions")
perms_sub = devices_perms.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
perms_sub.required = True
perms_add = perms_sub.add_parser("add", help="add permissions")
perms_add.add_argument("name", help="name of the device")
perms_add.add_argument("group", help="group")
perms_add.add_argument("permission", help="permission")
perms_delete = perms_sub.add_parser("delete", help="delete permissions")
perms_delete.add_argument("name", help="name of the device")
perms_delete.add_argument("group", help="group")
perms_delete.add_argument("permission", help="permission")
perms_list = perms_sub.add_parser("list", help="list permissions")
perms_list.add_argument("name", help="name of the device")
out_format = perms_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"
devices_show = sub.add_parser("show", help="show device details")
devices_show.add_argument("name", help="device name")
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("name", help="name 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("name", help="name 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("name", help="name 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("name", help="name of the device")
devices_update.add_argument("--worker", default=None, help="worker name")
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")
devices_update.add_argument(
"--health",
default=None,
choices=["GOOD", "UNKNOWN", "LOOPING", "BAD", "MAINTENANCE", "RETIRED"],
help="device health",
)
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"
)
if version >= (2022, 4):
devices_update.add_argument("--type", default=None, help="device-type")
if version >= (2025, 12):
devices_update.add_argument(
"--reason", default=None, help="reason of health change"
)
def help_string():
return "manage devices"
def handle_add(proxy, options, config):
proxy.scheduler.devices.add(
options.name,
options.type,
options.worker,
options.user,
options.group,
not options.private,
options.health,
options.description,
)
return 0
def handle_control(proxy, options, _):
config = proxy.scheduler.devices.get_dictionary(options.name, True, None)
data = safe_yaml.load(str(config))
action = options.action
keys = {"on": "power_on", "off": "power_off", "reset": "hard_reset"}
if action == "connect":
command = None
with contextlib.suppress(KeyError):
for _, c in data["commands"]["connections"].items():
if "primary" in c.get("tags", []):
command = c["connect"]
break
if not command:
print(
f"Device {options.name} does not define a primary connection",
file=sys.stderr,
)
return 1
else:
key = keys[action]
if key not in data.get("commands", {}):
print(f"The command '{action}' is not defined", file=sys.stderr)
return 1
command = data["commands"].get(key)
if isinstance(command, list):
command = " && ".join(command)
if options.dry_run:
print(command)
else:
subprocess.check_call(command, shell=True)
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)),
file=sys.stderr,
)
return 1
except KeyError:
print(f"Unknown key '{key}' for '{value}'", file=sys.stderr)
return 1
except TypeError:
print(f"Unable to lookup inside '{value}' for '{key}'", file=sys.stderr)
return 1
print(value)
return 0
def handle_dict(proxy, options, _):
if options.sub_sub_sub_command == "delete":
proxy.scheduler.devices.set_dictionary(options.name, "")
return 0
elif options.sub_sub_sub_command == "get":
config = proxy.scheduler.devices.get_dictionary(
options.name, options.render, options.context
)
if not options.field:
print(str(config).rstrip("\n"))
return 0
if options.render:
value = safe_yaml.load(str(config))
return _lookups(value, options.field.split("."))
else:
# Extract some variables
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("Unknown field '%s'" % field_name, file=sys.stderr)
return 1
else:
config = options.config.read()
ret = proxy.scheduler.devices.set_dictionary(options.name, config)
if not ret:
print("Unable to set the configuration", file=sys.stderr)
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":
safe_yaml.dump(devices, sys.stdout)
else:
print("Devices:")
for device in devices:
print(
"* %s (%s): %s,%s"
% (
device["hostname"],
device["type"],
device["state"],
device["health"],
)
)
return 0
def handle_maintenance(proxy, options, _):
proxy.scheduler.devices.update(
options.name, None, None, None, None, "MAINTENANCE", None
)
device = proxy.scheduler.devices.show(options.name)
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_perms(proxy, options, _):
if options.sub_sub_sub_command == "add":
proxy.scheduler.devices.perms_add(
options.name, options.group, options.permission
)
elif options.sub_sub_sub_command == "delete":
proxy.scheduler.devices.perms_delete(
options.name, options.group, options.permission
)
elif options.sub_sub_sub_command == "list":
perms = proxy.scheduler.devices.perms_list(options.name)
if options.output_format == "json":
print(json.dumps(perms))
elif options.output_format == "yaml":
safe_yaml.dump(perms, sys.stdout)
else:
print("Permissions:")
for perm in perms:
print("* %s %s" % (perm["group"], perm["name"]))
return 0
def handle_show(proxy, options, config):
device = proxy.scheduler.devices.show(options.name)
if options.output_format == "json":
print(json.dumps(device))
elif options.output_format == "yaml":
safe_yaml.dump(device, sys.stdout)
else:
print("name : %s" % device["hostname"])
print("device-type : %s" % device["device_type"])
print("state : %s" % device["state"])
print("health : %s" % device["health"])
if config["version"] < (2019, 9):
print("user : %s" % device["user"])
print("group : %s" % device["group"])
print("health job : %s" % device["health_job"])
print("description : %s" % device["description"])
if config["version"] < (2019, 9):
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.name, options.tag)
elif options.sub_sub_sub_command == "delete":
proxy.scheduler.devices.tags.delete(options.name, options.tag)
else:
tags = proxy.scheduler.devices.tags.list(options.name)
if options.output_format == "json":
print(json.dumps(tags))
elif options.output_format == "yaml":
safe_yaml.dump(tags, sys.stdout)
else:
print("Tags:")
for tag in tags:
print("* %s" % tag)
return 0
def handle_update(proxy, options, config):
if config["version"] < (2022, 4):
proxy.scheduler.devices.update(
options.name,
options.worker,
options.user,
options.group,
options.public,
options.health,
options.description,
)
elif config["version"] < (2025, 12):
proxy.scheduler.devices.update(
options.name,
options.worker,
options.user,
options.group,
options.public,
options.health,
options.description,
options.type,
)
else:
proxy.scheduler.devices.update(
options.name,
options.worker,
options.user,
options.group,
options.public,
options.health,
options.description,
options.type,
options.reason,
)
return 0
def handle(proxy, options, config):
handlers = {
"add": handle_add,
"control": handle_control,
"dict": handle_dict,
"list": handle_list,
"maintenance": handle_maintenance,
"perms": handle_perms,
"show": handle_show,
"tags": handle_tags,
"update": handle_update,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/events.py 0000664 0000000 0000000 00000023251 15172666047 0020111 0 ustar 00root root 0000000 0000000 # 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 asyncio
import json
import sys
from urllib.parse import urlparse
import aiohttp
from lavacli.__about__ import __version__
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"
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("name", type=str, help="name 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("name", type=str, help="worker name")
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 print_event(options, config, topic, dt, username, data):
# 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:
return
if topic_end == "device":
msg = f"[{data['device']}] <{data['device_type']}> state={data['state']} health={data['health']}"
if "job" in data:
msg += " for %s" % data["job"]
elif topic_end == "testjob":
msg = f"[{data['job']}] <{data.get('device', '??')}> state={data['state']} health={data['health']} ({data['description']})"
elif topic_end == "worker":
msg = f"[{data['hostname']}] state={data['state']} health={data['health']}"
elif topic_end == "event":
msg = f"[{data['job']}] message={data['message']}"
if sys.stdout.isatty():
print(
f"\033[1;30m{dt}\033[0m \033[1;37m{topic}\033[0m \033[32m{username}\033[0m - {msg}"
)
else:
print(f"{dt} {topic} {username} - {msg}")
def loop_zmq_events(proxy, options, config, func):
import zmq # pylint: disable=import-outside-toplevel
from zmq.utils.strtypes import b # pylint: disable=import-outside-toplevel
# Try to find the socket url
url = _get_zmq_url(proxy, options, config)
if url is None:
print("Unable to find the socket url", file=sys.stderr)
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(f"Listening to {url} (socks {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, file=sys.stderr)
return 1
while True:
msg = sock.recv_multipart()
try:
# Convert bytes to string using decode() instead of deprecated strtypes
(topic, _, dt, username, data) = (
m.decode("utf-8") if isinstance(m, bytes) else m for m in msg
)
except ValueError:
print("Invalid message: %s" % msg, file=sys.stderr)
continue
if func(options, config, topic, dt, username, data):
break
def loop_ws_events(proxy, options, config, func):
async def handler():
HEADERS = {"User-Agent": "lavacli v%s" % __version__}
url = urlparse(options.uri)
scheme = url.scheme
path = url.path
if path.endswith("/RPC2/"):
path = path[:-5]
elif path.endswith("/RPC2"):
path = path[:-4]
if not path.endswith("/"):
path = path + "/"
ws_url = ws_url_redacted = f"{scheme}://{url.netloc}{path}ws/"
if "@" in url.netloc:
ws_url_redacted = (
f"{scheme}://:@{url.netloc.split('@')[-1]}{path}ws/"
)
try:
while True:
try:
async with aiohttp.ClientSession(headers=HEADERS) as session:
print("Connecting to %s" % ws_url_redacted)
async with session.ws_connect(ws_url, heartbeat=30) as ws:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
try:
data = json.loads(msg.data)
if "error" in data:
raise aiohttp.ClientError(data["error"])
(topic, _, dt, username, data) = data
except ValueError:
print(
"Invalid message: %s" % msg,
file=sys.stderr,
)
continue
if func(options, config, topic, dt, username, data):
return 0
print("Connection closed")
await asyncio.sleep(1)
except aiohttp.ClientError as exc:
print("Connection issue: %s" % str(exc), file=sys.stderr)
await asyncio.sleep(1)
except Exception as exc:
print(exc, file=sys.stderr)
asyncio.run(handler())
def handle_listen(proxy, options, config):
if config["version"] < (2020, 9):
loop_zmq_events(proxy, options, config, print_event)
else:
loop_ws_events(proxy, options, config, print_event)
return 0
def handle_wait(proxy, options, config):
def wait(options, config, topic, dt, username, data):
# "job" is called "testjob" in the events
object_topic = options.object
if object_topic == "job":
object_topic = "testjob"
data = json.loads(data)
# Filter by object
obj = topic.split(".")[-1]
if obj != object_topic:
return False
if object_topic == "device":
if data.get("device") != options.name:
return False
elif object_topic == "testjob":
if data.get("job") != options.job_id:
return False
else:
if data.get("hostname") != options.name:
return False
# Filter by state
if options.state is not None:
if data.get("state") != options.state.capitalize():
return False
# Filter by health
if options.health is not None:
if data.get("health") != options.health.capitalize():
return False
return True
if config["version"] < (2020, 9):
loop_zmq_events(proxy, options, config, wait)
else:
loop_ws_events(proxy, options, config, wait)
return 0
def handle(proxy, options, config):
handlers = {"listen": handle_listen, "wait": handle_wait}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/groups.py 0000664 0000000 0000000 00000013207 15172666047 0020124 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2023-present 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 lavacli.utils import safe_yaml
def configure_parser(parser, version):
sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands")
sub.required = True
if version < (2023, 3):
return
# "add"
groups_add = sub.add_parser("add", help="add a group")
groups_add.add_argument("name", help="name")
# "delete"
groups_del = sub.add_parser("delete", help="delete a group")
groups_del.add_argument("name", help="name")
# "list"
groups_list = sub.add_parser("list", help="list groups")
out_format = groups_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",
)
# "perms"
groups_perms = sub.add_parser("perms", help="manage user permissions")
perms_sub = groups_perms.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
perms_sub.required = True
perms_add = perms_sub.add_parser("add", help="add a permission")
perms_add.add_argument("name", help="group name")
perms_add.add_argument("app", help="application")
perms_add.add_argument("model", help="model")
perms_add.add_argument("codename", help="codename")
perms_del = perms_sub.add_parser("delete", help="remove a permssion")
perms_del.add_argument("name", help="group name")
perms_del.add_argument("app", help="application")
perms_del.add_argument("model", help="model")
perms_del.add_argument("codename", help="codename")
perms_list = perms_sub.add_parser("list", help="list permissions for a user")
perms_list.add_argument("name", help="group name")
out_format = perms_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"
groups_show = sub.add_parser("show", help="show group details")
groups_show.add_argument("name", help="name")
out_format = groups_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 groups"
def handle_add(proxy, options, _):
proxy.auth.groups.add(
options.name,
)
return 0
def handle_delete(proxy, options, _):
proxy.auth.groups.delete(options.name)
return 0
def handle_list(proxy, options, _):
groups = proxy.auth.groups.list()
if options.output_format == "json":
print(json.dumps(groups))
elif options.output_format == "yaml":
safe_yaml.dump(groups, sys.stdout)
else:
print("Groups:")
for g in groups:
print("* %s" % g)
return 0
def handle_perms(proxy, options, _):
if options.sub_sub_sub_command == "add":
proxy.auth.groups.perms.add(
options.name, options.app, options.model, options.codename
)
elif options.sub_sub_sub_command == "delete":
proxy.auth.groups.perms.delete(
options.name, options.app, options.model, options.codename
)
else:
perms = proxy.auth.groups.perms.list(options.name)
if options.output_format == "json":
print(json.dumps(perms))
elif options.output_format == "yaml":
safe_yaml.dump(perms, sys.stdout)
else:
print("Permissions:")
for perm in perms:
print("* %s.%s.%s" % (perm["app"], perm["model"], perm["codename"]))
return 0
def handle_show(proxy, options, config):
group = proxy.auth.groups.show(options.name)
if options.output_format == "json":
print(json.dumps(group))
elif options.output_format == "yaml":
safe_yaml.dump(group, sys.stdout)
else:
print("name : %s (%d)" % (group["name"], group["id"]))
print("permissions: %s" % ", ".join(group["permissions"]))
print("users : %s" % ", ".join(group["users"]))
def handle(proxy, options, config):
handlers = {
"add": handle_add,
"delete": handle_delete,
"list": handle_list,
"perms": handle_perms,
"show": handle_show,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/identities.py 0000664 0000000 0000000 00000010074 15172666047 0020745 0 ustar 00root root 0000000 0000000 # 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 sys
from lavacli.utils import flow_yaml, safe_yaml
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, encoding="utf-8") as f_conf:
data = safe_yaml.load(f_conf.read())
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:
flow_yaml.dump(config, f_conf)
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, file=sys.stderr)
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:
flow_yaml.dump(config[options.id], sys.stdout)
return 0
except KeyError:
print("Unknown identity '%s'" % options.id, file=sys.stderr)
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-2.8/lavacli/commands/jobs.py 0000664 0000000 0000000 00000067343 15172666047 0017554 0 ustar 00root root 0000000 0000000 # 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 os
import pathlib
import sys
import time
import xmlrpc.client
from collections import defaultdict
from urllib.parse import urlparse
from lavacli.utils import (
exc2str,
fetch_jobs,
fetch_jobs_concurrent,
log_yaml,
print_error_summary,
safe_yaml,
)
def configure_log_options(parser):
parser.add_argument(
"--filters",
default=None,
type=str,
help="comma separated list of levels to show",
)
parser.add_argument(
"--polling",
default=5,
type=int,
help="polling interval in seconds [default=5s]",
)
parser.add_argument(
"--raw", default=False, action="store_true", help="print raw logs"
)
parser.add_argument("--start", default=0, type=int, help="start at the given line")
parser.add_argument("--end", default=None, type=int, help="end at the given line")
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 >= (2023, 10):
# "autocancel"
jobs_autocancel = sub.add_parser(
"autocancel",
help="cancel jobs that take longer than job timeout and the specific duration",
)
jobs_autocancel.add_argument(
"--duration", type=int, required=True, help="duration in minutes"
)
jobs_autocancel.add_argument(
"--dry-run",
action="store_true",
default=False,
help="do not cancel the jobs",
)
# "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")
# "find-errors"
jobs_find_errors = sub.add_parser("find-errors", help="Find errors in recent jobs")
jobs_find_errors.add_argument(
"--limit", type=int, default=100, help="Number of jobs to fetch"
)
jobs_find_errors.add_argument(
"--since", type=int, default=None, help="Jobs from the last N minutes"
)
# "list"
jobs_list = sub.add_parser("list", help="list jobs")
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",
)
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",
)
configure_log_options(jobs_logs)
# "queue"
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(
"--follow",
default=True,
dest="no_follow",
action="store_false",
help="resubmit and poll for the logs",
)
configure_log_options(jobs_resubmit)
# "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 separated 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",
)
jobs_submit.add_argument(
"--follow",
default=True,
dest="no_follow",
action="store_false",
help="resubmit and poll for the logs",
)
configure_log_options(jobs_submit)
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"
)
# "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, _):
ret = 0
for job_id in options.job_id:
try:
proxy.scheduler.jobs.cancel(job_id)
except xmlrpc.client.Error as exc:
print(
f"Unable to cancel job {job_id}: {exc2str(exc, options.uri)}",
file=sys.stderr,
)
ret = 1
return ret
def handle_autocancel(proxy, options, _):
# Jobs that still running within its timeout shouldn't be canceled.
skip_list = []
# A loop is needed as the list api only returns the last 100 jobs.
while True:
jobs = proxy.scheduler.jobs.list(
"RUNNING",
None,
0,
100,
None,
False,
options.duration,
)
if not jobs:
break
job_ids = [job["id"] for job in jobs]
if set(job_ids).issubset(skip_list):
break
jobs = [job for job in jobs if job["id"] not in skip_list]
duration = datetime.timedelta(minutes=options.duration)
for job in jobs:
job_id = job["id"]
definition = proxy.scheduler.jobs.definition(job_id)
data = safe_yaml.load(definition)["timeouts"]["job"]
job_timeout = datetime.timedelta(
days=data.get("days", 0),
hours=data.get("hours", 0),
minutes=data.get("minutes", 0),
seconds=data.get("seconds", 0),
)
if duration > job_timeout:
try:
if not options.dry_run:
proxy.scheduler.jobs.cancel(job_id)
print(
"[CANCELED] %s: [%s] (%s) - %s"
% (
job_id,
job["submitter"],
job["description"],
job["device_type"],
)
)
except xmlrpc.client.Error as exc:
print(
f"Unable to cancel {job_id}: {exc2str(exc, options.uri)}",
file=sys.stderr,
)
return 1
else:
print(
"[ SKIP ] %s: [%s] (%s) - %s - timeout not reached yet"
% (
job_id,
job["submitter"],
job["description"],
job["device_type"],
)
)
skip_list.append(job_id)
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):
jobs = proxy.scheduler.jobs.list(
options.state,
options.health,
options.start,
options.limit,
options.since,
options.verbose,
)
if options.output_format == "json":
print(json.dumps(jobs))
elif options.output_format == "yaml":
safe_yaml.dump(jobs, sys.stdout)
else:
print(f"Jobs (from {1 + options.start} to {options.start + options.limit}):")
for job in jobs:
if 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"],
)
)
else:
print(
"* %s: %s,%s [%s] (%s) - %s"
% (
job["id"],
job["state"],
job["health"],
job["submitter"],
job["description"],
job["device_type"],
)
)
return 0
if os.environ.get("FORCE_COLOR") or sys.stdout.isatty():
COLORS = {
"exception": "\033[1;31m",
"error": "\033[1;31m",
"warning": "\033[1;33m",
"info": "\033[1;37m",
"debug": "\033[0;37m",
"target": "\033[32m",
"input": "\033[0;35m",
"feedback": "\033[0;33m",
"results": "\033[1;34m",
"dt": "\033[0;90m",
"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
sys.stdout.write("- ")
log_yaml.dump(
line,
sys.stdout,
)
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")
ns = ""
if level == "feedback" and "ns" in line:
ns = " <" + COLORS["feedback"] + line["ns"] + COLORS["end"] + ">"
print(
COLORS["dt"]
+ timestamp
+ COLORS["end"]
+ ns
+ " "
+ COLORS[level]
+ msg
+ COLORS["end"]
)
def _download_logs(proxy, version, job_id, start, end):
(finished, data) = proxy.scheduler.jobs.logs(job_id, start, end)
logs = safe_yaml.load(str(data))
return (finished, logs)
def handle_logs(proxy, options, config):
# Loop
lines = options.start
while True:
try:
(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
except xmlrpc.client.ProtocolError as exc:
# Ignore temporary Internal Server Error as we already got some logs
if lines > options.start and exc.errcode == 500:
pass
# 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.now(datetime.timezone.utc).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":
safe_yaml.dump(data, sys.stdout)
else:
print(f"Jobs (from {1+options.start} to {options.start + options.limit}):")
for job in data:
print(
f"* {job['id']}: {job['submitter']} ({job['description'] or ''}) - {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 = f"{parsed.scheme}://{host}/scheduler/job/"
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.now(datetime.timezone.utc).isoformat(),
"lvl": "info",
"msg": "[lavacli] Job %s submitted" % job_id,
}
],
options.raw,
options.filters,
)
follow_logs(job_id, proxy, options, config)
return 0
def follow_logs(job_id, proxy, options, config):
# 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.now(datetime.timezone.utc).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)
def handle_run(proxy, options, config):
job_id = proxy.scheduler.jobs.submit(options.definition.read())
print_logs(
[
{
"dt": datetime.datetime.now(datetime.timezone.utc).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.now(datetime.timezone.utc).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 in ("json", "yaml"):
submit_time = job.get("submit_time")
job["submit_time"] = submit_time.value if submit_time else None
start_time = job.get("start_time")
job["start_time"] = start_time.value if start_time else None
end_time = job.get("end_time")
job["end_time"] = end_time.value if end_time else None
if options.output_format == "json":
print(json.dumps(job))
elif options.output_format == "yaml":
safe_yaml.dump(job, sys.stdout)
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"])
print("state : %s" % job["state"])
print("Health : %s" % job["health"])
if job.get("failure_comment"):
print("failure : %s" % job["failure_comment"])
if job.get("error_type"):
print("error : %s: %s" % (job["error_type"], job["error_msg"]))
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, config):
prefix = ""
if options.print_url:
parsed = urlparse(options.uri)
host = parsed.netloc.split("@")[-1]
prefix = f"{parsed.scheme}://{host}/scheduler/job/"
for definition in options.definition:
try:
job_id = proxy.scheduler.jobs.submit(definition.read())
if options.no_follow:
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(
f"Unable to submit {definition.name}: {exc2str(exc, options.uri)}",
file=sys.stderr,
)
return 1
if not options.no_follow:
follow_logs(job_id, proxy, options, config)
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_find_errors(proxy, options, config):
"""Main function to fetch and process LAVA jobs."""
parsed = urlparse(options.uri)
host = parsed.netloc.split("@")[-1]
url = f"{parsed.scheme}://{host}"
job_numbers = fetch_jobs(proxy, None, "INCOMPLETE", options.limit, options.since)
if not job_numbers:
print("No jobs found.")
return
print(f"\nTotal jobs found: {len(job_numbers)}")
print("Fetching job details concurrently...")
error_summary = defaultdict(lambda: defaultdict(list))
def fetch_job_details(proxy, job_id):
"""Fetch job details for a single job ID."""
return proxy.scheduler.jobs.show(job_id)
def progress_callback(processed, total):
"""Show progress every 10 jobs or at the end."""
if processed % 10 == 0 or processed == total:
print(f"Processed {processed}/{total} jobs...")
# Fetch all job details concurrently
results = fetch_jobs_concurrent(
proxy,
job_numbers,
fetch_job_details,
max_workers=20,
progress_callback=progress_callback,
)
# Process results
for job_id, job_data in results:
if isinstance(job_data, Exception):
print(f"Error fetching job {job_id}: {job_data}")
continue
if job_data:
device_name = job_data.get("device") or job_data.get("device_type")
job_url = f"{url}/scheduler/job/{job_id}"
error_msg = job_data.get("error_msg", "").strip()
if error_msg:
error_summary[error_msg][device_name].append(job_url)
print_error_summary(error_summary, summary=True)
print_error_summary(error_summary, summary=False)
def handle(proxy, options, config):
handlers = {
"cancel": handle_cancel,
"autocancel": handle_autocancel,
"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,
"find-errors": handle_find_errors,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/lab.py 0000664 0000000 0000000 00000137463 15172666047 0017356 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2022-present 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 difflib
import sys
import xmlrpc
from dataclasses import MISSING, InitVar, asdict, dataclass, field, fields
from pathlib import Path
from typing import Any, Dict, List, Set
from voluptuous import MultipleInvalid
from lavacli import colors, schemas
from lavacli.utils import rt_yaml, safe_yaml
def print_file_diff(src, dst):
if src is None:
diffs = difflib.unified_diff([], dst.split("\n"), lineterm="")
elif dst is None:
diffs = difflib.unified_diff(src.split("\n"), [], lineterm="")
else:
diffs = difflib.unified_diff(src.split("\n"), dst.split("\n"), lineterm="")
print(" | " + "\n | ".join(list(diffs)[2:]))
class Base:
@classmethod
def new(cls, **kwargs):
fields_names = [f.name for f in fields(cls)]
i_kwargs = {}
v_kwargs = {}
for k in kwargs:
if k in fields_names:
v_kwargs[k] = kwargs[k]
else:
i_kwargs[k] = kwargs[k]
return cls(**v_kwargs)
def diff(self, data: Dict[str, Any]) -> List[str]:
return [
f.name for f in fields(self) if getattr(self, f.name) != data.get(f.name)
]
@dataclass(frozen=True, order=True)
class GroupDevicePermission:
name: str
group: str
def dump(self):
data = {k: v for k, v in asdict(self).items()}
return data if data else None
def __repr__(self):
return f"{self.name:<25}{self.group}"
@dataclass
class Device(Base):
hostname: str
device_type: str
worker: str
description: str = None
tags: Set[str] = field(default_factory=set)
permissions: Set[GroupDevicePermission] = field(default_factory=set)
health: str = None
retire: InitVar[bool] = None
def __post_init__(self, retire):
self.tags = set(self.tags)
self.permissions = set([GroupDevicePermission(**p) for p in self.permissions])
self.retire = retire
if self.retire is True:
self.health = "RETIRED"
def diff(self, data: Dict[str, Any]) -> List[str]:
data = data.copy()
data["tags"] = set(data["tags"])
if data["description"] is None:
data["description"] = ""
if self.description is None:
self.description = ""
if self.health is None:
# Do nothing if not defined.
self.health = data["health"]
if self.retire is False and data["health"] == "RETIRED":
# set health to UNKNOWN to un-retire.
self.health = "UNKNOWN"
return super().diff(data)
def dump(self, exclude):
defaults = {f.name: f.default for f in fields(self) if f.default != MISSING}
data = {}
for k, v in asdict(self).items():
if k in defaults and v == defaults[k]:
continue
data[k] = v
if "description" in data and data["description"] in ["", None]:
del data["description"]
if not data["tags"]:
del data["tags"]
else:
data["tags"] = sorted(data["tags"])
del data["hostname"]
if not data["permissions"] or "permissions" in exclude or "groups" in exclude:
del data["permissions"]
else:
data["permissions"] = [p.dump() for p in sorted(data["permissions"])]
# Add `retire: true` for retired device.
if data["health"] == "Retired":
data["retire"] = True
del data["health"]
return data if data else None
def get_dict(self, base):
with contextlib.suppress(FileNotFoundError):
return (base / "devices" / f"{self.hostname}.jinja2").read_text(
encoding="utf-8"
)
return None
def set_dict(self, base, text):
(base / "devices").mkdir(parents=True, exist_ok=True)
with contextlib.suppress(FileNotFoundError):
return (base / "devices" / f"{self.hostname}.jinja2").write_text(
text, encoding="utf-8"
)
@dataclass
class DeviceType(Base):
name: str
description: str = ""
health_disabled: bool = False
health_denominator: str = "hours"
health_frequency: int = 24
aliases: Set[str] = field(default_factory=set)
display: bool = True
permissions: Set[GroupDevicePermission] = field(default_factory=set)
def __post_init__(self):
self.aliases = set(self.aliases)
self.permissions = set([GroupDevicePermission(**p) for p in self.permissions])
def diff(self, data: Dict[str, Any]) -> List[str]:
data = data.copy()
data["aliases"] = set(data["aliases"])
if data["description"] is None:
data["description"] = ""
if self.description is None:
self.description = ""
return super().diff(data)
def dump(self, exclude):
defaults = {f.name: f.default for f in fields(self) if f.default != MISSING}
data = {}
for k, v in asdict(self).items():
if k in defaults and v == defaults[k]:
continue
data[k] = v
if not data["aliases"]:
del data["aliases"]
else:
data["aliases"] = sorted(data["aliases"])
if "description" in data and data["description"] in ["", None]:
del data["description"]
del data["name"]
if not data["permissions"] or "permissions" in exclude or "groups" in exclude:
del data["permissions"]
else:
data["permissions"] = [p.dump() for p in sorted(data["permissions"])]
return data if data else None
def get_health_check(self, base):
with contextlib.suppress(FileNotFoundError):
return (base / "health-checks" / f"{self.name}.yaml").read_text(
encoding="utf-8"
)
return None
def set_health_check(self, base, text):
(base / "health-checks").mkdir(parents=True, exist_ok=True)
(base / "health-checks" / f"{self.name}.yaml").write_text(
text, encoding="utf-8"
)
def get_template(self, base):
with contextlib.suppress(FileNotFoundError):
return (base / "device-types" / f"{self.name}.jinja2").read_text(
encoding="utf-8"
)
def set_template(self, base, text):
(base / "device-types").mkdir(parents=True, exist_ok=True)
(base / "device-types" / f"{self.name}.jinja2").write_text(
text, encoding="utf-8"
)
@dataclass(frozen=True, order=True)
class Permission:
app: str
model: str
codename: str
@classmethod
def from_str(cls, s):
app, model, codename = s.split(".")
return cls(app=app, model=model, codename=codename)
def dump(self):
return str(self)
def __repr__(self):
return f"{self.app}.{self.model}.{self.codename}"
@dataclass
class Group(Base):
name: str
permissions: Set[Permission] = field(default_factory=set)
def __post_init__(self):
self.permissions = set([Permission.from_str(p) for p in self.permissions])
def dump(self, exclude):
defaults = {f.name: f.default for f in fields(self) if f.default != MISSING}
data = {}
for k, v in asdict(self).items():
if k in defaults and v == defaults[k]:
continue
data[k] = v
if not data["permissions"] or "permissions" in exclude:
del data["permissions"]
else:
data["permissions"] = [p.dump() for p in sorted(data["permissions"])]
del data["name"]
return data if data else None
@dataclass
class User(Base):
username: str
last_name: str = ""
first_name: str = ""
email: str = ""
is_superuser: bool = False
is_staff: bool = False
is_active: bool = True
ldap: bool = False
groups: Set[str] = field(default_factory=set)
permissions: Set[Permission] = field(default_factory=set)
def __post_init__(self):
self.groups = set(self.groups)
self.permissions = set([Permission.from_str(p) for p in self.permissions])
def diff(self, data: Dict[str, Any]) -> List[str]:
data = data.copy()
data["groups"] = set(data["groups"])
diff = super().diff(data)
# ldap is user add only.
if "ldap" in diff:
diff.remove("ldap")
# Don't update first_name, last_name and email for ldap user.
if self.ldap:
diff = [d for d in diff if d not in ["first_name", "last_name", "email"]]
return diff
def dump(self, exclude):
defaults = {f.name: f.default for f in fields(self) if f.default != MISSING}
data = {}
for k, v in asdict(self).items():
if k in defaults and v == defaults[k]:
continue
data[k] = v
if not data["groups"] or "groups" in exclude:
del data["groups"]
else:
data["groups"] = sorted(data["groups"])
if not data["permissions"] or "permissions" in exclude:
del data["permissions"]
else:
data["permissions"] = [p.dump() for p in sorted(data["permissions"])]
del data["username"]
return data if data else None
@dataclass
class Worker(Base):
hostname: str
description: str = ""
job_limit: int = 0
health: str = None
retire: InitVar[bool] = False
def __post_init__(self, retire):
self.retire = retire
if self.retire is True:
self.health = "RETIRED"
def diff(self, data: Dict[str, Any]) -> List[str]:
data = data.copy()
if data["description"] is None:
data["description"] = ""
if self.description is None:
self.description = ""
if self.health is None:
# Do nothing if not defined.
self.health = data["health"]
if self.retire is False and data["health"] == "RETIRED":
# Set health to ACTIVE to un-retire.
self.health = "ACTIVE"
return super().diff(data)
def dump(self):
defaults = {f.name: f.default for f in fields(self) if f.default != MISSING}
data = {}
for k, v in asdict(self).items():
if k in defaults and v == defaults[k]:
continue
data[k] = v
if "description" in data and data["description"] in ["", None]:
del data["description"]
del data["hostname"]
# Add `retire: true` for retired worker.
if data["health"] == "Retired":
data["retire"] = True
del data["health"]
return data if data else None
def get_config(self, base):
with contextlib.suppress(FileNotFoundError):
return (base / "workers" / self.hostname / "dispatcher.yaml").read_text(
encoding="utf-8"
)
def set_config(self, base, text):
(base / "workers" / self.hostname).mkdir(parents=True, exist_ok=True)
(base / "workers" / self.hostname / "dispatcher.yaml").write_text(
text, encoding="utf-8"
)
def get_env(self, base):
with contextlib.suppress(FileNotFoundError):
return (base / "workers" / self.hostname / "env.yaml").read_text(
encoding="utf-8"
)
def set_env(self, base, text):
(base / "workers" / self.hostname).mkdir(parents=True, exist_ok=True)
(base / "workers" / self.hostname / "env.yaml").write_text(
text, encoding="utf-8"
)
def get_env_dut(self, base):
with contextlib.suppress(FileNotFoundError):
return (base / "workers" / self.hostname / "env-dut.yaml").read_text(
encoding="utf-8"
)
def set_env_dut(self, base, text):
(base / "workers" / self.hostname).mkdir(parents=True, exist_ok=True)
(base / "workers" / self.hostname / "env-dut.yaml").write_text(
text, encoding="utf-8"
)
@dataclass
class Config:
device_types: Dict[str, DeviceType]
devices: Dict[str, Device]
workers: Dict[str, Worker]
groups: Dict[str, Group] = field(default_factory=dict)
users: Dict[str, User] = field(default_factory=dict)
def __post_init__(self):
self.devices = {n: Device(hostname=n, **d) for n, d in self.devices.items()}
self.device_types = {
n: DeviceType(name=n, **(dt if dt is not None else {}))
for n, dt in self.device_types.items()
}
self.groups = {
n: Group(name=n, **(grp if grp is not None else {}))
for n, grp in self.groups.items()
}
self.users = {
n: User(username=n, **(user if user is not None else {}))
for n, user in self.users.items()
}
self.workers = {
h: Worker(hostname=h, **(w if w is not None else {}))
for h, w in self.workers.items()
}
def _groups(self, exclude):
return {k: self.groups[k].dump(exclude) for k in self.groups}
def _users(self, exclude):
return {k: self.users[k].dump(exclude) for k in self.users}
def _device_types(self, exclude):
return {k: self.device_types[k].dump(exclude) for k in self.device_types}
def _workers(self):
return {k: self.workers[k].dump() for k in self.workers}
def _devices(self, exclude):
return {k: self.devices[k].dump(exclude) for k in self.devices}
def dump(self, resources, exclude):
data = {}
if "device-types" in resources:
data["device_types"] = self._device_types(exclude)
if "devices" in resources:
data["devices"] = self._devices(exclude)
if "workers" in resources:
data["workers"] = self._workers()
if "groups" in resources and "groups" not in exclude:
data["groups"] = self._groups(exclude)
if "users" in resources and "users" not in exclude:
data["users"] = self._users(exclude)
return data
def dump_device_types(self, exclude):
return {"device_types": self._device_types(exclude)}
def dump_devices(self, exclude):
return {"devices": self._devices(exclude)}
def dump_groups(self, exclude):
return {"groups": self._groups(exclude)}
def dump_users(self, exclude):
return {"users": self._users(exclude)}
def dump_workers(self):
return {"workers": self._workers()}
class ConfigFile:
def __init__(self, filepath):
self.filepath = filepath
@property
def filepath(self):
return self._filepath
@filepath.setter
def filepath(self, value):
if not isinstance(value, Path):
raise ValueError("filepath must be a pathlib.Path object!")
self._filepath = value.resolve()
def is_yaml_file(self):
with contextlib.suppress(AttributeError):
if self.filepath.suffix == ".yaml":
return True
return False
def is_dir(self):
"""Treat non yaml file as a directory"""
if self.is_yaml_file():
return False
return True
@property
def base_dir(self):
base_dir = self.filepath
if self.is_yaml_file():
base_dir = (self.filepath / ".." / self.filepath.stem).resolve()
return base_dir
def write(self, filename, data):
print(f"{colors.yellow}> {filename}{colors.reset}")
with filename.open("w") as f:
rt_yaml.dump(data, f)
def load(self):
if self.is_yaml_file():
return safe_yaml.load(self.filepath.read_text(encoding="utf-8"))
if self.is_dir():
data = {}
files = [*sorted(self.filepath.glob("*.yaml"))]
for _file in files:
_config = safe_yaml.load(_file.read_text(encoding="utf-8"))
data.update(_config)
return data
return {}
def dump(self, lab, resources=[], exclude=[]):
if self.is_yaml_file():
self.write(self.filepath, lab.dump(resources, exclude))
if self.is_dir():
if "groups" in resources and "groups" not in exclude:
self.write((self.base_dir / "groups.yaml"), lab.dump_groups(exclude))
if "users" in resources and "users" not in exclude:
self.write((self.base_dir / "users.yaml"), lab.dump_users(exclude))
if "device-types" in resources:
self.write(
(self.base_dir / "device-types.yaml"),
lab.dump_device_types(exclude),
)
if "devices" in resources:
self.write((self.base_dir / "devices.yaml"), lab.dump_devices(exclude))
if "workers" in resources:
self.write((self.base_dir / "workers.yaml"), lab.dump_workers())
def configure_parser(parser, version):
sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands")
sub.required = True
if version < (2022, 4):
return
# "apply"
lab_apply = sub.add_parser("apply", help="apply configuration")
lab_apply.add_argument(
"--dry-run",
action="store_true",
default=False,
help="Do not update the configuration",
)
lab_apply.add_argument(
"--resources",
default=[],
action="append",
choices=["groups", "users", "devices", "device-types", "workers"],
help="resources to sync",
)
lab_apply.add_argument(
"--delete",
action="store_true",
default=False,
help="Delete resource that not found in config file",
)
lab_apply.add_argument(
"config",
type=Path,
help="Path to a single config file using '.yaml' extension or a directory containing a set of config files",
)
# "import"
lab_import = sub.add_parser("import", help="import configuration")
lab_import.add_argument(
"--resources",
default=[],
action="append",
choices=["groups", "users", "devices", "device-types", "workers"],
help="resources to import",
)
lab_import.add_argument(
"--exclude",
default=[],
action="append",
choices=["groups", "users", "permissions"],
help="resource to exclude",
)
lab_import.add_argument(
"config",
type=Path,
help="Path to a single config file using '.yaml' extension or a directory containing a set of config files",
)
# validate
lab_validate = sub.add_parser("validate", help="validate configuration")
lab_validate.add_argument("config", type=Path, help="configuration file")
def help_string():
return "manage lab configuration"
def validate(data: dict) -> bool:
try:
schemas.config_schema(data)
return True
except MultipleInvalid as exc:
print(str(exc))
print(f"{colors.red}Config invalid!{colors.reset}")
return False
def handle_apply(proxy, options, config):
if not options.resources:
options.resources = ["devices", "device-types", "groups", "users", "workers"]
config_file = ConfigFile(options.config)
data = config_file.load()
if not validate(data):
return 1
lab = Config(**data)
base = config_file.base_dir
print(f"{colors.cyan}> groups{colors.reset}")
if "groups" not in options.resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
elif config["version"] >= (2023, 3):
groups = proxy.auth.groups.list()
for group in lab.groups.values():
if group.name in groups:
print(f" {colors.green}* {group.name}{colors.reset}")
else:
print(f" {colors.yellow}* {group.name}{colors.reset}")
if not options.dry_run:
proxy.auth.groups.add(group.name)
data = proxy.auth.groups.show(group.name)
data["permissions"] = set(
[Permission.from_str(p) for p in data["permissions"]]
)
diff = group.diff(data)
if "permissions" in diff:
print(f" {colors.yellow}-> permissions{colors.reset}")
missing = group.permissions.difference(set(data["permissions"]))
for perm in missing:
print(f" {colors.green}+ {perm}{colors.reset}")
if not options.dry_run:
proxy.auth.groups.perms.add(
group.name, perm.app, perm.model, perm.codename
)
missing = set(data["permissions"]).difference(group.permissions)
for perm in missing:
print(f" {colors.red}- {perm}{colors.reset}")
if not options.dry_run:
proxy.auth.groups.perms.delete(
group.name, perm.app, perm.model, perm.codename
)
if options.delete:
for group in groups:
if group not in lab.groups:
print(f" {colors.red}* {group}{colors.reset}")
if not options.dry_run:
proxy.auth.groups.delete(group)
print(f"{colors.cyan}> users{colors.reset}")
if "users" not in options.resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
elif config["version"] >= (2023, 3):
users = [user["username"] for user in proxy.auth.users.list()]
for user in lab.users.values():
if user.username in users:
print(f" {colors.green}* {user.username}{colors.reset}")
else:
print(f" {colors.yellow}* {user.username}{colors.reset}")
if not options.dry_run:
proxy.auth.users.add(
user.username,
user.first_name or None,
user.last_name or None,
user.email or None,
user.is_active,
user.is_staff,
user.is_superuser,
user.ldap,
)
data = proxy.auth.users.show(user.username)
data["permissions"] = set(
[Permission.from_str(p) for p in data["permissions"]]
)
diff = user.diff(data)
update_diff = [n for n in diff if n not in ["groups", "permissions"]]
if update_diff:
for name in update_diff:
print(
f" {colors.yellow}-> {name}: '{data[name]}' => '{getattr(user, name)}'{colors.reset}"
)
if not options.dry_run:
proxy.auth.users.update(
user.username,
user.first_name if "first_name" in diff else None,
user.last_name if "last_name" in diff else None,
user.email if "email" in diff else None,
user.is_active if "is_active" in diff else None,
user.is_staff if "is_staff" in diff else None,
user.is_superuser if "is_superuser" in diff else None,
)
if "groups" in diff:
print(f" {colors.yellow}-> groups{colors.reset}")
missing = user.groups.difference(set(data["groups"]))
for grp in missing:
print(f" {colors.green}+ {grp}{colors.reset}")
if not options.dry_run:
proxy.auth.users.groups.add(user.username, grp)
missing = set(data["groups"]).difference(user.groups)
for grp in missing:
print(f" {colors.red}- {grp}{colors.reset}")
if not options.dry_run:
proxy.auth.users.groups.delete(user.username, grp)
if "permissions" in diff:
print(f" {colors.yellow}-> permissions{colors.reset}")
missing = user.permissions.difference(set(data["permissions"]))
for perm in missing:
print(f" {colors.green}+ {perm}{colors.reset}")
if not options.dry_run:
proxy.auth.users.perms.add(
user.username, perm.app, perm.model, perm.codename
)
missing = set(data["permissions"]).difference(user.permissions)
for perm in missing:
print(f" {colors.red}- {perm}{colors.reset}")
if not options.dry_run:
proxy.auth.users.perms.delete(
user.username, perm.app, perm.model, perm.codename
)
if options.delete:
for user in users:
if user not in lab.users:
print(f" {colors.red}* {user}{colors.reset}")
if not options.dry_run:
proxy.auth.users.delete(user)
print(f"{colors.cyan}> device-types{colors.reset}")
if "device-types" not in options.resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
device_types = [dt["name"] for dt in proxy.scheduler.device_types.list(False)]
for dt in lab.device_types.values():
if dt.name in device_types:
print(f" {colors.green}* {dt.name}{colors.reset}")
else:
print(f" {colors.yellow}* {dt.name}{colors.reset}")
if not options.dry_run:
proxy.scheduler.device_types.add(
dt.name,
dt.description or None,
dt.display or True,
# owners_only is deprecated.
None,
dt.health_frequency or 24,
dt.health_denominator or "hours",
)
data = proxy.scheduler.device_types.show(dt.name)
if config["version"] >= (2023, 3):
data["permissions"] = set(
[GroupDevicePermission(**p) for p in data.get("permissions", [])]
)
diff = dt.diff(data)
dt_diff = [n for n in diff if n not in ["aliases", "permissions"]]
if dt_diff:
for name in dt_diff:
print(
f" {colors.yellow}-> {name}: '{data[name]}' => '{getattr(dt, name)}'{colors.reset}"
)
if not options.dry_run:
proxy.scheduler.device_types.update(
dt.name,
dt.description if "description" in diff else None,
dt.display if "display" in diff else None,
None,
dt.health_frequency if "health_frequency" in diff else None,
dt.health_denominator if "health_denominator" in diff else None,
dt.health_disabled if "health_disabled" in diff else None,
)
if "aliases" in diff:
print(f" {colors.yellow}-> aliases{colors.reset}")
missing = dt.aliases.difference(set(data["aliases"]))
for alias in missing:
print(f" {colors.green}+ {alias}{colors.reset}")
if not options.dry_run:
proxy.scheduler.device_types.aliases.add(dt.name, alias)
missing = set(data["aliases"]).difference(dt.aliases)
for alias in missing:
print(f" {colors.red}- {alias}{colors.reset}")
if not options.dry_run:
proxy.scheduler.device_types.aliases.delete(dt.name, alias)
if config["version"] >= (2023, 3) and "permissions" in diff:
if "groups" not in options.resources:
print(f" {colors.yellow}-> SKIP permissions{colors.reset}")
else:
print(
f" {colors.yellow}-> {'permission':<25}group{colors.reset}"
)
missing = sorted(
dt.permissions.difference(set(data["permissions"]))
)
for perm in missing:
print(f" {colors.green}+ {perm}{colors.reset}")
if not options.dry_run:
proxy.scheduler.device_types.perms_add(
dt.name, perm.group, perm.name
)
missing = sorted(
set(data["permissions"]).difference(dt.permissions)
)
for perm in missing:
print(f" {colors.red}- {perm}{colors.reset}")
if not options.dry_run:
proxy.scheduler.device_types.perms_delete(
dt.name, perm.group, perm.name
)
try:
hc = str(proxy.scheduler.device_types.get_health_check(dt.name))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
hc = None
if dt.get_health_check(base) != hc:
print(f" {colors.yellow}-> health-check{colors.reset}")
print_file_diff(hc, dt.get_health_check(base))
if not options.dry_run:
proxy.scheduler.device_types.set_health_check(
dt.name, dt.get_health_check(base)
)
if not data["default_template"] or dt.get_template(base) is not None:
try:
template = str(proxy.scheduler.device_types.get_template(dt.name))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
template = None
if dt.get_template(base) != template:
print(f" {colors.yellow}-> template{colors.reset}")
print_file_diff(template, dt.get_template(base))
if not options.dry_run:
proxy.scheduler.device_types.set_template(
dt.name, dt.get_template(base)
)
if options.delete:
for dt in device_types:
if dt not in lab.device_types:
print(f" {colors.red}* {dt}{colors.reset}")
if not options.dry_run:
# Hide the device type in the GUI.
proxy.scheduler.device_types.update(
dt,
None,
False,
None,
None,
None,
None,
)
print(f"{colors.cyan}> workers{colors.reset}")
if "workers" not in options.resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
if config["version"] >= (2023, 3):
workers = proxy.scheduler.workers.list(True)
else:
workers = proxy.scheduler.workers.list()
for worker in lab.workers.values():
if worker.hostname in workers:
print(f" {colors.green}* {worker.hostname}{colors.reset}")
else:
print(f" {colors.yellow}* {worker.hostname}{colors.reset}")
if not options.dry_run:
proxy.scheduler.workers.add(
worker.hostname, worker.description, False
)
data = proxy.scheduler.workers.show(worker.hostname)
# Active/Maintenance/Retired -> ACTIVE/MAINTENANCE/RETRIED for comparison.
data["health"] = data["health"].upper()
diff = worker.diff(data)
for name in diff:
print(
f" {colors.yellow}-> {name}: '{data[name]}' => '{getattr(worker, name)}'{colors.reset}"
)
if diff and not options.dry_run:
proxy.scheduler.workers.update(
worker.hostname,
worker.description if "description" in diff else None,
worker.health if "health" in diff else None,
worker.job_limit if "job_limit" in diff else None,
)
if not data["default_config"] or worker.get_config(base) is not None:
try:
wconfig = str(proxy.scheduler.workers.get_config(worker.hostname))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
wconfig = None
if worker.get_config(base) != wconfig:
print(f" {colors.yellow}-> config{colors.reset}")
print_file_diff(wconfig, worker.get_config(base))
if not options.dry_run:
proxy.scheduler.workers.set_config(
worker.hostname, worker.get_config(base)
)
if not data["default_env"] or worker.get_env(base) is not None:
try:
wenv = str(proxy.scheduler.workers.get_env(worker.hostname))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
wenv = None
if worker.get_env(base) != wenv:
print(f" {colors.yellow}-> env{colors.reset}")
print_file_diff(wenv, worker.get_env(base))
if not options.dry_run:
proxy.scheduler.workers.set_env(
worker.hostname, worker.get_env(base)
)
if not data["default_env_dut"] or worker.get_env_dut(base) is not None:
try:
wenv_dut = str(proxy.scheduler.workers.get_env_dut(worker.hostname))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
wenv_dut = None
if worker.get_env_dut(base) != wenv_dut:
print(f" {colors.yellow}-> env-dut{colors.reset}")
print_file_diff(wenv_dut, worker.get_env_dut(base))
if not options.dry_run:
proxy.scheduler.workers.set_env_dut(
worker.hostname, worker.get_env_dut(base)
)
if options.delete and config["version"] >= (2023, 5):
for worker in workers:
if worker not in lab.workers:
print(f" {colors.red}* {worker}{colors.reset}")
if not options.dry_run:
proxy.scheduler.workers.delete(worker)
print(f"{colors.cyan}> devices{colors.reset}")
if "devices" not in options.resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
devices = [d["hostname"] for d in proxy.scheduler.devices.list(True)]
for device in lab.devices.values():
if device.hostname in devices:
print(f" {colors.green}* {device.hostname}{colors.reset}")
else:
print(f" {colors.yellow}* {device.hostname}{colors.reset}")
if not options.dry_run:
proxy.scheduler.devices.add(
device.hostname,
device.device_type,
device.worker,
None,
None,
None,
None,
device.description,
)
data = proxy.scheduler.devices.show(device.hostname)
# Good/Unknow/Looping/Bad/Maintenance/Retired ->
# GOOD/UNKNOWN/LOOPING/BAD/MAINTENANCE/RETIRED for comparison
data["health"] = data["health"].upper()
if config["version"] >= (2023, 3):
data["permissions"] = set(
[GroupDevicePermission(**p) for p in data.get("permissions", [])]
)
diff = device.diff(data)
device_diff = [n for n in diff if n not in ["tags", "permissions"]]
if device_diff:
for name in device_diff:
print(
f" {colors.yellow}-> {name}: '{data[name]}' => '{getattr(device, name)}'{colors.reset}"
)
if not options.dry_run:
proxy.scheduler.devices.update(
device.hostname,
device.worker if "worker" in diff else None,
None,
None,
None,
device.health if "health" in diff else None,
device.description if "description" in diff else None,
device.device_type if "device_type" in diff else None,
)
if "tags" in diff:
print(f" {colors.yellow}-> tags{colors.reset}")
missing = device.tags.difference(set(data["tags"]))
for tag in missing:
print(f" {colors.green}+ {tag}{colors.reset}")
if not options.dry_run:
proxy.scheduler.devices.tags.add(device.hostname, tag)
missing = set(data["tags"]).difference(device.tags)
for tag in missing:
print(f" {colors.red}- {tag}{colors.reset}")
if not options.dry_run:
proxy.scheduler.devices.tags.delete(device.hostname, tag)
if config["version"] >= (2023, 3) and "permissions" in diff:
if "groups" not in options.resources:
print(f" {colors.yellow}-> SKIP permissions{colors.reset}")
else:
print(
f" {colors.yellow}-> {'permission':<25}group{colors.reset}"
)
missing = sorted(
device.permissions.difference(set(data["permissions"]))
)
for perm in missing:
print(f" {colors.green}+ {perm}{colors.reset}")
if not options.dry_run:
proxy.scheduler.devices.perms_add(
device.hostname, perm.group, perm.name
)
missing = sorted(
set(data["permissions"]).difference(device.permissions)
)
for perm in missing:
print(f" {colors.red}- {perm}{colors.reset}")
if not options.dry_run:
proxy.scheduler.devices.perms_delete(
device.hostname, perm.group, perm.name
)
try:
ddict = str(proxy.scheduler.devices.get_dictionary(device.hostname))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
ddict = None
if device.get_dict(base) != ddict:
print(f" {colors.yellow}-> dictionary{colors.reset}")
print_file_diff(ddict, device.get_dict(base))
if not options.dry_run:
proxy.scheduler.devices.set_dictionary(
device.hostname, device.get_dict(base)
)
if options.delete and config["version"] >= (2023, 5):
for device in devices:
if device not in lab.devices:
print(f" {colors.red}* {device}{colors.reset}")
if not options.dry_run:
proxy.scheduler.devices.delete(device)
return 0
def handle_import(proxy, options, config):
lab = Config({}, {}, {}, {}, {})
config_file = ConfigFile(options.config)
base = config_file.base_dir
base.mkdir(parents=True, exist_ok=True)
resources = options.resources
if resources:
if "devices" in resources:
if (
"device-types" not in resources
or "workers" not in resources
or "groups" not in resources
):
sys.stderr.write(
"'--resources devices' needs '--resources device-types --resources workers --resources groups'\n"
)
return 1
if "device-types" in resources:
if "groups" not in resources:
sys.stderr.write(
"'--resources device-types' needs '--resources groups'\n"
)
return 1
if "users" in resources:
if "groups" not in resources:
sys.stderr.write("'--resources users' needs '--resources groups'\n")
return 1
else:
resources = ["devices", "device-types", "groups", "users", "workers"]
excluded_resources = options.exclude
if config["version"] >= (2023, 3):
print(f"{colors.cyan}> groups{colors.reset}")
if "groups" not in resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
if "groups" in excluded_resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
groups = [grp for grp in proxy.auth.groups.list()]
for grp in groups:
print(f" {colors.green}* {grp}{colors.reset}")
data = proxy.auth.groups.show(grp)
lab.groups[grp] = Group.new(
name=data["name"], permissions=data["permissions"]
)
print(f"{colors.cyan}> users{colors.reset}")
if "users" not in resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
if "users" in excluded_resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
users = [user["username"] for user in proxy.auth.users.list()]
for user in users:
print(f" {colors.green}* {user}{colors.reset}")
data = proxy.auth.users.show(user)
lab.users[user] = User.new(**data)
print(f"{colors.cyan}> device-types{colors.reset}")
if "device-types" not in resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
device_types = [dt["name"] for dt in proxy.scheduler.device_types.list(False)]
for dt in device_types:
print(f" {colors.green}* {dt}{colors.reset}")
data = proxy.scheduler.device_types.show(dt)
lab.device_types[dt] = DeviceType.new(**data)
try:
hc = str(proxy.scheduler.device_types.get_health_check(dt))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
hc = None
if hc is not None:
print(f" {colors.green} -> health-check{colors.reset}")
lab.device_types[dt].set_health_check(base, hc)
if data["default_template"]:
print(f" {colors.green} -> default template{colors.reset}")
else:
try:
template = str(proxy.scheduler.device_types.get_template(dt))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
template = None
if template is not None:
print(f" {colors.green} -> template{colors.reset}")
lab.device_types[dt].set_template(base, template)
print(f"{colors.cyan}> workers{colors.reset}")
if "workers" not in resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
if config["version"] >= (2023, 3):
workers = proxy.scheduler.workers.list(True)
else:
workers = proxy.scheduler.workers.list()
for worker in workers:
print(f" {colors.green}* {worker}{colors.reset}")
data = proxy.scheduler.workers.show(worker)
lab.workers[worker] = Worker.new(**data)
if data["default_config"]:
print(f" {colors.green} -> default config{colors.reset}")
else:
try:
wconfig = str(proxy.scheduler.workers.get_config(worker))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
wconfig = None
if wconfig is not None:
print(f" {colors.green} -> config{colors.reset}")
lab.workers[worker].set_config(base, wconfig)
if data["default_env"]:
print(f" {colors.green} -> default env{colors.reset}")
else:
try:
wenv = str(proxy.scheduler.workers.get_env(worker))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
wenv = None
if wenv is not None:
print(f" {colors.green} -> env{colors.reset}")
lab.workers[worker].set_env(base, wenv)
if data["default_env_dut"]:
print(f" {colors.green} -> default env-dut{colors.reset}")
else:
try:
wenv_dut = str(proxy.scheduler.workers.get_env_dut(worker))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
wenv_dut = None
if wenv_dut is not None:
print(f" {colors.green} -> env-dut{colors.reset}")
lab.workers[worker].set_env_dut(base, wenv_dut)
print(f"{colors.cyan}> devices{colors.reset}")
if "devices" not in resources:
print(f" {colors.yellow}-> SKIP{colors.reset}")
else:
devices = [d["hostname"] for d in proxy.scheduler.devices.list(True)]
for device in devices:
print(f" {colors.green}* {device}{colors.reset}")
data = proxy.scheduler.devices.show(device)
lab.devices[device] = Device.new(**data)
try:
ddict = str(proxy.scheduler.devices.get_dictionary(device))
except xmlrpc.client.Fault as exc:
if exc.faultCode != 404:
raise
ddict = None
if ddict is not None:
print(f" {colors.green} -> dictionary{colors.reset}")
lab.devices[device].set_dict(base, ddict)
config_file.dump(lab, resources, excluded_resources)
return 0
def handle_validate(proxy, options, config):
config_file = ConfigFile(options.config)
data = config_file.load()
if validate(data):
print(f"{colors.green}Config valid.{colors.reset}")
return 0
return 1
def handle(proxy, options, config):
handlers = {
"apply": handle_apply,
"import": handle_import,
"validate": handle_validate,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/results.py 0000664 0000000 0000000 00000006221 15172666047 0020304 0 ustar 00root root 0000000 0000000 # 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 lavacli.utils import safe_yaml
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 = safe_yaml.load(data)
if options.output_format == "json":
print(json.dumps(results))
elif options.output_format == "yaml":
safe_yaml.dump(results, sys.stdout)
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(f"* {res['suite']}.{res['name']} [{res['result']}]")
elif res["result"] == "pass":
print(f"* {res['suite']}.{res['name']} [\033[1;32mpass\033[0m]")
elif res["result"] == "fail":
print(f"* {res['suite']}.{res['name']} [\033[1;31mfail\033[0m]")
else:
print(f"* {res['suite']}.{res['name']} [{res['result']}]")
return 0
lavacli-2.8/lavacli/commands/system.py 0000664 0000000 0000000 00000021775 15172666047 0020142 0 ustar 00root root 0000000 0000000 # 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
from lavacli.utils import flow_yaml
def configure_parser(parser, version):
sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands")
sub.required = True
# "active"
sub.add_parser("active", help="activate the system")
# "api"
sub.add_parser("api", help="print server API version")
# "certificate"
if version >= (2020, 4):
sub.add_parser("certificate")
# "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"
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 separated 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)
workers.append(
{
"hostname": w["hostname"],
"description": w["description"],
"state": w["state"],
"health": w["health"],
}
)
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:
flow_yaml.dump(export, f_out)
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_certificate(proxy, _, __):
print(proxy.system.get_master_certificate())
def handle(proxy, options, config):
handlers = {
"active": handle_active,
"api": handle_api,
"certificate": handle_certificate,
"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-2.8/lavacli/commands/tags.py 0000664 0000000 0000000 00000007151 15172666047 0017544 0 ustar 00root root 0000000 0000000 # 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 lavacli.utils import safe_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":
safe_yaml.dump(tags, sys.stdout)
else:
print("Tags:")
for tag in tags:
if tag["description"]:
print(f"* {tag['name']} ({tag['description']})")
else:
print(f"* {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":
safe_yaml.dump(tag, sys.stdout)
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-2.8/lavacli/commands/tokens.py 0000664 0000000 0000000 00000006043 15172666047 0020110 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2025-present Linaro Limited
# 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 lavacli.utils import safe_yaml
def configure_parser(parser, version):
sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands")
sub.required = True
if version < (2025, 5):
return
# "add"
tokens_add = sub.add_parser("add", help="add a token")
tokens_add.add_argument("name", help="token name")
tokens_add.add_argument("--token", required=True, help="token string")
# "delete"
tokens_delete = sub.add_parser("delete", help="delete a token")
tokens_delete.add_argument("name", help="token name")
# "list"
tokens_list = sub.add_parser("list", help="list tokens")
out_format = tokens_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"
tokens_show = sub.add_parser("show", help="show token string")
tokens_show.add_argument("name", help="token name")
def help_string():
return "manage user remote artifact tokens"
def handle_add(proxy, options):
proxy.scheduler.remote_artifact_tokens.add(options.name, options.token)
return 0
def handle_delete(proxy, options):
proxy.scheduler.remote_artifact_tokens.delete(options.name)
return 0
def handle_list(proxy, options):
tokens = proxy.scheduler.remote_artifact_tokens.list()
if options.output_format == "json":
print(json.dumps(tokens))
elif options.output_format == "yaml":
safe_yaml.dump(tokens, sys.stdout)
else:
print("tokens:")
for token in tokens:
if token["token"]:
print(f"* {token['name']}: {token['token']}")
else:
print(f"* {token['name']}:")
return 0
def handle_show(proxy, options):
token = proxy.scheduler.remote_artifact_tokens.show(options.name)
print(token)
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-2.8/lavacli/commands/users.py 0000664 0000000 0000000 00000026172 15172666047 0017753 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2023-present 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 lavacli.utils import safe_yaml
def configure_parser(parser, version):
sub = parser.add_subparsers(dest="sub_sub_command", help="Sub commands")
sub.required = True
if version < (2023, 3):
return
# "add"
users_add = sub.add_parser("add", help="add a user")
users_add.add_argument("username", help="username")
users_add.add_argument("--email", default=None, help="email")
users_add.add_argument("--first-name", default=None, help="first name")
users_add.add_argument("--last-name", default=None, help="last name")
users_add.add_argument(
"--no-active",
action="store_false",
dest="is_active",
default=True,
help="no active user",
)
users_add.add_argument(
"--staff",
action="store_true",
dest="is_staff",
default=False,
help="staff user",
)
users_add.add_argument(
"--superuser",
action="store_true",
dest="is_superuser",
default=False,
help="superuser",
)
users_add.add_argument(
"--ldap",
action="store_true",
dest="ldap",
help="ldap user",
)
# "delete"
users_del = sub.add_parser("delete", help="delete a user")
users_del.add_argument("username", help="username")
# "groups"
users_groups = sub.add_parser("groups", help="manage user groups")
groups_sub = users_groups.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
groups_sub.required = True
groups_add = groups_sub.add_parser("add", help="add a group")
groups_add.add_argument("username", help="username")
groups_add.add_argument("group", help="name of the group")
groups_del = groups_sub.add_parser("delete", help="remove a group")
groups_del.add_argument("username", help="username")
groups_del.add_argument("group", help="name of the group")
groups_list = groups_sub.add_parser("list", help="list groups for a user")
groups_list.add_argument("username", help="username")
out_format = groups_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",
)
# "perms"
users_perms = sub.add_parser("perms", help="manage user permissions")
perms_sub = users_perms.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
perms_sub.required = True
perms_add = perms_sub.add_parser("add", help="add a permission")
perms_add.add_argument("username", help="username")
perms_add.add_argument("app", help="application")
perms_add.add_argument("model", help="model")
perms_add.add_argument("codename", help="codename")
perms_del = perms_sub.add_parser("delete", help="remove a permssion")
perms_del.add_argument("username", help="username")
perms_del.add_argument("app", help="application")
perms_del.add_argument("model", help="model")
perms_del.add_argument("codename", help="codename")
perms_list = perms_sub.add_parser("list", help="list permissions for a user")
perms_list.add_argument("username", help="username")
out_format = perms_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",
)
# "list"
users_list = sub.add_parser("list", help="list users")
out_format = users_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"
users_show = sub.add_parser("show", help="show user details")
users_show.add_argument("username", help="username")
out_format = users_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"
users_update = sub.add_parser("update", help="update a user")
users_update.add_argument("username", help="username")
users_update.add_argument("--email", default=None, help="email")
users_update.add_argument("--first-name", default=None, help="first name")
users_update.add_argument("--last-name", default=None, help="last name")
users_update.add_argument(
"--active",
action="store_true",
dest="is_active",
default=None,
help="active user",
)
users_update.add_argument(
"--no-active",
action="store_false",
dest="is_active",
default=None,
help="no active user",
)
users_update.add_argument(
"--staff",
action="store_true",
dest="is_staff",
default=None,
help="staff user",
)
users_update.add_argument(
"--no-staff",
action="store_false",
dest="is_staff",
default=None,
help="no staff user",
)
users_update.add_argument(
"--superuser",
action="store_true",
dest="is_superuser",
default=None,
help="superuser",
)
users_update.add_argument(
"--no-superuser",
action="store_false",
dest="is_superuser",
default=None,
help="no superuser",
)
def help_string():
return "manage users"
def handle_add(proxy, options, _):
proxy.auth.users.add(
options.username,
options.first_name,
options.last_name,
options.email,
options.is_active,
options.is_staff,
options.is_superuser,
options.ldap,
)
return 0
def handle_delete(proxy, options, _):
proxy.auth.users.delete(options.username)
return 0
def handle_groups(proxy, options, _):
if options.sub_sub_sub_command == "add":
proxy.auth.users.groups.add(options.username, options.group)
elif options.sub_sub_sub_command == "delete":
proxy.auth.users.groups.delete(options.username, options.group)
else:
groups = proxy.auth.users.groups.list(options.username)
if options.output_format == "json":
print(json.dumps(groups))
elif options.output_format == "yaml":
safe_yaml.dump(groups, sys.stdout)
else:
print("Groups:")
for group in groups:
print("* %s" % group)
return 0
def handle_list(proxy, options, _):
users = proxy.auth.users.list()
if options.output_format == "json":
print(json.dumps(users))
elif options.output_format == "yaml":
safe_yaml.dump(users, sys.stdout)
else:
print("Users:")
for u in users:
msg = "* %s" % u["username"]
if u["first_name"] or u["last_name"]:
msg += " (%s %s)" % (u["first_name"], u["last_name"])
if u["is_staff"]:
msg += " [staff]"
if u["is_superuser"]:
msg += " [superuser]"
if not u["is_active"]:
msg += " [INACTIVE]"
print(msg)
return 0
def handle_perms(proxy, options, _):
if options.sub_sub_sub_command == "add":
proxy.auth.users.perms.add(
options.username, options.app, options.model, options.codename
)
elif options.sub_sub_sub_command == "delete":
proxy.auth.users.perms.delete(
options.username, options.app, options.model, options.codename
)
else:
perms = proxy.auth.users.perms.list(options.username)
if options.output_format == "json":
print(json.dumps(perms))
elif options.output_format == "yaml":
safe_yaml.dump(perms, sys.stdout)
else:
print("Permissions:")
for perm in perms:
print("* %s.%s.%s" % (perm["app"], perm["model"], perm["codename"]))
return 0
def handle_show(proxy, options, config):
user = proxy.auth.users.show(options.username)
if options.output_format in ("json", "yaml"):
date_joined = user.get("date_joined")
user["date_joined"] = date_joined.value if date_joined else None
last_login = user.get("last_login")
user["last_login"] = last_login.value if last_login else None
if options.output_format == "json":
print(json.dumps(user))
elif options.output_format == "yaml":
safe_yaml.dump(user, sys.stdout)
else:
print("username : %s (%d)" % (user["username"], user["id"]))
print("first name : %s" % user["first_name"])
print("last name : %s" % user["last_name"])
print("groups : %s" % ", ".join(user["groups"]))
print("permissions: %s" % ", ".join(user["permissions"]))
print("email : %s" % user["email"])
print("active : %s" % user["is_active"])
print("staff : %s" % user["is_staff"])
print("superuser : %s" % user["is_superuser"])
print("date joined: %s" % user["date_joined"])
print("last login : %s" % user["last_login"])
def handle_update(proxy, options, _):
proxy.auth.users.update(
options.username,
options.first_name,
options.last_name,
options.email,
options.is_active,
options.is_staff,
options.is_superuser,
)
return 0
def handle(proxy, options, config):
handlers = {
"add": handle_add,
"delete": handle_delete,
"groups": handle_groups,
"list": handle_list,
"perms": handle_perms,
"show": handle_show,
"update": handle_update,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/commands/utils.py 0000664 0000000 0000000 00000010506 15172666047 0017744 0 ustar 00root root 0000000 0000000 # 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 sys
from pathlib import Path
import jinja2
import ruamel.yaml
from lavacli.utils import safe_yaml
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 separated 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):
if options.filename.name == "":
for line in options.filename:
try:
jobs.print_logs([safe_yaml.load(line)], options.raw, options.filters)
except ruamel.yaml.YAMLError:
print("Invalid yaml file")
else:
try:
logs = safe_yaml.load(options.filename.read())
except ruamel.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/"]
if Path("/usr/share/lava-server/device-types/").exists():
options.path.append("/usr/share/lava-server/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]: "=".join(k.split("=")[1:]) for k in options.context}
except Exception:
print("Invalid context variable", file=sys.stderr)
print("Should be of the form key=value", file=sys.stderr)
return 1
try:
print(template.render(**context))
return 0
except jinja2.TemplateNotFound:
print("Unable to find the templates", file=sys.stderr)
return 1
def handle(proxy, options, _):
handlers = {"logs": handle_logs, "templates": handle_templates}
return handlers[options.sub_sub_command](proxy, options)
lavacli-2.8/lavacli/commands/workers.py 0000664 0000000 0000000 00000031305 15172666047 0020300 0 ustar 00root root 0000000 0000000 # 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 sys
import time
from lavacli.utils import safe_yaml
def positive_integer(value):
int_value = int(value)
if int_value < 0:
raise argparse.ArgumentTypeError("%r should be a positive integer" % value)
return int_value
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("name", type=str, help="worker name")
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
if version >= (2022, 4):
config_delete = config_sub.add_parser(
"delete", help="delete the worker configuration"
)
config_delete.add_argument("name", type=str, help="worker name")
config_get = config_sub.add_parser("get", help="get the worker configuration")
config_get.add_argument("name", type=str, help="worker name")
config_set = config_sub.add_parser("set", help="set the worker configuration")
config_set.add_argument("name", type=str, help="worker name")
config_set.add_argument(
"config", type=argparse.FileType("r"), help="configuration file"
)
if (2020, 4) <= version <= (2020, 8):
# "certificate"
workers_cert = sub.add_parser("certificate", help="worker certificate")
cert_sub = workers_cert.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
cert_sub.required = True
cert_get = cert_sub.add_parser("get", help="get the worker certificate")
cert_get.add_argument("name", type=str, help="worker name")
cert_set = cert_sub.add_parser("set", help="set the worker certificate")
cert_set.add_argument("name", type=str, help="worker name")
cert_set.add_argument(
"certificate", type=argparse.FileType("r"), help="certificate 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
if version >= (2022, 4):
env_delete = env_sub.add_parser(
"delete", help="delete the worker environment"
)
env_delete.add_argument("name", type=str, help="worker name")
env_get = env_sub.add_parser("get", help="get the worker environment")
env_get.add_argument("name", type=str, help="worker name")
env_set = env_sub.add_parser("set", help="set the worker environment")
env_set.add_argument("name", type=str, help="worker name")
env_set.add_argument(
"env", type=argparse.FileType("r"), help="environment file"
)
if version >= (2022, 1):
# "env-dut"
workers_env_dut = sub.add_parser("env-dut", help="worker environment")
env_dut_sub = workers_env_dut.add_subparsers(
dest="sub_sub_sub_command", help="Sub commands"
)
env_dut_sub.required = True
if version >= (2022, 4):
env_dut_delete = env_dut_sub.add_parser(
"delete", help="delete the dut environment"
)
env_dut_delete.add_argument("name", type=str, help="worker name")
env_dut_get = env_dut_sub.add_parser("get", help="get the dut environment")
env_dut_get.add_argument("name", type=str, help="worker name")
env_dut_set = env_dut_sub.add_parser("set", help="set the dut environment")
env_dut_set.add_argument("name", type=str, help="worker name")
env_dut_set.add_argument(
"env", type=argparse.FileType("r"), help="environment file"
)
# "list"
workers_list = sub.add_parser("list", help="list workers")
workers_list.add_argument(
"--all",
"-a",
action="store_true",
default=False,
help="list every workers, including retired",
)
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("name", type=str, help="worker name")
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("name", help="worker name")
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("name", type=str, help="worker name")
update_parser.add_argument(
"--description", type=str, default=None, help="worker description"
)
update_parser.add_argument(
"--health",
type=str,
default=None,
choices=["ACTIVE", "MAINTENANCE", "RETIRED"],
help="worker health",
)
if version >= (2020, 1):
update_parser.add_argument(
"--job-limit", type=positive_integer, default=None, help="job limit"
)
def help_string():
return "manage workers"
def handle_add(proxy, options, _):
proxy.scheduler.workers.add(options.name, options.description, options.disabled)
return 0
def handle_config(proxy, options, _):
if options.sub_sub_sub_command == "delete":
config = proxy.scheduler.workers.set_config(options.name, "")
elif options.sub_sub_sub_command == "get":
config = proxy.scheduler.workers.get_config(options.name)
print(str(config).rstrip("\n"))
else:
config = options.config.read()
ret = proxy.scheduler.workers.set_config(options.name, config)
if not ret:
print("Unable to store worker configuration", file=sys.stderr)
return 1
return 0
def handle_certificate(proxy, options, _):
if options.sub_sub_sub_command == "get":
env = proxy.scheduler.workers.get_certificate(options.name)
print(str(env).rstrip("\n"))
else:
certificate = options.certificate.read()
ret = proxy.scheduler.workers.set_certificate(options.name, certificate)
if not ret:
print("Unable to store worker certificate", file=sys.stderr)
return 1
return 0
def handle_env(proxy, options, _):
if options.sub_sub_sub_command == "delete":
proxy.scheduler.workers.set_env(options.name, "")
elif options.sub_sub_sub_command == "get":
env = proxy.scheduler.workers.get_env(options.name)
print(str(env).rstrip("\n"))
else:
env = options.env.read()
ret = proxy.scheduler.workers.set_env(options.name, env)
if not ret:
print("Unable to store worker environment", file=sys.stderr)
return 1
return 0
def handle_env_dut(proxy, options, _):
if options.sub_sub_sub_command == "delete":
proxy.scheduler.workers.set_env_dut(options.name, "")
elif options.sub_sub_sub_command == "get":
env = proxy.scheduler.workers.get_env_dut(options.name)
print(str(env).rstrip("\n"))
else:
env = options.env.read()
ret = proxy.scheduler.workers.set_env_dut(options.name, env)
if not ret:
print("Unable to store worker dut environment", file=sys.stderr)
return 1
return 0
def handle_list(proxy, options, config):
if config["version"] >= (2023, 3):
workers = proxy.scheduler.workers.list(options.all)
else:
workers = proxy.scheduler.workers.list()
if options.output_format == "json":
print(json.dumps(workers))
elif options.output_format == "yaml":
safe_yaml.dump(workers, sys.stdout)
else:
print("Workers:")
for worker in workers:
print("* %s" % worker)
return 0
def handle_maintenance(proxy, options, _):
proxy.scheduler.workers.update(options.name, None, "MAINTENANCE")
if options.force or options.wait:
worker_devices = proxy.scheduler.workers.show(options.name)["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.name)
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
safe_yaml.dump(worker, sys.stdout)
else:
print("hostname : %s" % worker["hostname"])
print("description : %s" % worker["description"])
print("state : %s" % worker["state"])
print("health : %s" % worker["health"])
print("devices : %s" % ", ".join(worker["devices"]))
print("last ping : %s" % worker["last_ping"])
if config["version"] >= (2020, 1):
print("job limit : %d" % worker["job_limit"])
if config["version"] >= (2020, 6):
print("version : %s" % worker["version"])
if "token" in worker:
print("token : %s" % worker["token"])
return 0
def handle_update(proxy, options, config):
if config["version"] >= (2020, 1):
proxy.scheduler.workers.update(
options.name, options.description, options.health, options.job_limit
)
else:
proxy.scheduler.workers.update(
options.name, options.description, options.health
)
return 0
def handle(proxy, options, config):
handlers = {
"add": handle_add,
"config": handle_config,
"certificate": handle_certificate,
"env": handle_env,
"env-dut": handle_env_dut,
"list": handle_list,
"maintenance": handle_maintenance,
"show": handle_show,
"update": handle_update,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-2.8/lavacli/schemas.py 0000664 0000000 0000000 00000011716 15172666047 0016432 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2022-present Linaro
# 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 voluptuous import All, Any, Invalid, Length, Range, Schema
from voluptuous.validators import Email
group_device_permission = Schema(
{
"name": All(str, Length(min=1)),
"group": All(str, Length(min=1)),
}
)
device_schema = Schema(
{
"hostname": All(str, Length(min=1)),
"device_type": All(str, Length(min=1)),
"worker": Any(str, None),
"description": str,
"tags": list,
"permissions": [group_device_permission],
"retire": bool,
},
)
device_types_schema = Schema(
Any(
{
"name": All(str, Length(min=1)),
"description": str,
"health_disabled": bool,
"health_denominator": Any("hours", "jobs"),
"health_frequency": All(int, Range(min=1)),
"aliases": list,
"display": bool,
"permissions": [group_device_permission],
},
None,
)
)
group_schema = Schema(Any({"name": str, "permissions": list}, None))
user_schema = Schema(
Any(
{
"username": All(str, Length(min=1)),
"last_name": All(str, Length(min=1)),
"first_name": All(str, Length(min=1)),
"email": Email(),
"is_superuser": bool,
"is_staff": bool,
"is_active": bool,
"ldap": bool,
"groups": list,
"permissions": list,
},
None,
)
)
worker_schema = Schema(
Any(
{
"hostname": str,
"description": str,
"job_limit": All(int, Range(min=1)),
"retire": bool,
},
None,
)
)
def user_group_must_exist(data: dict) -> dict:
users = data.get("users", {})
for user in users:
user_config = users[user]
if user_config:
for group in user_config.get("groups", []):
if group not in data.get("groups", {}):
raise Invalid(
f"Group must exist",
path=["users", user, "groups", group],
)
return data
def device_dt_must_exist(data: dict) -> dict:
devices = data.get("devices", {})
for device in devices:
dt = devices[device].get("device_type")
if dt and dt not in data.get("device_types", {}):
raise Invalid(
f"Device type must exist",
path=["devices", device, "device_type", dt],
)
return data
def device_worker_must_exist(data: dict) -> dict:
devices = data.get("devices", {})
for device in devices:
worker = devices[device].get("worker")
if worker and worker not in data.get("workers", {}):
raise Invalid(
f"Worker must exist",
path=["devices", device, "worker", worker],
)
return data
def device_perms_group_must_exist(data: dict) -> dict:
devices = data.get("devices", {})
for device in devices:
perms = devices[device].get("permissions", [])
for perm in perms:
group = perm["group"]
if group not in data.get("groups", {}):
raise Invalid(
f"Group must exist",
path=["devices", device, "permissions", perm],
)
return data
def dt_perms_group_must_exist(data: dict) -> dict:
dts = data.get("device_types", {})
for dt in dts:
dt_config = dts[dt]
if dt_config:
perms = dts[dt].get("permissions", [])
for perm in perms:
group = perm["group"]
if group not in data.get("groups", {}):
raise Invalid(
f"Group must exist",
path=["devices_types", dt, "permissions", perm],
)
return data
config_schema = Schema(
All(
{
"groups": {str: group_schema},
"users": {str: user_schema},
"workers": {str: worker_schema},
"device_types": {str: device_types_schema},
"devices": {str: device_schema},
},
user_group_must_exist,
device_dt_must_exist,
device_worker_must_exist,
device_perms_group_must_exist,
dt_perms_group_must_exist,
)
)
lavacli-2.8/lavacli/utils.py 0000664 0000000 0000000 00000012247 15172666047 0016147 0 ustar 00root root 0000000 0000000 # 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
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse
from ruamel.yaml import YAML
VERSION_LATEST = (3000, 1)
# yaml objects
flow_yaml = YAML(typ="safe")
flow_yaml.default_flow_style = False
log_yaml = YAML(typ="safe")
log_yaml.default_flow_style = True
log_yaml.default_style = '"'
log_yaml.width = 10**6
# 'safe' -> SafeLoader/SafeDumper
safe_yaml = YAML(typ="safe")
# 'rt'/None -> RoundTripLoader/RoundTripDumper (default)
rt_yaml = YAML(typ="rt")
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 exc2str(exc, url):
if isinstance(exc, xmlrpc.client.ProtocolError):
msg = exc.errmsg
if url is None:
return msg
p = urlparse(url)
if "@" in p.netloc:
uri = f"{p.scheme}://:@{p.netloc.split('@')[-1]}{p.path}"
else:
uri = f"{p.scheme}://{p.netloc}{p.path}"
return msg.replace(url, uri)
return str(exc)
def fetch_jobs(proxy, state, health, limit, since, start=0):
job_numbers = []
batch_size = 100
while len(job_numbers) < limit:
remaining = limit - len(job_numbers)
fetch_count = min(batch_size, remaining)
try:
jobs = proxy.scheduler.jobs.list(
state,
health,
start,
fetch_count,
since,
False,
)
except xmlrpc.client.Error as exc:
print(f"Error fetching jobs: {exc}")
break
if not jobs:
break
job_ids = [str(job["id"]) for job in jobs]
job_numbers.extend(job_ids)
start += batch_size
return job_numbers
def extract_device_name(job_output):
device_regex = re.compile(r"(?i)^\s*device\s*:\s*(.*)")
for line in job_output.splitlines():
match = device_regex.match(line)
if match:
return match.group(1).strip()
return None
def print_error_summary(error_summary, summary=True):
if summary:
print("\n=== Short log with error count type of error and devices ===")
else:
print("\n=== Unique Errors Found with job-url ===")
for error, device_jobs in sorted(
error_summary.items(),
key=lambda x: sum(len(jobs) for jobs in x[1].values()),
reverse=True,
):
total_count = sum(len(jobs) for jobs in device_jobs.values())
if summary:
devices_str = ", ".join(sorted(device_jobs))
print(f"[{total_count}] {error} (Devices: {devices_str})")
else:
print(f"\n[{total_count}] {error}")
for device in sorted(device_jobs):
print(f" - {device}:")
for url in sorted(device_jobs[device]):
print(f" * {url}")
def fetch_jobs_concurrent(
proxy, job_ids, fetch_func, max_workers=None, progress_callback=None
):
"""
Fetch multiple jobs concurrently using ThreadPoolExecutor.
Args:
proxy: XML-RPC proxy object
job_ids: List of job IDs to fetch
fetch_func: Function that takes (proxy, job_id) and returns job data
max_workers: Maximum number of concurrent workers (default: min(20, len(job_ids)))
progress_callback: Optional callback function called with (processed, total)
Returns:
List of (job_id, job_data) tuples. job_data is None if fetch failed.
"""
if not job_ids:
return []
if max_workers is None:
max_workers = min(20, len(job_ids))
results = []
processed = 0
def fetch_single(job_id):
try:
return job_id, fetch_func(proxy, job_id)
except Exception as exc:
# Return the exception for caller to handle
return job_id, exc
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_job = {
executor.submit(fetch_single, job_id): job_id for job_id in job_ids
}
for future in as_completed(future_to_job):
job_id, result = future.result()
results.append((job_id, result))
processed += 1
if progress_callback:
progress_callback(processed, len(job_ids))
return results
lavacli-2.8/requirements.txt 0000664 0000000 0000000 00000000057 15172666047 0016302 0 ustar 00root root 0000000 0000000 aiohttp
jinja2
requests
ruamel.yaml
voluptuous
lavacli-2.8/setup.py 0000664 0000000 0000000 00000004533 15172666047 0014533 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# 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://gitlab.com/lava/lavacli/issues/",
"Source Code": "https://gitlab.com/lava/lavacli/",
},
python_requires=">=3.8",
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.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"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=["aiohttp", "jinja2", "requests", "ruamel.yaml", "voluptuous"],
setup_requires=[],
tests_require=["pytest", "pytest-runner"],
zip_safe=True,
)
lavacli-2.8/share/ 0000775 0000000 0000000 00000000000 15172666047 0014116 5 ustar 00root root 0000000 0000000 lavacli-2.8/share/lavacli.yaml 0000664 0000000 0000000 00000001506 15172666047 0016417 0 ustar 00root root 0000000 0000000 validation:
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-2.8/share/release.sh 0000775 0000000 0000000 00000003725 15172666047 0016104 0 ustar 00root root 0000000 0000000 #!/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
export EMAIL=$(git config user.email)
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 --repository lavacli dist"
read
twine upload --repository lavacli dist/*
echo "done"
echo
fi
lavacli-2.8/tests/ 0000775 0000000 0000000 00000000000 15172666047 0014156 5 ustar 00root root 0000000 0000000 lavacli-2.8/tests/__init__.py 0000664 0000000 0000000 00000000000 15172666047 0016255 0 ustar 00root root 0000000 0000000 lavacli-2.8/tests/conftest.py 0000664 0000000 0000000 00000003701 15172666047 0016356 0 ustar 00root root 0000000 0000000 # 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 xmlrpc.client
import pytest
from lavacli.utils import safe_yaml
class RecordingProxyFactory:
def __new__(cls, proxy_data):
class RecordingProxy:
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
ret = data["ret"]
if isinstance(ret, dict) and ret.get("fault_code"):
raise xmlrpc.client.Fault(ret.get("fault_code"), "fault string")
return ret
def __getattr__(self, attr):
self.request.append(attr)
return self
return RecordingProxy
@pytest.fixture
def setup(monkeypatch, tmp_path):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
with (tmp_path / "lavacli.yaml").open("w") as f_conf:
safe_yaml.dump({"default": {"uri": "https://lava.example.com/RPC2"}}, f_conf)
monkeypatch.setattr(xmlrpc.client, "ServerProxy", RecordingProxyFactory(None))
lavacli-2.8/tests/test_aliases.py 0000664 0000000 0000000 00000021426 15172666047 0017215 0 ustar 00root root 0000000 0000000 # 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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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-2.8/tests/test_device_types.py 0000664 0000000 0000000 00000047137 15172666047 0020266 0 ustar 00root root 0000000 0000000 # 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_dt_add(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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_delete(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"device-types",
"health-check",
"delete",
"mydt",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.device_types.set_health_check",
"args": ("mydt", ""),
"ret": None,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
def test_dt_hc_get_after_2019_1(setup, monkeypatch, capsys):
version = "2019.1"
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_2019_1(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
with (tmp_path / "hc.yaml").open("w") as f_hc:
f_hc.write("definition")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"device-types",
"health-check",
"set",
"mydt",
str(tmp_path / "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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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_delete(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"device-types",
"template",
"delete",
"bbb",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.device_types.set_template",
"args": ("bbb", ""),
"ret": None,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
def test_dt_template_get(setup, monkeypatch, capsys):
version = "2019.1"
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, tmp_path):
version = "2019.1"
with (tmp_path / "template.jinja2").open("w") as f_hc:
f_hc.write("template definition")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"device-types",
"template",
"set",
"bbb",
str(tmp_path / "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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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-2.8/tests/test_devices.py 0000664 0000000 0000000 00000077575 15172666047 0017236 0 ustar 00root root 0000000 0000000 # 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
from lavacli import main
def test_devices_add(setup, monkeypatch, capsys):
version = "2019.1"
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(setup, monkeypatch, capsys):
version = "2019.1"
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(setup, monkeypatch, capsys):
version = "2019.1"
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_delete(setup, monkeypatch, capsys):
version = "2022.4"
monkeypatch.setattr(sys, "argv", ["lavacli", "devices", "dict", "delete", "qemu01"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.devices.set_dictionary",
"args": ("qemu01", ""),
"ret": True,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
def test_devices_dict_get(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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": """{"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 = "2019.1"
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": """{"hello": [{"world": "as usual"}, "my"]}""",
},
],
)
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "list index out of range (2 vs 2)\n" # nosec
def test_devices_dict_get_render_field_missing(setup, monkeypatch, capsys):
version = "2019.1"
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": """{"hello": [{"world": "as usual"}, "my"]}""",
},
],
)
assert main() == 1 # nosec
assert ( # nosec
capsys.readouterr()[1] == "Unknown key 'worl' for '{'world': 'as usual'}'\n"
)
def test_devices_dict_get_render_field_missing_1(setup, monkeypatch, capsys):
version = "2019.1"
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": """{"hello": [{"world": "as usual"}, "my"]}""",
},
],
)
assert main() == 1 # nosec
assert ( # nosec
capsys.readouterr()[1] == "Unable to lookup inside 'as usual' for '0'\n"
)
def test_devices_dict_get_render_field_missing_2(setup, monkeypatch, capsys):
version = "2019.1"
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": """{"hello": [{"world": "as usual"}, "my"]}""",
},
],
)
assert main() == 1 # nosec
assert ( # nosec
capsys.readouterr()[1] == "Unable to lookup inside 'as usual' for 'missing'\n"
)
def test_devices_dict_get_jinja2_field(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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()[1] == "Unknown field 'world'\n" # nosec
def test_devices_dict_set(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
with (tmp_path / "dict.jinja2").open("w") as f_conf:
f_conf.write("{% set exclusive = True %}")
monkeypatch.setattr(
sys,
"argv",
["lavacli", "devices", "dict", "set", "qemu01", str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "dict.jinja2").open("w") as f_conf:
f_conf.write("{% set exclusive = True %}")
monkeypatch.setattr(
sys,
"argv",
["lavacli", "devices", "dict", "set", "qemu01", str(tmp_path / "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()[1] == "Unable to set the configuration\n" # nosec
def test_devices_list(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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_maintenance(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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_tags_add(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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
lavacli-2.8/tests/test_events.py 0000664 0000000 0000000 00000057703 15172666047 0017107 0 ustar 00root root 0000000 0000000 # 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:
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:
def socket(self, sock_type):
assert sock_type == zmq.SUB # nosec
return DummySocket()
def test_events_listen(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
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
readouterr = capsys.readouterr()
assert ( # nosec
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)
\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
"""
)
assert ( # nosec
readouterr[1]
== "Invalid message: invalid message\nUnknown error: pop from empty list\n"
)
def test_events_listen_config(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
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
readouterr = capsys.readouterr()
assert readouterr[0] == "Listening to tcp://localhost:5501\n" # nosec
assert readouterr[1] == "Unknown error: pop from empty list\n" # nosec
def test_events_listen_config_2(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
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 (tmp_path / "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
readouterr = capsys.readouterr()
assert readouterr[0] == "Listening to tcp://localhost:789\n" # nosec
assert readouterr[1] == "Unknown error: pop from empty list\n" # nosec
def test_events_listen_filter(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
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
readouterr = capsys.readouterr()
assert ( # nosec
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
"""
)
assert ( # nosec
readouterr[1]
== "Invalid message: invalid message\nUnknown error: pop from empty list\n"
)
def test_events_listen_filter_2(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
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
readouterr = capsys.readouterr()
assert ( # nosec
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-31\033[0m \033[1;37mv.l.o.worker\033[0m \033[32madmin\033[0m - [worker-01] state=Active health=Maintenance
"""
)
assert ( # nosec
readouterr[1]
== "Invalid message: invalid message\nUnknown error: pop from empty list\n"
)
def test_events_wait_device(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
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, tmp_path):
version = "2019.1"
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, tmp_path):
version = "2019.1"
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, tmp_path):
version = "2019.1"
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, tmp_path):
version = "2019.1"
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, tmp_path):
version = "2019.1"
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
readouterr = capsys.readouterr()
assert readouterr[0] == "Listening to tcp://lava.example.com:5500\n" # nosec
assert readouterr[1] == "Invalid message: strange\n" # nosec
assert DummySocket.data == [] # nosec
lavacli-2.8/tests/test_helpers.py 0000664 0000000 0000000 00000002454 15172666047 0017236 0 ustar 00root root 0000000 0000000 # 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 VERSION_LATEST, parse_version
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("2019.1-1-1") == (2019, 1) # nosec
assert parse_version("2019.1.post2-1+stretch") == (2019, 1) # 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-2.8/tests/test_identities.py 0000664 0000000 0000000 00000016520 15172666047 0017734 0 ustar 00root root 0000000 0000000 # 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
from lavacli import main
from lavacli.utils import safe_yaml
def test_identities_add(setup, monkeypatch, capsys, tmp_path):
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 (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.load(f_in)
assert set(data.keys()) == {"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, tmp_path):
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 (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.load(f_in)
assert set(data.keys()) == {"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, tmp_path):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"identities",
"add",
"v.l.o",
"--uri",
"https://validation.linaro.org/RPC2",
],
)
(tmp_path / "lavacli.yaml").unlink()
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
with (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.load(f_in)
assert set(data.keys()) == {"v.l.o"} # nosec
assert data["v.l.o"] == {"uri": "https://validation.linaro.org/RPC2"} # nosec
def test_identities_delete(setup, monkeypatch, capsys, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "delete", "v.l.o"])
with (tmp_path / "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 (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.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, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "delete", "v.l.o"])
(tmp_path / "lavacli.yaml").unlink()
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Unknown identity 'v.l.o'\n" # nosec
assert not (tmp_path / "lavacli.yaml").exists() # nosec
def test_identities_delete_missing_key(setup, monkeypatch, capsys, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "delete", "v.l.o"])
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Unknown identity 'v.l.o'\n" # nosec
with (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.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, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "list"])
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "Identities:\n* default\n" # nosec
with (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.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, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "list"])
with (tmp_path / "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 (tmp_path / "lavacli.yaml").open() as f_in:
data = safe_yaml.load(f_in)
assert set(data.keys()) == {"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, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "list"])
(tmp_path / "lavacli.yaml").unlink()
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "Identities:\n" # nosec
assert not (tmp_path / "lavacli.yaml").exists() # nosec
def test_identities_show(setup, monkeypatch, capsys, tmp_path):
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, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "missing"])
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Unknown identity 'missing'\n" # nosec
def test_identities_show_no_config(setup, monkeypatch, capsys, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "default"])
(tmp_path / "lavacli.yaml").unlink()
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Unknown identity 'default'\n" # nosec
def test_identities_show_invalid_config(setup, monkeypatch, capsys, tmp_path):
monkeypatch.setattr(sys, "argv", ["lavacli", "identities", "show", "default"])
with (tmp_path / "lavacli.yaml").open("w") as f_conf:
f_conf.write("hello")
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Invalid configuration file\n" # nosec
lavacli-2.8/tests/test_jobs.py 0000664 0000000 0000000 00000165634 15172666047 0016543 0 ustar 00root root 0000000 0000000 # 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
from lavacli import main
from lavacli.utils import safe_yaml
def test_jobs_cancel(setup, monkeypatch, capsys):
version = "2019.1"
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_autocancel(setup, monkeypatch, capsys):
monkeypatch.setattr(
sys, "argv", ["lavacli", "jobs", "autocancel", "--duration", "1440"]
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": "2023.10"},
{
"request": "scheduler.jobs.list",
"args": ("RUNNING", None, 0, 100, None, False, 1440),
"ret": [
{
"id": "16",
"description": "hello",
"device_type": "bbb",
"health": "Unknown",
"state": "Running",
"submitter": "lava",
},
{
"id": "17",
"description": "something",
"device_type": "qemu",
"health": "Unknown",
"state": "Running",
"submitter": "admin",
},
],
},
{
"request": "scheduler.jobs.definition",
"args": ("16",),
"ret": "timeouts:\n job:\n minutes: 720\n",
},
{"request": "scheduler.jobs.cancel", "args": ("16",), "ret": None},
{
"request": "scheduler.jobs.definition",
"args": ("17",),
"ret": "timeouts:\n job:\n minutes: 1445\n",
},
{
"request": "scheduler.jobs.list",
"args": ("RUNNING", None, 0, 100, None, False, 1440),
"ret": [],
},
],
)
assert main() == 0
assert (
capsys.readouterr()[0]
== """[CANCELED] 16: [lava] (hello) - bbb
[ SKIP ] 17: [admin] (something) - qemu - timeout not reached yet\n"""
)
def test_jobs_config(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
monkeypatch.setattr(
sys, "argv", ["lavacli", "jobs", "config", "1234", "--dest", str(tmp_path)]
)
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 (tmp_path / "definition.yaml").open() as f_in:
assert f_in.read() == "definition" # nosec
with (tmp_path / "device.yaml").open() as f_in:
assert f_in.read() == "device" # nosec
with (tmp_path / "dispatcher.yaml").open() as f_in:
assert f_in.read() == "dispatcher" # nosec
with (tmp_path / "env.yaml").open() as f_in:
assert f_in.read() == "env" # nosec
with (tmp_path / "env.dut.yaml").open() as f_in:
assert f_in.read() == "env.dut" # nosec
def test_jobs_definition(setup, monkeypatch, capsys):
version = "2019.1"
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(setup, monkeypatch, capsys):
version = "2019.1"
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": "Finished",
"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: Finished,Complete [lava] (hello) - bbb
* 12: Running,Unknown [admin] (something) - \n"""
)
def test_jobs_list_since_verbose(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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, 0, False),
"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 = "2019.1"
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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("1234", 1, None),
"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: 2019.1-1"
)
assert lines[1][:20] == "2018-04-23T12:07:02 " # nosec
assert safe_yaml.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 = "2019.1"
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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("1234", 1, None),
"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: 2019.1-1"
)
assert lines[1][:20] == "2018-04-23T12:07:02 " # nosec
assert safe_yaml.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 = "2019.1"
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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("1234", 1, None),
"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: 2019.1-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 = "2019.1"
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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("1234", 1, None),
"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: 2019.1-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 = "2019.1"
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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("1234", 1, None),
"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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("1234", 1, None),
"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: 2019.1-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, tmp_path):
version = "2019.1"
now = xmlrpc.client.DateTime("20180128T01:01:01")
def sleep(duration):
assert duration == 5 # nosec
with (tmp_path / "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(tmp_path / "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, None),
"ret": (
False,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.logs",
"args": ("4567", 1, None),
"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: 2019.1-1"
)
assert lines[2][:20] == "2018-04-23T12:07:02 " # nosec
assert safe_yaml.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(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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, tmp_path):
version = "2019.1"
with (tmp_path / "job.yaml").open("w") as f_out:
f_out.write("job definition as yaml")
monkeypatch.setattr(
sys, "argv", ["lavacli", "jobs", "submit", str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "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(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "job.yaml").open("w") as f_out:
f_out.write("job definition as yaml")
monkeypatch.setattr(
sys, "argv", ["lavacli", "jobs", "submit", str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "job.yaml").open("w") as f_out:
f_out.write("job definition as yaml")
with (tmp_path / "lavacli.yaml").open("w") as f_conf:
safe_yaml.dump(
{
"default": {"uri": "https://lava.example.com/RPC2"},
"admin": {"uri": "https://localhost:8001/RPC2"},
},
f_conf,
)
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"-i",
"admin",
"jobs",
"submit",
str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "job1.yaml").open("w") as f_out:
f_out.write("first job definition as yaml")
with (tmp_path / "job2.yaml").open("w") as f_out:
f_out.write("second job definition as yaml")
with (tmp_path / "job3.yaml").open("w") as f_out:
f_out.write("third job definition as yaml")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"jobs",
"submit",
str(tmp_path / "job1.yaml"),
str(tmp_path / "job2.yaml"),
str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "job.yaml").open("w") as f_out:
f_out.write("job definition as yaml")
monkeypatch.setattr(
sys, "argv", ["lavacli", "jobs", "submit", str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "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(tmp_path / "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 = "2019.1"
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
def test_jobs_submit_follow(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
with (tmp_path / "job.yaml").open("w") as f_out:
f_out.write("job definition as yaml")
monkeypatch.setattr(
sys,
"argv",
["lavacli", "jobs", "submit", "--follow", str(tmp_path / "job.yaml")],
)
now = xmlrpc.client.DateTime("20180128T01:01:01")
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.jobs.submit",
"args": ("job definition as yaml",),
"ret": 5689,
},
{
"request": "scheduler.jobs.logs",
"args": ("5689", 0, None),
"ret": (
True,
'- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "lava-dispatcher, installed at version: 2019.1-1"}',
),
},
{
"request": "scheduler.jobs.show",
"args": ("5689",),
"ret": {
"id": "5689",
"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 "lava-dispatcher, installed at version: 2019.1" in capsys.readouterr()[0]
lavacli-2.8/tests/test_lab.py 0000664 0000000 0000000 00000430225 15172666047 0016333 0 ustar 00root root 0000000 0000000 import sys
import xmlrpc.client
import pytest
import ruamel.yaml
from lavacli import main
from lavacli.commands.lab import ConfigFile
from lavacli.utils import safe_yaml
@pytest.fixture
def mock_get():
class GetData:
def __init__(self):
self.system_version_2023_2 = {
"request": "system.version",
"args": (),
"ret": 2023.2,
}
self.system_version_2023_3 = {
"request": "system.version",
"args": (),
"ret": 2023.3,
}
self.system_version_2023_05 = {
"request": "system.version",
"args": (),
"ret": 2023.05,
}
self.auth_groups_list_empty = {
"request": "auth.groups.list",
"args": (),
"ret": [],
}
self.auth_groups_list = {
"request": "auth.groups.list",
"args": (),
"ret": ["group1", "group2"],
}
self.auth_groups_show_group1 = {
"request": "auth.groups.show",
"args": ("group1",),
"ret": {
"id": 5,
"name": "group1",
"permissions": ["auth.user.add_user"],
"users": ["user1"],
},
}
self.auth_groups_show_group2 = {
"request": "auth.groups.show",
"args": ("group2",),
"ret": {
"id": 6,
"name": "group2",
"permissions": ["auth.user.delete_user"],
"users": ["user2"],
},
}
self.auth_groups_show_group3 = {
"request": "auth.groups.show",
"args": ("group3",),
"ret": {
"id": 9,
"name": "group3",
"permissions": ["auth.group.add_group"],
"users": ["user3"],
},
}
self.auth_users_list_empty = {
"request": "auth.users.list",
"args": (),
"ret": [],
}
self.auth_users_list = {
"request": "auth.users.list",
"args": (),
"ret": [
{
"username": "user1",
"last_name": "",
"first_name": "cheese",
"is_superuser": False,
"is_staff": False,
"is_active": True,
},
{
"username": "user2",
"last_name": "",
"first_name": "",
"is_superuser": False,
"is_staff": False,
"is_active": True,
},
],
}
self.auth_users_show_user1 = {
"request": "auth.users.show",
"args": ("user1",),
"ret": {
"email": "",
"first_name": "",
"groups": ["group1"],
"permissions": ["lava_scheduler_app.device.add_device"],
"id": 4,
"is_active": True,
"is_staff": False,
"is_superuser": False,
"last_login": None,
"last_name": "",
"username": "user1",
},
}
self.auth_users_show_user2 = {
"request": "auth.users.show",
"args": ("user2",),
"ret": {
"email": "",
"first_name": "",
"groups": ["group2"],
"permissions": ["lava_scheduler_app.device.delete_device"],
"id": 5,
"is_active": True,
"is_staff": False,
"is_superuser": False,
"last_login": None,
"last_name": "",
"username": "user2",
},
}
self.auth_users_show_user3 = {
"request": "auth.users.show",
"args": ("user3",),
"ret": {
"email": "",
"first_name": "",
"groups": ["group3"],
"permissions": [],
"id": 14,
"is_active": True,
"is_staff": False,
"is_superuser": False,
"last_login": None,
"last_name": "",
"username": "user3",
},
}
self.auth_users_show_user3_ldap = {
"request": "auth.users.show",
"args": ("user3",),
"ret": {
"email": "first.last@linaro,org",
"first_name": "First",
"groups": ["group3"],
"permissions": [],
"id": 14,
"is_active": True,
"is_staff": False,
"is_superuser": False,
"last_login": None,
"last_name": "Last",
"username": "user3",
},
}
self.scheduler_device_types_list_empty = {
"request": "scheduler.device_types.list",
"args": (False,),
"ret": [],
}
self.scheduler_device_types_list = {
"request": "scheduler.device_types.list",
"args": (False,),
"ret": [
{
"name": "docker",
"devices": 2,
"installed": True,
"template": True,
},
{"name": "qemu", "devices": 2, "installed": True, "template": True},
],
}
self.scheduler_device_types_show_docker = {
"request": "scheduler.device_types.show",
"args": ("docker",),
"ret": {
"name": "docker",
"description": "",
"display": True,
"health_disabled": False,
"health_denominator": "hours",
"health_frequency": 24,
"aliases": [],
"devices": ["docker-01", "docker-02"],
"default_template": True,
"permissions": [
{"name": "change_devicetype", "group": "group1"},
],
},
}
self.scheduler_device_types_show_docker_custom_template = {
"request": "scheduler.device_types.show",
"args": ("docker",),
"ret": {
"name": "docker",
"description": "",
"display": True,
"health_disabled": False,
"health_denominator": "hours",
"health_frequency": 24,
"aliases": [],
"devices": ["docker-01", "docker-02"],
"default_template": False,
"permissions": [
{"name": "change_devicetype", "group": "group1"},
],
},
}
self.scheduler_device_types_get_health_check_docker = {
"request": "scheduler.device_types.get_health_check",
"args": ("docker",),
"ret": "hc-definition",
}
self.scheduler_device_types_get_health_check_docker_empty = {
"request": "scheduler.device_types.get_health_check",
"args": ("docker",),
"ret": {"fault_code": 404},
}
self.scheduler_device_types_get_template_docker = {
"request": "scheduler.device_types.get_template",
"args": ("docker",),
"ret": "template content",
}
self.scheduler_device_types_show_qemu = {
"request": "scheduler.device_types.show",
"args": ("qemu",),
"ret": {
"name": "qemu",
"description": None,
"display": True,
"health_disabled": False,
"health_denominator": "hours",
"health_frequency": 24,
"aliases": [],
"devices": ["qemu-01", "qemu-02"],
"default_template": True,
},
}
self.scheduler_device_types_show_qemu_custom_template = {
"request": "scheduler.device_types.show",
"args": ("qemu",),
"ret": {
"name": "qemu",
"description": None,
"display": True,
"health_disabled": False,
"health_denominator": "hours",
"health_frequency": 24,
"aliases": [],
"devices": ["qemu-01", "qemu-02"],
"default_template": False,
},
}
self.scheduler_device_types_get_health_check_qemu = {
"request": "scheduler.device_types.get_health_check",
"args": ("qemu",),
"ret": "hc-definition",
}
self.scheduler_device_types_show_bbb = {
"request": "scheduler.device_types.show",
"args": ("bbb",),
"ret": {
"name": "bbb",
"description": None,
"display": True,
"health_disabled": False,
"health_denominator": "hours",
"health_frequency": 24,
"aliases": [],
"devices": [],
"default_template": True,
},
}
self.scheduler_device_types_get_health_check_bbb = {
"request": "scheduler.device_types.get_health_check",
"args": ("bbb",),
"ret": "hc-definition",
}
self.scheduler_device_types_get_template_qemu = {
"request": "scheduler.device_types.get_template",
"args": ("qemu",),
"ret": "template content",
}
self.scheduler_workers_list_empty = {
"request": "scheduler.workers.list",
"args": (True,),
"ret": [],
}
self.scheduler_workers_list_empty_2023_2 = {
"request": "scheduler.workers.list",
"args": (),
"ret": [],
}
self.scheduler_workers_list = {
"request": "scheduler.workers.list",
"args": (True,),
"ret": ["worker01", "worker02"],
}
self.scheduler_workers_list_all = {
"request": "scheduler.workers.list",
"args": (True,),
"ret": ["worker01", "worker02"],
}
self.scheduler_workers_list_all_2023_2 = {
"request": "scheduler.workers.list",
"args": (),
"ret": ["worker01", "worker02"],
}
self.scheduler_workers_show_worker01 = {
"request": "scheduler.workers.show",
"args": ("worker01",),
"ret": {
"hostname": "worker01",
"description": "",
"state": "Online",
"health": "Active",
"devices": ["docker-01", "qemu-01"],
"job_limit": 0,
"version": "2023.03",
"default_config": True,
"default_env": True,
"default_env_dut": True,
},
}
self.scheduler_workers_show_retired_worker01 = {
"request": "scheduler.workers.show",
"args": ("worker01",),
"ret": {
"hostname": "worker01",
"description": "",
"state": "Online",
"health": "Retired",
"devices": ["docker-01", "qemu-01"],
"job_limit": 0,
"version": "2023.03",
"default_config": True,
"default_env": True,
"default_env_dut": True,
},
}
self.scheduler_workers_show_worker01_custom_config = {
"request": "scheduler.workers.show",
"args": ("worker01",),
"ret": {
"hostname": "worker01",
"description": "",
"state": "Online",
"health": "Active",
"devices": ["docker-01", "qemu-01"],
"job_limit": 0,
"version": "2023.03",
"default_config": False,
"default_env": True,
"default_env_dut": True,
},
}
self.scheduler_workers_get_config_worker01 = {
"request": "scheduler.workers.get_config",
"args": ("worker01",),
"ret": "config content",
}
self.scheduler_workers_show_worker01_custom_env = {
"request": "scheduler.workers.show",
"args": ("worker01",),
"ret": {
"hostname": "worker01",
"description": "",
"state": "Online",
"health": "Active",
"devices": ["docker-01", "qemu-01"],
"job_limit": 0,
"version": "2023.03",
"default_config": True,
"default_env": False,
"default_env_dut": True,
},
}
self.scheduler_workers_get_env_worker01 = {
"request": "scheduler.workers.get_env",
"args": ("worker01",),
"ret": "env content",
}
self.scheduler_workers_show_worker01_custom_env_dut = {
"request": "scheduler.workers.show",
"args": ("worker01",),
"ret": {
"hostname": "worker01",
"description": "",
"state": "Online",
"health": "Active",
"devices": ["docker-01", "qemu-01"],
"job_limit": 0,
"version": "2023.03",
"default_config": True,
"default_env": True,
"default_env_dut": False,
},
}
self.scheduler_workers_get_env_dut_worker01 = {
"request": "scheduler.workers.get_env_dut",
"args": ("worker01",),
"ret": "env-dut content",
}
self.scheduler_workers_show_worker02 = {
"request": "scheduler.workers.show",
"args": ("worker02",),
"ret": {
"hostname": "worker02",
"description": "",
"state": "Offline",
"health": "Active",
"devices": ["docker-02", "qemu-02"],
"job_limit": 0,
"version": "2023.02.0042.g2755aa13a",
"default_config": True,
"default_env": True,
"default_env_dut": True,
},
}
self.scheduler_workers_show_worker03 = {
"request": "scheduler.workers.show",
"args": ("worker03",),
"ret": {
"hostname": "worker03",
"description": "",
"state": "Offline",
"health": "Active",
"devices": [],
"job_limit": 0,
"version": None,
"default_config": True,
"default_env": True,
"default_env_dut": True,
},
}
self.scheduler_devices_list_empty = {
"request": "scheduler.devices.list",
"args": (True,),
"ret": [],
}
self.scheduler_devices_list = {
"request": "scheduler.devices.list",
"args": (True,),
"ret": [
{
"hostname": "docker-01",
"type": "docker",
"health": "Good",
"state": "Idle",
"current_job": None,
"pipeline": True,
},
{
"hostname": "docker-02",
"type": "docker",
"health": "Unknown",
"state": "Idle",
"current_job": None,
"pipeline": True,
},
{
"hostname": "qemu-01",
"type": "qemu",
"health": "Good",
"state": "Idle",
"current_job": None,
"pipeline": True,
},
{
"hostname": "qemu-02",
"type": "qemu",
"health": "Unknown",
"state": "Idle",
"current_job": None,
"pipeline": True,
},
],
}
self.scheduler_devices_show_docker_01 = {
"request": "scheduler.devices.show",
"args": ("docker-01",),
"ret": {
"hostname": "docker-01",
"device_type": "docker",
"health": "Good",
"state": "Idle",
"health_job": True,
"description": "Created automatically by LAVA.",
"pipeline": True,
"has_device_dict": True,
"worker": "worker01",
"current_job": None,
"tags": ["docker-01", "worker"],
"permissions": [
{"name": "change_devicetype", "group": "group1"},
],
},
}
self.scheduler_devices_get_dictionary_docker_01 = {
"request": "scheduler.devices.get_dictionary",
"args": ("docker-01",),
"ret": "yaml_dict",
}
self.scheduler_devices_show_docker_02 = {
"request": "scheduler.devices.show",
"args": ("docker-02",),
"ret": {
"hostname": "docker-02",
"device_type": "docker",
"health": "Unknown",
"state": "Idle",
"health_job": True,
"description": "Created automatically by LAVA.",
"pipeline": True,
"has_device_dict": True,
"worker": "worker02",
"current_job": None,
"tags": ["docker-02", "docker-worker"],
},
}
self.scheduler_devices_get_dictionary_docker_02 = {
"request": "scheduler.devices.get_dictionary",
"args": ("docker-02",),
"ret": "yaml_dict",
}
self.scheduler_devices_show_qemu_01 = {
"request": "scheduler.devices.show",
"args": ("qemu-01",),
"ret": {
"hostname": "qemu-01",
"device_type": "qemu",
"health": "Good",
"state": "Idle",
"health_job": True,
"description": "Created automatically by LAVA.",
"pipeline": True,
"has_device_dict": True,
"worker": "worker01",
"current_job": None,
"tags": [],
},
}
self.scheduler_devices_show_retired_qemu_01 = {
"request": "scheduler.devices.show",
"args": ("qemu-01",),
"ret": {
"hostname": "qemu-01",
"device_type": "qemu",
"health": "Retired",
"state": "Idle",
"health_job": True,
"description": "Created automatically by LAVA.",
"pipeline": True,
"has_device_dict": True,
"worker": "worker01",
"current_job": None,
"tags": [],
},
}
self.scheduler_devices_get_dictionary_qemu_01 = {
"request": "scheduler.devices.get_dictionary",
"args": ("qemu-01",),
"ret": "yaml_dict",
}
self.scheduler_devices_show_qemu_02 = {
"request": "scheduler.devices.show",
"args": ("qemu-02",),
"ret": {
"hostname": "qemu-02",
"device_type": "qemu",
"health": "Unknown",
"state": "Idle",
"health_job": True,
"description": "Created automatically by LAVA.",
"pipeline": True,
"has_device_dict": True,
"worker": "worker02",
"current_job": None,
"tags": [],
},
}
self.scheduler_devices_get_dictionary_qemu_02 = {
"request": "scheduler.devices.get_dictionary",
"args": ("qemu-02",),
"ret": "yaml_dict",
}
self.scheduler_devices_show_qemu_03 = {
"request": "scheduler.devices.show",
"args": ("qemu-03",),
"ret": {
"hostname": "qemu-03",
"device_type": "qemu",
"health": "Unknown",
"state": "Idle",
"health_job": True,
"description": "qemu03",
"pipeline": True,
"has_device_dict": True,
"worker": "worker01",
"current_job": None,
"tags": [],
},
}
self.scheduler_devices_get_dictionary_qemu_03 = {
"request": "scheduler.devices.get_dictionary",
"args": ("qemu-03",),
"ret": "yaml_dict",
}
return GetData()
@pytest.fixture
def mock_post():
class PostData:
def __init__(self):
self.auth_groups_add_group3 = {
"request": "auth.groups.add",
"args": ("group3",),
"ret": None,
}
self.auth_groups_delete_group2 = {
"request": "auth.groups.delete",
"args": ("group2",),
"ret": None,
}
self.auth_groups_perms_add_group1 = {
"request": "auth.groups.perms.add",
"args": ("group1", "auth", "user", "delete_user"),
"ret": None,
}
self.auth_groups_perms_delete_group1 = {
"request": "auth.groups.perms.delete",
"args": ("group1", "auth", "user", "add_user"),
"ret": None,
}
self.auth_users_add_user3 = {
"request": "auth.users.add",
"args": ("user3", None, None, None, True, False, False, False),
"ret": None,
}
self.auth_users_add_user3_ldap = {
"request": "auth.users.add",
"args": ("user3", None, None, None, True, False, False, True),
"ret": None,
}
self.auth_users_delete_user2 = {
"request": "auth.users.delete",
"args": ("user2",),
"ret": None,
}
self.auth_users_perms_add_user1 = {
"request": "auth.users.perms.add",
"args": ("user1", "lava_scheduler_app", "device", "delete_device"),
"ret": None,
}
self.auth_users_update_user1 = {
"request": "auth.users.update",
"args": ("user1", None, None, None, None, None, None),
"ret": None,
}
self.auth_users_perms_delete_user1 = {
"request": "auth.users.perms.delete",
"args": ("user1", "lava_scheduler_app", "device", "add_device"),
"ret": None,
}
self.auth_users_update_user2 = {
"request": "auth.users.update",
"args": ("user2", "first", "last", "user2@email.io", False, True, True),
"ret": None,
}
self.auth_users_groups_add_user1_group2 = {
"request": "auth.users.groups.add",
"args": ("user1", "group2"),
"ret": None,
}
self.auth_users_groups_delete_user1_group1 = {
"request": "auth.users.groups.delete",
"args": ("user1", "group1"),
"ret": None,
}
self.scheduler_device_types_add_bbb = {
"request": "scheduler.device_types.add",
"args": ("bbb", None, True, None, 24, "hours"),
"ret": None,
}
self.scheduler_device_types_hide_qemu = {
"request": "scheduler.device_types.update",
"args": ("qemu", None, False, None, None, None, None),
"ret": None,
}
self.scheduler_device_types_update_docker = {
"request": "scheduler.device_types.update",
"args": ("docker", "new", False, None, 12, "jobs", True),
"ret": None,
}
self.scheduler_device_types_set_health_check_docker_add = {
"request": "scheduler.device_types.set_health_check",
"args": ("docker", "hc-definition"),
"ret": None,
}
self.scheduler_device_types_set_health_check_docker_del = {
"request": "scheduler.device_types.set_health_check",
"args": ("docker", None),
"ret": None,
}
self.scheduler_device_types_set_health_check_docker_update = {
"request": "scheduler.device_types.set_health_check",
"args": ("docker", "new-hc-definition"),
"ret": None,
}
self.scheduler_device_types_set_template_docker = {
"request": "scheduler.device_types.set_template",
"args": ("docker", "new template definition"),
"ret": None,
}
self.scheduler_device_types_perms_add_docker = {
"request": "scheduler.device_types.perms_add",
"args": ("docker", "group1", "view_devicetype"),
"ret": None,
}
self.scheduler_device_types_perms_delete_docker = {
"request": "scheduler.device_types.perms_delete",
"args": ("docker", "group1", "change_devicetype"),
"ret": None,
}
self.scheduler_workers_add_worker03 = {
"request": "scheduler.workers.add",
"args": ("worker03", "", False),
"ret": None,
}
self.scheduler_workers_delete_worker02 = {
"request": "scheduler.workers.delete",
"args": ("worker02",),
"ret": None,
}
self.scheduler_workers_update_worker01 = {
"request": "scheduler.workers.update",
"args": ("worker01", "new", None, 10),
"ret": None,
}
self.scheduler_workers_retire_worker01 = {
"request": "scheduler.workers.update",
"args": ("worker01", None, "RETIRED", None),
"ret": None,
}
self.scheduler_workers_unretire_worker01 = {
"request": "scheduler.workers.update",
"args": ("worker01", None, "ACTIVE", None),
"ret": None,
}
self.scheduler_workers_set_config_worker01 = {
"request": "scheduler.workers.set_config",
"args": ("worker01", "local config content"),
"ret": True,
}
self.scheduler_workers_set_env_worker01 = {
"request": "scheduler.workers.set_env",
"args": ("worker01", "local env content"),
"ret": True,
}
self.scheduler_workers_set_env_dut_worker01 = {
"request": "scheduler.workers.set_env_dut",
"args": ("worker01", "local env-dut content"),
"ret": True,
}
self.scheduler_devices_add_qemu_03 = {
"request": "scheduler.devices.add",
"args": (
"qemu-03",
"qemu",
"worker01",
None,
None,
None,
None,
"qemu03",
),
"ret": None,
}
self.scheduler_devices_delete_qemu_02 = {
"request": "scheduler.devices.delete",
"args": ("qemu-02",),
"ret": None,
}
self.scheduler_devices_update_qemu_01 = {
"request": "scheduler.devices.update",
"args": (
"qemu-01",
"worker02",
None,
None,
None,
None,
"qemu01",
"qemu-aarch64",
),
"ret": None,
}
self.scheduler_devices_retire_qemu_01 = {
"request": "scheduler.devices.update",
"args": (
"qemu-01",
None,
None,
None,
None,
"RETIRED",
None,
None,
),
"ret": None,
}
self.scheduler_devices_unretire_qemu_01 = {
"request": "scheduler.devices.update",
"args": (
"qemu-01",
None,
None,
None,
None,
"UNKNOWN",
None,
None,
),
"ret": None,
}
self.scheduler_devices_set_dictionary_docker_01 = {
"request": "scheduler.devices.set_dictionary",
"args": ("docker-01", "new_yaml_dict"),
"ret": False,
}
self.scheduler_devices_tags_add_docker_01 = {
"request": "scheduler.devices.tags.add",
"args": ("docker-01", "worker01"),
"ret": None,
}
self.scheduler_devices_tags_delete_docker_01 = {
"request": "scheduler.devices.tags.delete",
"args": ("docker-01", "docker-01"),
"ret": None,
}
self.scheduler_devices_perms_add_docker_01 = {
"request": "scheduler.devices.perms_add",
"args": ("docker-01", "group1", "view_devicetype"),
"ret": None,
}
self.scheduler_devices_perms_delete_docker_01 = {
"request": "scheduler.devices.perms_delete",
"args": ("docker-01", "group1", "change_devicetype"),
"ret": None,
}
return PostData()
@pytest.fixture
def config_file(tmp_path):
return tmp_path / "lab.yaml"
@pytest.fixture
def config_dir(tmp_path):
return tmp_path / "lab"
@pytest.fixture
def config_def():
return """device_types:
docker:
permissions:
- name: change_devicetype
group: group1
qemu:
devices:
docker-01:
device_type: docker
worker: worker01
description: Created automatically by LAVA.
tags:
- docker-01
- worker
permissions:
- name: change_devicetype
group: group1
docker-02:
device_type: docker
worker: worker02
description: Created automatically by LAVA.
tags:
- docker-02
- docker-worker
qemu-01:
device_type: qemu
worker: worker01
description: Created automatically by LAVA.
qemu-02:
device_type: qemu
worker: worker02
description: Created automatically by LAVA.
groups:
group1:
permissions:
- auth.user.add_user
group2:
permissions:
- auth.user.delete_user
users:
user1:
groups:
- group1
permissions:
- lava_scheduler_app.device.add_device
user2:
groups:
- group2
permissions:
- lava_scheduler_app.device.delete_device
workers:
worker01:
worker02:
"""
def test_lab_import_empty(setup, monkeypatch, capsys, config_file, mock_get):
monkeypatch.setattr(sys, "argv", ["lavacli", "lab", "import", str(config_file)])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list_empty,
mock_get.auth_users_list_empty,
mock_get.scheduler_device_types_list_empty,
mock_get.scheduler_workers_list_empty,
mock_get.scheduler_devices_list_empty,
],
)
expected_def = """device_types: {}
devices: {}
groups: {}
users: {}
workers: {}
"""
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_file.exists()
yaml = ruamel.yaml.YAML(typ="safe")
assert yaml.load(config_file.read_text()) == yaml.load(expected_def)
def test_lab_import_groups_users_unsupported(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(sys, "argv", ["lavacli", "lab", "import", str(config_file)])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_2,
mock_get.scheduler_device_types_list_empty,
mock_get.scheduler_workers_list_empty_2023_2,
mock_get.scheduler_devices_list_empty,
],
)
expected_def = """device_types: {}
devices: {}
groups: {}
users: {}
workers: {}
"""
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_file.exists()
yaml = ruamel.yaml.YAML(typ="safe")
assert yaml.load(config_file.read_text()) == yaml.load(expected_def)
def test_lab_import_config_file(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(sys, "argv", ["lavacli", "lab", "import", str(config_file)])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_file.exists()
yaml = ruamel.yaml.YAML(typ="safe")
assert yaml.load(config_file.read_text()) == yaml.load(config_def)
config_dir = config_file.parent / config_file.name.split(".")[0]
assert (config_dir / "devices/docker-01.jinja2").exists()
assert (config_dir / "devices/docker-02.jinja2").exists()
assert (config_dir / "devices/qemu-01.jinja2").exists()
assert (config_dir / "devices/qemu-02.jinja2").exists()
assert not (config_dir / "device-types/docker.jinja2").exists()
assert not (config_dir / "device-types/qemu.jinja2").exists()
assert (config_dir / "health-checks/docker.yaml").exists()
assert (config_dir / "health-checks/qemu.yaml").exists()
config = ConfigFile(config_file)
assert config.is_yaml_file()
assert not config.is_dir()
assert config.load() == safe_yaml.load(config_def)
def test_lab_import_config_dir(
setup, monkeypatch, capsys, config_dir, config_def, mock_get
):
monkeypatch.setattr(sys, "argv", ["lavacli", "lab", "import", str(config_dir)])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_dir.exists()
assert (config_dir / "device-types.yaml").exists()
assert (config_dir / "devices.yaml").exists()
assert (config_dir / "groups.yaml").exists()
assert (config_dir / "users.yaml").exists()
assert (config_dir / "workers.yaml").exists()
config = ConfigFile(config_dir)
assert config.is_dir()
assert not config.is_yaml_file()
assert config.load() == safe_yaml.load(config_def)
def test_lab_import_config_file_exclude_groups(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--exclude", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "groups" not in config
assert "groups" not in config["users"]["user1"]
assert config["device_types"]["docker"] is None
assert "permissions" not in config["devices"]["docker-01"]
def test_lab_import_config_file_exclude_users(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--exclude", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "users" not in config
def test_lab_import_config_file_exclude_permissions(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--exclude", "permissions", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert config["groups"]["group1"] is None
assert "permissions" not in config["users"]["user1"]
assert config["device_types"]["docker"] is None
assert "permissions" not in config["devices"]["docker-01"]
def test_lab_import_config_dir_exclude_groups(
setup, monkeypatch, capsys, config_dir, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--exclude", "groups", str(config_dir)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_dir).load()
assert "groups" not in config
assert "groups" not in config["users"]["user1"]
assert config["device_types"]["docker"] is None
assert "permissions" not in config["devices"]["docker-01"]
def test_lab_import_config_dir_exclude_users(
setup, monkeypatch, capsys, config_dir, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--exclude", "users", str(config_dir)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_dir).load()
assert "users" not in config
def test_lab_import_config_dir_exclude_permissions(
setup, monkeypatch, capsys, config_dir, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--exclude", "permissions", str(config_dir)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_dir).load()
assert config["groups"]["group1"] is None
assert "permissions" not in config["users"]["user1"]
assert config["device_types"]["docker"] is None
assert "permissions" not in config["devices"]["docker-01"]
def test_lab_import_custom_template(setup, monkeypatch, capsys, config_file, mock_get):
monkeypatch.setattr(sys, "argv", ["lavacli", "lab", "import", str(config_file)])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list_empty,
mock_get.auth_users_list_empty,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker_custom_template,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_get_template_docker,
mock_get.scheduler_device_types_show_qemu_custom_template,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_device_types_get_template_qemu,
mock_get.scheduler_workers_list_empty,
mock_get.scheduler_devices_list_empty,
],
)
expected_def = """device_types:
docker:
permissions:
- name: change_devicetype
group: group1
qemu:
devices: {}
groups: {}
users: {}
workers: {}
"""
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_file.exists()
yaml = ruamel.yaml.YAML(typ="safe")
assert yaml.load(config_file.read_text()) == yaml.load(expected_def)
config_dir = config_file.parent / config_file.name.split(".")[0]
assert (config_dir / "device-types/docker.jinja2").exists()
assert (config_dir / "device-types/qemu.jinja2").exists()
def test_lab_import_devices_dependency_error(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--resources", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
],
)
assert main() == 1
assert (
capsys.readouterr()[1]
== "'--resources devices' needs '--resources device-types --resources workers --resources groups'\n"
)
def test_lab_import_device_types_dependency_error(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--resources", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
],
)
assert main() == 1
assert (
capsys.readouterr()[1]
== "'--resources device-types' needs '--resources groups'\n"
)
def test_lab_import_users_dependency_error(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--resources", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
],
)
assert main() == 1
assert capsys.readouterr()[1] == "'--resources users' needs '--resources groups'\n"
def test_lab_import_config_file_groups(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--resources", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "groups" in config
assert "users" not in config
assert "devices" not in config
assert "device_types" not in config
assert "workers" not in config
def test_lab_import_config_file_users(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"users",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "users" in config
assert "groups" in config
assert "devices" not in config
assert "device_types" not in config
assert "workers" not in config
def test_lab_import_config_file_devices(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"devices",
"--resources",
"device-types",
"--resources",
"groups",
"--resources",
"workers",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "devices" in config
assert "device_types" in config
assert "workers" in config
assert "groups" in config
assert "users" not in config
def test_lab_import_config_file_device_types(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"device-types",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "device_types" in config
assert "groups" in config
assert "workers" not in config
assert "users" not in config
assert "devices" not in config
def test_lab_import_config_file_workers(
setup, monkeypatch, capsys, config_file, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"workers",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
config = ConfigFile(config_file).load()
assert "workers" in config
assert "users" not in config
assert "groups" not in config
assert "devices" not in config
assert "device_types" not in config
def test_lab_import_config_dir_groups(setup, monkeypatch, capsys, config_dir, mock_get):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "import", "--resources", "groups", str(config_dir)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_dir.exists()
assert not (config_dir / "device-types.yaml").exists()
assert not (config_dir / "devices.yaml").exists()
assert (config_dir / "groups.yaml").exists()
assert not (config_dir / "users.yaml").exists()
assert not (config_dir / "workers.yaml").exists()
def test_lab_import_config_dir_users(setup, monkeypatch, capsys, config_dir, mock_get):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"users",
"--resources",
"groups",
str(config_dir),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_dir.exists()
assert not (config_dir / "device-types.yaml").exists()
assert not (config_dir / "devices.yaml").exists()
assert (config_dir / "groups.yaml").exists()
assert (config_dir / "users.yaml").exists()
assert not (config_dir / "workers.yaml").exists()
def test_lab_import_config_dir_devices(
setup, monkeypatch, capsys, config_dir, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"devices",
"--resources",
"device-types",
"--resources",
"groups",
"--resources",
"workers",
str(config_dir),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_dir.exists()
assert (config_dir / "device-types.yaml").exists()
assert (config_dir / "devices.yaml").exists()
assert (config_dir / "groups.yaml").exists()
assert not (config_dir / "users.yaml").exists()
assert (config_dir / "workers.yaml").exists()
def test_lab_import_config_dir_device_types(
setup, monkeypatch, capsys, config_dir, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"device-types",
"--resources",
"groups",
str(config_dir),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_dir.exists()
assert (config_dir / "device-types.yaml").exists()
assert not (config_dir / "devices.yaml").exists()
assert (config_dir / "groups.yaml").exists()
assert not (config_dir / "users.yaml").exists()
assert not (config_dir / "workers.yaml").exists()
def test_lab_import_config_dir_workers(
setup, monkeypatch, capsys, config_dir, mock_get
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"import",
"--resources",
"workers",
str(config_dir),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
assert main() == 0
assert capsys.readouterr()[1] == ""
assert config_dir.exists()
assert not (config_dir / "device-types.yaml").exists()
assert not (config_dir / "devices.yaml").exists()
assert not (config_dir / "groups.yaml").exists()
assert not (config_dir / "users.yaml").exists()
assert (config_dir / "workers.yaml").exists()
def test_lab_apply_groups_unsupported(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_2,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_groups_no_change(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_groups_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_post.auth_groups_add_group3,
mock_get.auth_groups_show_group3,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["groups"]["group3"] = {"permissions": ["auth.group.add_group"]}
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n \x1b[33m* group3\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_groups_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"groups",
"--delete",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_post.auth_groups_delete_group2,
],
)
data = safe_yaml.load(config_def)
del data["groups"]["group2"]
del data["users"]["user2"]["groups"]
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[91m* group2\x1b[0m\n" in out
assert err == ""
def test_lab_apply_groups_perms_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_post.auth_groups_perms_add_group1,
mock_get.auth_groups_show_group2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["groups"]["group1"]["permissions"].append("auth.user.delete_user")
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[33m-> permissions\x1b[0m\n \x1b[32m+ auth.user.delete_user\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_groups_perms_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "groups", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_post.auth_groups_perms_delete_group1,
mock_get.auth_groups_show_group2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["groups"]["group1"]["permissions"].pop()
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[33m-> permissions\x1b[0m\n \x1b[91m- auth.user.add_user\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_unsupported(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_2,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_no_change(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[32m* user2\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_post.auth_users_add_user3,
mock_get.auth_users_show_user3,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user3"] = {"groups": ["group3"], "permissions": []}
data["groups"]["group3"] = None
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[32m* user2\x1b[0m\n \x1b[33m* user3\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_add_ldap(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_post.auth_users_add_user3_ldap,
mock_get.auth_users_show_user3_ldap,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user3"] = {"ldap": True, "groups": ["group3"], "permissions": []}
data["groups"]["group3"] = None
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[32m* user2\x1b[0m\n \x1b[33m* user3\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"users",
"--delete",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_post.auth_users_delete_user2,
],
)
data = safe_yaml.load(config_def)
del data["users"]["user2"]
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[91m* user2\x1b[0m\n" in out
assert err == ""
def test_lab_apply_users_update(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_get.auth_users_show_user2,
mock_post.auth_users_update_user2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user2"]["first_name"] = "first"
data["users"]["user2"]["last_name"] = "last"
data["users"]["user2"]["email"] = "user2@email.io"
data["users"]["user2"]["is_active"] = False
data["users"]["user2"]["is_staff"] = True
data["users"]["user2"]["is_superuser"] = True
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[32m* user2\x1b[0m\n \x1b[33m-> last_name: '' => 'last'\x1b[0m\n \x1b[33m-> first_name: '' => 'first'\x1b[0m\n \x1b[33m-> email: '' => 'user2@email.io'\x1b[0m\n \x1b[33m-> is_superuser: 'False' => 'True'\x1b[0m\n \x1b[33m-> is_staff: 'False' => 'True'\x1b[0m\n \x1b[33m-> is_active: 'True' => 'False'\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_groups_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_post.auth_users_groups_add_user1_group2,
mock_get.auth_users_show_user2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user1"]["groups"].append("group2")
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[33m-> groups\x1b[0m\n \x1b[32m+ group2\x1b[0m\n \x1b[32m* user2\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_groups_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_post.auth_users_groups_delete_user1_group1,
mock_get.auth_users_show_user2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user1"]["groups"].pop()
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[33m-> groups\x1b[0m\n \x1b[91m- group1\x1b[0m\n \x1b[32m* user2\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_perms_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_post.auth_users_perms_add_user1,
mock_get.auth_users_show_user2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user1"]["permissions"].append(
"lava_scheduler_app.device.delete_device"
)
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[33m-> permissions\x1b[0m\n \x1b[32m+ lava_scheduler_app.device.delete_device\x1b[0m\n \x1b[32m* user2\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_users_perms_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "users", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_users_list,
mock_get.auth_users_show_user1,
mock_post.auth_users_perms_delete_user1,
mock_get.auth_users_show_user2,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["users"]["user1"]["permissions"].pop()
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[32m* user1\x1b[0m\n \x1b[33m-> permissions\x1b[0m\n \x1b[91m- lava_scheduler_app.device.add_device\x1b[0m\n \x1b[32m* user2\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
@pytest.fixture
def dt_hc(config_file):
config_dir = config_file.parent / config_file.name.split(".")[0]
hc_dir = config_dir / "health-checks"
hc_dir.mkdir(parents=True, exist_ok=True)
(hc_dir / "bbb.yaml").write_text("hc-definition", encoding="utf-8")
(hc_dir / "docker.yaml").write_text("hc-definition", encoding="utf-8")
(hc_dir / "qemu.yaml").write_text("hc-definition", encoding="utf-8")
def test_lab_apply_dt_no_change(
setup, monkeypatch, capsys, config_file, config_def, mock_get, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_post.scheduler_device_types_add_bbb,
mock_get.scheduler_device_types_show_bbb,
mock_get.scheduler_device_types_get_health_check_bbb,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["device_types"]["bbb"] = {}
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m* bbb\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_hide(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"device-types",
"--delete",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_post.scheduler_device_types_hide_qemu,
],
)
data = safe_yaml.load(config_def)
del data["device_types"]["qemu"]
# delete devices need the device type.
del data["devices"]["qemu-01"]
del data["devices"]["qemu-02"]
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[91m* qemu\x1b[0m\n" in out
assert err == ""
def test_lab_apply_dt_update(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_post.scheduler_device_types_update_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["device_types"]["docker"] is None:
data["device_types"]["docker"] = {}
data["device_types"]["docker"]["description"] = "new"
data["device_types"]["docker"]["display"] = False
data["device_types"]["docker"]["health_frequency"] = 12
data["device_types"]["docker"]["health_denominator"] = "jobs"
data["device_types"]["docker"]["health_disabled"] = True
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[33m-> description: '' => 'new'\x1b[0m\n \x1b[33m-> health_disabled: 'False' => 'True'\x1b[0m\n \x1b[33m-> health_denominator: 'hours' => 'jobs'\x1b[0m\n \x1b[33m-> health_frequency: '24' => '12'\x1b[0m\n \x1b[33m-> display: 'True' => 'False'\x1b[0m\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_set_hc_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker_empty,
mock_post.scheduler_device_types_set_health_check_docker_add,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
config_file.write_text(config_def, encoding="utf-8")
assert main() == 0
out, err = capsys.readouterr()
diff = " \x1b[32m* docker\x1b[0m\n \x1b[33m-> health-check\x1b[0m\n | @@ -0,0 +1 @@\n | +hc-definition\n"
assert diff in out
assert err == ""
def test_lab_apply_dt_set_hc_del(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_post.scheduler_device_types_set_health_check_docker_del,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
config_file.write_text(config_def, encoding="utf-8")
config_dir = config_file.parent / config_file.name.split(".")[0]
hc_path = config_dir / "health-checks" / "docker.yaml"
hc_path.unlink()
assert main() == 0
out, err = capsys.readouterr()
diff = " \x1b[32m* docker\x1b[0m\n \x1b[33m-> health-check\x1b[0m\n | @@ -1 +0,0 @@\n | -hc-definition\n"
assert diff in out
assert err == ""
def test_lab_apply_dt_set_hc_update(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_post.scheduler_device_types_set_health_check_docker_update,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
config_file.write_text(config_def, encoding="utf-8")
config_dir = config_file.parent / config_file.name.split(".")[0]
hc_path = config_dir / "health-checks" / "docker.yaml"
hc_path.write_text("new-hc-definition", encoding="utf-8")
assert main() == 0
out, err = capsys.readouterr()
diff = " \x1b[32m* docker\x1b[0m\n \x1b[33m-> health-check\x1b[0m\n | @@ -1 +1 @@\n | -hc-definition\n | +new-hc-definition\n"
assert diff in out
assert err == ""
def test_lab_apply_dt_set_template(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker_custom_template,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_get_template_docker,
mock_post.scheduler_device_types_set_template_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
config_dir = config_file.parent / config_file.name.split(".")[0]
hc_dir = config_dir / "device-types"
hc_dir.mkdir(parents=True, exist_ok=True)
(hc_dir / "docker.jinja2").write_text("new template definition", encoding="utf-8")
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[33m-> template\x1b[0m\n | @@ -1 +1 @@\n | -template content\n | +new template definition\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_perms_add_groups_missing(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["device_types"]["docker"] is None:
data["device_types"]["docker"] = {}
data["device_types"]["docker"]["permissions"].append(
{"name": "view_devicetype", "group": "group1"}
)
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = """\x1b[36m> groups\x1b[0m
\x1b[33m-> SKIP\x1b[0m
\x1b[36m> users\x1b[0m
\x1b[33m-> SKIP\x1b[0m
\x1b[36m> device-types\x1b[0m
\x1b[32m* docker\x1b[0m
\x1b[33m-> SKIP permissions\x1b[0m
\x1b[32m* qemu\x1b[0m
\x1b[36m> workers\x1b[0m
\x1b[33m-> SKIP\x1b[0m
\x1b[36m> devices\x1b[0m
\x1b[33m-> SKIP\x1b[0m
"""
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_perms_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"device-types",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_post.scheduler_device_types_perms_add_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["device_types"]["docker"] is None:
data["device_types"]["docker"] = {}
data["device_types"]["docker"]["permissions"].append(
{"name": "view_devicetype", "group": "group1"}
)
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = """\x1b[36m> groups\x1b[0m
\x1b[32m* group1\x1b[0m
\x1b[32m* group2\x1b[0m
\x1b[36m> users\x1b[0m
\x1b[33m-> SKIP\x1b[0m
\x1b[36m> device-types\x1b[0m
\x1b[32m* docker\x1b[0m
\x1b[33m-> permission group\x1b[0m
\x1b[32m+ view_devicetype group1\x1b[0m
\x1b[32m* qemu\x1b[0m
\x1b[36m> workers\x1b[0m
\x1b[33m-> SKIP\x1b[0m
\x1b[36m> devices\x1b[0m
\x1b[33m-> SKIP\x1b[0m
"""
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_perms_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"device-types",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_post.scheduler_device_types_perms_delete_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["device_types"]["docker"] is None:
data["device_types"]["docker"] = {}
del data["device_types"]["docker"]["permissions"]
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[33m-> permission group\x1b[0m\n \x1b[91m- change_devicetype group1\x1b[0m\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_perms_update(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"device-types",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_post.scheduler_device_types_perms_add_docker,
mock_post.scheduler_device_types_perms_delete_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["device_types"]["docker"] is None:
data["device_types"]["docker"] = {}
data["device_types"]["docker"]["permissions"] = [
{"name": "view_devicetype", "group": "group1"},
]
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[33m-> permission group\x1b[0m\n \x1b[32m+ view_devicetype group1\x1b[0m\n \x1b[91m- change_devicetype group1\x1b[0m\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_dt_perms_unsupported(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post, dt_hc
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "device-types", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_2,
mock_get.scheduler_device_types_list,
mock_get.scheduler_device_types_show_docker,
mock_get.scheduler_device_types_get_health_check_docker,
mock_get.scheduler_device_types_show_qemu,
mock_get.scheduler_device_types_get_health_check_qemu,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["device_types"]["docker"] is None:
data["device_types"]["docker"] = {}
data["device_types"]["docker"]["permissions"] = [
{"name": "view_devicetype", "group": "group1"},
]
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[32m* docker\x1b[0m\n \x1b[32m* qemu\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_workers_no_change(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
def test_lab_apply_workers_list_2023_2(
setup, monkeypatch, capsys, config_file, config_def, mock_get
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_2,
mock_get.scheduler_workers_list_all_2023_2,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[32m* worker01\x1b[0m\n \x1b[32m* worker02\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_workers_add(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_get.scheduler_workers_show_worker02,
mock_post.scheduler_workers_add_worker03,
mock_get.scheduler_workers_show_worker03,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["workers"]["worker03"] = {}
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[32m* worker01\x1b[0m\n \x1b[32m* worker02\x1b[0m\n \x1b[33m* worker03\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_workers_delete(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"workers",
"--delete",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_05,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_post.scheduler_workers_delete_worker02,
],
)
data = safe_yaml.load(config_def)
del data["workers"]["worker02"]
# delete devices need the worker.
del data["devices"]["docker-02"]
del data["devices"]["qemu-02"]
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[91m* worker02\x1b[0m\n" in out
assert err == ""
def test_lab_apply_workers_update(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_post.scheduler_workers_update_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["workers"]["worker01"] is None:
data["workers"]["worker01"] = {}
data["workers"]["worker01"]["description"] = "new"
data["workers"]["worker01"]["job_limit"] = 10
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[32m* worker01\x1b[0m\n \x1b[33m-> description: '' => 'new'\x1b[0m\n \x1b[33m-> job_limit: '0' => '10'\x1b[0m\n \x1b[32m* worker02\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_workers_retire(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01,
mock_post.scheduler_workers_retire_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
data = safe_yaml.load(config_def)
if data["workers"]["worker01"] is None:
data["workers"]["worker01"] = {}
data["workers"]["worker01"]["retire"] = True
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[33m-> health: 'ACTIVE' => 'RETIRED'\x1b[0m\n" in out
assert err == ""
def test_lab_apply_workers_unretire(
setup, monkeypatch, capsys, config_file, config_def, mock_get, mock_post
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_retired_worker01,
mock_post.scheduler_workers_unretire_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
data = safe_yaml.load(config_def)
if data["workers"]["worker01"] is None:
data["workers"]["worker01"] = {}
data["workers"]["worker01"]["retire"] = False
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[33m-> health: 'RETIRED' => 'ACTIVE'\x1b[0m\n" in out
assert err == ""
@pytest.fixture
def worker_config(config_file):
config_dir = config_file.parent / config_file.name.split(".")[0]
worker_dir = config_dir / "workers/worker01"
worker_dir.mkdir(parents=True, exist_ok=True)
return worker_dir
def test_lab_apply_workers_set_config(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
worker_config,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01_custom_config,
mock_get.scheduler_workers_get_config_worker01,
mock_post.scheduler_workers_set_config_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
config_file.write_text(config_def, encoding="utf-8")
(worker_config / "dispatcher.yaml").write_text(
"local config content", encoding="utf-8"
)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[32m* worker01\x1b[0m\n \x1b[33m-> config\x1b[0m\n | @@ -1 +1 @@\n | -config content\n | +local config content\n \x1b[32m* worker02\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_workers_env_update(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
worker_config,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01_custom_env,
mock_get.scheduler_workers_get_env_worker01,
mock_post.scheduler_workers_set_env_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
config_file.write_text(config_def, encoding="utf-8")
(worker_config / "env.yaml").write_text("local env content", encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[32m* worker01\x1b[0m\n \x1b[33m-> env\x1b[0m\n | @@ -1 +1 @@\n | -env content\n | +local env content\n \x1b[32m* worker02\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_workers_set_env_dut(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
worker_config,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "workers", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_workers_list_all,
mock_get.scheduler_workers_show_worker01_custom_env_dut,
mock_get.scheduler_workers_get_env_dut_worker01,
mock_post.scheduler_workers_set_env_dut_worker01,
mock_get.scheduler_workers_show_worker02,
],
)
config_file.write_text(config_def, encoding="utf-8")
(worker_config / "env-dut.yaml").write_text(
"local env-dut content", encoding="utf-8"
)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[32m* worker01\x1b[0m\n \x1b[33m-> env-dut\x1b[0m\n | @@ -1 +1 @@\n | -env-dut content\n | +local env-dut content\n \x1b[32m* worker02\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
@pytest.fixture
def device_dict(config_file):
config_dir = config_file.parent / config_file.name.split(".")[0]
device_dir = config_dir / "devices"
device_dir.mkdir(parents=True, exist_ok=True)
(device_dir / "docker-01.jinja2").write_text("yaml_dict", encoding="utf-8")
(device_dir / "docker-02.jinja2").write_text("yaml_dict", encoding="utf-8")
(device_dir / "qemu-01.jinja2").write_text("yaml_dict", encoding="utf-8")
(device_dir / "qemu-02.jinja2").write_text("yaml_dict", encoding="utf-8")
(device_dir / "qemu-03.jinja2").write_text("yaml_dict", encoding="utf-8")
def test_lab_apply_devices_no_change(
setup, monkeypatch, capsys, config_file, config_def, mock_get, device_dict
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
config_file.write_text(config_def, encoding="utf-8")
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_add(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
mock_post.scheduler_devices_add_qemu_03,
mock_get.scheduler_devices_show_qemu_03,
mock_get.scheduler_devices_get_dictionary_qemu_03,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["devices"]["qemu-03"] = {
"device_type": "qemu",
"worker": "worker01",
"description": "qemu03",
}
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n \x1b[33m* qemu-03\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_delete(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"devices",
"--delete",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_05,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_post.scheduler_devices_delete_qemu_02,
],
)
data = safe_yaml.load(config_def)
del data["devices"]["qemu-02"]
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[91m* qemu-02\x1b[0m\n" in out
assert err == ""
def test_lab_apply_devices_update(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_post.scheduler_devices_update_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["devices"]["qemu-01"] = {
"device_type": "qemu-aarch64",
"worker": "worker02",
"description": "qemu01",
}
data["device_types"]["qemu-aarch64"] = None
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[33m-> device_type: 'qemu' => 'qemu-aarch64'\x1b[0m\n \x1b[33m-> worker: 'worker01' => 'worker02'\x1b[0m\n \x1b[33m-> description: 'Created automatically by LAVA.' => 'qemu01'\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_retire(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_post.scheduler_devices_retire_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
data = safe_yaml.load(config_def)
data["devices"]["qemu-01"]["retire"] = True
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[33m-> health: 'GOOD' => 'RETIRED'\x1b[0m\n" in out
assert err == ""
def test_lab_apply_devices_unretire(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_retired_qemu_01,
mock_post.scheduler_devices_unretire_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
data = safe_yaml.load(config_def)
data["devices"]["qemu-01"]["retire"] = False
with open(config_file, "w") as f:
safe_yaml.dump(data, f)
assert main() == 0
out, err = capsys.readouterr()
assert " \x1b[33m-> health: 'RETIRED' => 'UNKNOWN'\x1b[0m\n" in out
assert err == ""
def test_lab_apply_devices_set_dictionary(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_post.scheduler_devices_set_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
config_file.write_text(config_def, encoding="utf-8")
config_dir = config_file.parent / config_file.name.split(".")[0]
(config_dir / "devices/docker-01.jinja2").write_text(
"new_yaml_dict", encoding="utf-8"
)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[33m-> dictionary\x1b[0m\n | @@ -1 +1 @@\n | -yaml_dict\n | +new_yaml_dict\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_tags_add(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_post.scheduler_devices_tags_add_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
mock_get.scheduler_devices_show_qemu_03,
mock_get.scheduler_devices_get_dictionary_qemu_03,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["devices"]["docker-01"]["tags"].append("worker01")
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[33m-> tags\x1b[0m\n \x1b[32m+ worker01\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_tags_delete(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_post.scheduler_devices_tags_delete_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
mock_get.scheduler_devices_show_qemu_03,
mock_get.scheduler_devices_get_dictionary_qemu_03,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
data["devices"]["docker-01"]["tags"].remove("docker-01")
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[33m-> tags\x1b[0m\n \x1b[91m- docker-01\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_perms_add(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"devices",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_post.scheduler_devices_perms_add_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["devices"]["docker-01"] is None:
data["devices"]["docker-01"] = {}
data["devices"]["docker-01"]["permissions"].append(
{"name": "view_devicetype", "group": "group1"}
)
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[33m-> permission group\x1b[0m\n \x1b[32m+ view_devicetype group1\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_perms_delete(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"devices",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_post.scheduler_devices_perms_delete_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["devices"]["docker-01"] is None:
data["devices"]["docker-01"] = {}
del data["devices"]["docker-01"]["permissions"]
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[33m-> permission group\x1b[0m\n \x1b[91m- change_devicetype group1\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_perms_update(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"lab",
"apply",
"--resource",
"devices",
"--resources",
"groups",
str(config_file),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_3,
mock_get.auth_groups_list,
mock_get.auth_groups_show_group1,
mock_get.auth_groups_show_group2,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_post.scheduler_devices_perms_add_docker_01,
mock_post.scheduler_devices_perms_delete_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["devices"]["docker-01"] is None:
data["devices"]["docker-01"] = {}
data["devices"]["docker-01"]["permissions"] = [
{"name": "view_devicetype", "group": "group1"},
]
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[32m* group1\x1b[0m\n \x1b[32m* group2\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[33m-> permission group\x1b[0m\n \x1b[32m+ view_devicetype group1\x1b[0m\n \x1b[91m- change_devicetype group1\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
def test_lab_apply_devices_perms_unsupported(
setup,
monkeypatch,
capsys,
config_file,
config_def,
mock_get,
mock_post,
device_dict,
):
monkeypatch.setattr(
sys,
"argv",
["lavacli", "lab", "apply", "--resource", "devices", str(config_file)],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
mock_get.system_version_2023_2,
mock_get.scheduler_devices_list,
mock_get.scheduler_devices_show_docker_01,
mock_get.scheduler_devices_get_dictionary_docker_01,
mock_get.scheduler_devices_show_docker_02,
mock_get.scheduler_devices_get_dictionary_docker_02,
mock_get.scheduler_devices_show_qemu_01,
mock_get.scheduler_devices_get_dictionary_qemu_01,
mock_get.scheduler_devices_show_qemu_02,
mock_get.scheduler_devices_get_dictionary_qemu_02,
],
)
yaml = ruamel.yaml.YAML(typ="safe")
data = yaml.load(config_def)
if data["devices"]["docker-01"] is None:
data["devices"]["docker-01"] = {}
data["devices"]["docker-01"]["permissions"] = [
{"name": "view_devicetype", "group": "group1"},
]
with open(config_file, "w") as f:
yaml.dump(data, f)
expected_out = "\x1b[36m> groups\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> users\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> device-types\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> workers\x1b[0m\n \x1b[33m-> SKIP\x1b[0m\n\x1b[36m> devices\x1b[0m\n \x1b[32m* docker-01\x1b[0m\n \x1b[32m* docker-02\x1b[0m\n \x1b[32m* qemu-01\x1b[0m\n \x1b[32m* qemu-02\x1b[0m\n"
assert main() == 0
out, err = capsys.readouterr()
assert out == expected_out
assert err == ""
class TestConfigFile:
def test_filepath_setter(self, tmp_path):
with pytest.raises(ValueError) as exc:
_config = ConfigFile("path_str")
assert str(exc.value) == "filepath must be a pathlib.Path object!"
def test_is_dir(self, tmp_path):
config = ConfigFile(tmp_path / "lab")
assert config.is_dir()
def test_is_yaml_file(self, tmp_path):
config = ConfigFile(tmp_path / "lab.yaml")
assert config.is_yaml_file()
def test_base_dir(self, tmp_path):
"""
Test 'lab.yaml/../lab' is resolved to 'lab'. If not, 'lab.yaml'
will be created as an parent dir of 'lab' which leads to file
writing error.
"""
config = ConfigFile(tmp_path / "lab.yaml")
assert str(config.base_dir) == str(config.filepath.with_suffix(""))
lavacli-2.8/tests/test_lavacli.py 0000664 0000000 0000000 00000003117 15172666047 0017204 0 ustar 00root root 0000000 0000000 # 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
from lavacli import main
from lavacli.__about__ import __version__
def test_lavacli_version(setup, monkeypatch, capsys):
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):
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):
monkeypatch.setattr(sys, "argv", ["lavacli", "-i", "bla", "devices", "list"])
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Unknown identity 'bla'\n" # nosec
lavacli-2.8/tests/test_results.py 0000664 0000000 0000000 00000026543 15172666047 0017302 0 ustar 00root root 0000000 0000000 # 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_results_job(setup, monkeypatch, capsys):
version = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"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 = "2019.1"
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": """[{"suite": "lava", "name": "validate", "result": "pass"}]""",
},
],
)
assert main() == 0 # nosec
assert ( # nosec
capsys.readouterr()[0] == "- {name: validate, result: pass, suite: lava}\n"
)
lavacli-2.8/tests/test_schemas.py 0000664 0000000 0000000 00000005754 15172666047 0017225 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2022-present Linaro
# 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
from voluptuous import MultipleInvalid, Schema
from lavacli import schemas
from lavacli.utils import safe_yaml
def test_user_group_must_exist():
config = """groups:
group1:
users:
user1:
groups:
- group2
"""
schema = Schema(schemas.user_group_must_exist)
with pytest.raises(MultipleInvalid) as exc:
schema(safe_yaml.load(config))
assert exc.value.msg == "Group must exist"
assert exc.value.path == ["users", "user1", "groups", "group2"]
def test_device_dt_must_exist():
config = """device_types:
qemu:
devices:
docker-01:
device_type: docker
"""
schema = Schema(schemas.device_dt_must_exist)
with pytest.raises(MultipleInvalid) as exc:
schema(safe_yaml.load(config))
assert exc.value.msg == "Device type must exist"
assert exc.value.path == ["devices", "docker-01", "device_type", "docker"]
def test_device_worker_must_exist():
config = """device_types:
qemu:
devices:
docker-01:
worker: worker01
workers:
worker02:
"""
schema = Schema(schemas.device_worker_must_exist)
with pytest.raises(MultipleInvalid) as exc:
schema(safe_yaml.load(config))
assert exc.value.msg == "Worker must exist"
assert exc.value.path == ["devices", "docker-01", "worker", "worker01"]
def test_device_perms_group_must_exist():
config = """devices:
docker-01:
permissions:
- name: change_device
group: group2
groups:
group1:
"""
schema = Schema(schemas.device_perms_group_must_exist)
with pytest.raises(MultipleInvalid) as exc:
schema(safe_yaml.load(config))
assert exc.value.msg == "Group must exist"
assert exc.value.path == [
"devices",
"docker-01",
"permissions",
{"name": "change_device", "group": "group2"},
]
def test_dt_perms_group_must_exist():
config = """device_types:
docker:
permissions:
- name: change_devicetype
group: group2
groups:
group1:
"""
schema = Schema(schemas.dt_perms_group_must_exist)
with pytest.raises(MultipleInvalid) as exc:
schema(safe_yaml.load(config))
assert exc.value.msg == "Group must exist"
assert exc.value.path == [
"devices_types",
"docker",
"permissions",
{"name": "change_devicetype", "group": "group2"},
]
lavacli-2.8/tests/test_system.py 0000664 0000000 0000000 00000062146 15172666047 0017124 0 ustar 00root root 0000000 0000000 # 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 = "2019.1"
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 = "2019.1"
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, tmp_path):
last_ping = xmlrpc.client.DateTime("20180128T01:01:01")
monkeypatch.setattr(
sys, "argv", ["lavacli", "system", "export", str(tmp_path / "export")]
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": "2019.1"},
{
"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(tmp_path / "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": "2019.1"},
{
"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": "2019.1"},
{
"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": "2019.1"},
{
"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": "2019.1"},
{
"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": "2019.1"},
{
"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": "2019.1"},
{
"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 = "2019.1"
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] == "2019.1\n" # nosec
def test_system_whoami(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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-2.8/tests/test_tags.py 0000664 0000000 0000000 00000014626 15172666047 0016536 0 ustar 00root root 0000000 0000000 # 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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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-2.8/tests/test_tokens.py 0000664 0000000 0000000 00000011125 15172666047 0017072 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2025-present Linaro Limited
# 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_tokens_add(setup, monkeypatch, capsys):
version = "2025.05"
monkeypatch.setattr(
sys, "argv", ["lavacli", "tokens", "add", "n1", "--token", "v1"]
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.remote_artifact_tokens.add",
"args": ("n1", "v1"),
"ret": None,
},
],
)
assert main() == 0
assert capsys.readouterr()[0] == ""
def test_tokens_delete(setup, monkeypatch, capsys):
version = "2025.05"
monkeypatch.setattr(sys, "argv", ["lavacli", "tokens", "delete", "n1"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.remote_artifact_tokens.delete",
"args": ("n1",),
"ret": None,
},
],
)
assert main() == 0
assert capsys.readouterr()[0] == ""
def test_tokens_list(setup, monkeypatch, capsys):
version = "2025.05"
monkeypatch.setattr(sys, "argv", ["lavacli", "tokens", "list"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.remote_artifact_tokens.list",
"args": (),
"ret": [
{"name": "n1", "token": "v1"},
{"name": "n2", "token": "v2"},
],
},
],
)
assert main() == 0
assert (
capsys.readouterr()[0]
== """tokens:
* n1: v1
* n2: v2
"""
)
def test_tokens_list_json(setup, monkeypatch, capsys):
version = "2025.05"
monkeypatch.setattr(sys, "argv", ["lavacli", "tokens", "list", "--json"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.remote_artifact_tokens.list",
"args": (),
"ret": [
{"name": "n1", "token": "v1"},
{"name": "n2", "token": "v2"},
],
},
],
)
assert main() == 0
assert json.loads(capsys.readouterr()[0]) == [
{"name": "n1", "token": "v1"},
{"name": "n2", "token": "v2"},
]
def test_tokens_list_yaml(setup, monkeypatch, capsys):
version = "2025.05"
monkeypatch.setattr(sys, "argv", ["lavacli", "tokens", "list", "--yaml"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.remote_artifact_tokens.list",
"args": (),
"ret": [
{"name": "n1", "token": "v1"},
{"name": "n2", "token": "v2"},
],
},
],
)
assert main() == 0
assert (
capsys.readouterr()[0]
== """- {name: n1, token: v1}
- {name: n2, token: v2}
"""
)
def test_tokens_show(setup, monkeypatch, capsys):
version = "2025.05"
monkeypatch.setattr(sys, "argv", ["lavacli", "tokens", "show", "n1"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.remote_artifact_tokens.show",
"args": ("n1",),
"ret": "v1",
},
],
)
assert main() == 0
assert capsys.readouterr()[0] == "v1\n"
lavacli-2.8/tests/test_users.py 0000664 0000000 0000000 00000012547 15172666047 0016741 0 ustar 00root root 0000000 0000000 # 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
def test_users_add_active_staff_superuser(setup, monkeypatch, capsys):
version = "2023.03"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"users",
"add",
"--staff",
"--superuser",
"user1",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "auth.users.add",
"args": ("user1", None, None, None, True, True, True, False),
"ret": None,
},
],
)
assert main() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_users_add_no_active(setup, monkeypatch, capsys):
version = "2023.03"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"users",
"add",
"--no-active",
"user1",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "auth.users.add",
"args": ("user1", None, None, None, False, False, False, False),
"ret": None,
},
],
)
assert main() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_users_add_ldap(setup, monkeypatch, capsys):
version = "2023.03"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"users",
"add",
"--ldap",
"user1",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "auth.users.add",
"args": ("user1", None, None, None, True, False, False, True),
"ret": None,
},
],
)
assert main() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_users_update_info(setup, monkeypatch, capsys):
version = "2023.03"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"users",
"update",
"--first-name",
"first",
"--last-name",
"last",
"--email",
"user1@email.io",
"user1",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "auth.users.update",
"args": ("user1", "first", "last", "user1@email.io", None, None, None),
"ret": None,
},
],
)
assert main() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_users_update_active_staff_superuser(setup, monkeypatch, capsys):
version = "2023.03"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"users",
"update",
"--active",
"--staff",
"--superuser",
"user1",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "auth.users.update",
"args": ("user1", None, None, None, True, True, True),
"ret": None,
},
],
)
assert main() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
def test_users_update_no_active_no_staff_no_superuser(setup, monkeypatch, capsys):
version = "2023.03"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"users",
"update",
"--no-active",
"--no-staff",
"--no-superuser",
"user1",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "auth.users.update",
"args": ("user1", None, None, None, False, False, False),
"ret": None,
},
],
)
assert main() == 0
out, err = capsys.readouterr()
assert out == ""
assert err == ""
lavacli-2.8/tests/test_workers.py 0000664 0000000 0000000 00000060470 15172666047 0017272 0 ustar 00root root 0000000 0000000 # 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
from lavacli import main
def test_workers_add(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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_delete(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"workers",
"config",
"delete",
"worker01",
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.set_config",
"args": ("worker01", ""),
"ret": True,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
def test_workers_config_get(setup, monkeypatch, capsys):
version = "2019.1"
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, tmp_path):
version = "2019.1"
with (tmp_path / "config.yaml").open("w") as f_conf:
f_conf.write("config content")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"workers",
"config",
"set",
"worker01",
str(tmp_path / "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, tmp_path):
version = "2019.1"
with (tmp_path / "config.yaml").open("w") as f_conf:
f_conf.write("config content")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"workers",
"config",
"set",
"worker01",
str(tmp_path / "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()[1] == "Unable to store worker configuration\n" # nosec
def test_workers_env_delete(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
monkeypatch.setattr(
sys,
"argv",
["lavacli", "workers", "env", "delete", "worker01"],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.set_env",
"args": ("worker01", ""),
"ret": True,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # 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, tmp_path):
version = "2019.6"
with (tmp_path / "env.yaml").open("w") as f_conf:
f_conf.write("env content")
monkeypatch.setattr(
sys,
"argv",
["lavacli", "workers", "env", "set", "worker01", str(tmp_path / "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, tmp_path):
version = "2019.6"
with (tmp_path / "env.yaml").open("w") as f_conf:
f_conf.write("env content")
monkeypatch.setattr(
sys,
"argv",
["lavacli", "workers", "env", "set", "worker01", str(tmp_path / "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()[1] == "Unable to store worker environment\n" # nosec
def test_workers_env_dut_delete(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
monkeypatch.setattr(
sys,
"argv",
["lavacli", "workers", "env-dut", "delete", "worker01"],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.set_env_dut",
"args": ("worker01", ""),
"ret": True,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
def test_workers_env_dut_get(setup, monkeypatch, capsys):
version = "2022.4"
monkeypatch.setattr(
sys, "argv", ["lavacli", "workers", "env-dut", "get", "worker01"]
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.get_env_dut",
"args": ("worker01",),
"ret": "env-dut content",
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "env-dut content\n" # nosec
def test_workers_env_dut_set(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
with (tmp_path / "env.yaml").open("w") as f_conf:
f_conf.write("env-dut content")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"workers",
"env-dut",
"set",
"worker01",
str(tmp_path / "env.yaml"),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.set_env_dut",
"args": ("worker01", "env-dut content"),
"ret": True,
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
def test_workers_env_dut_set_error(setup, monkeypatch, capsys, tmp_path):
version = "2022.4"
with (tmp_path / "env.yaml").open("w") as f_conf:
f_conf.write("env-dut content")
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"workers",
"env-dut",
"set",
"worker01",
str(tmp_path / "env.yaml"),
],
)
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.set_env_dut",
"args": ("worker01", "env-dut content"),
"ret": False,
},
],
)
assert main() == 1 # nosec
assert capsys.readouterr()[1] == "Unable to store worker dut environment\n" # nosec
def test_workers_list_exclude_retired(setup, monkeypatch, capsys):
version = "2023.3"
monkeypatch.setattr(sys, "argv", ["lavacli", "workers", "list"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.workers.list",
"args": (False,),
"ret": ["worker01", "worker02"],
},
],
)
assert main() == 0 # nosec
assert ( # nosec
capsys.readouterr()[0]
== """Workers:
* worker01
* worker02
"""
)
def test_workers_list(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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 = "2019.1"
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(setup, monkeypatch, capsys):
version = "2019.1"
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 = "2019.1"
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 = "2019.1"
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(setup, monkeypatch, capsys):
version = "2019.1"
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