pax_global_header 0000666 0000000 0000000 00000000064 15265406512 0014520 g ustar 00root root 0000000 0000000 52 comment=e68b3132f336d7cead4c8b76156d6ad6fc375405
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/ 0000775 0000000 0000000 00000000000 15265406512 0020767 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/.coveragerc 0000664 0000000 0000000 00000000151 15265406512 0023105 0 ustar 00root root 0000000 0000000 [run]
source =
lavacli
branch = True
[report]
precision = 2
[html]
title = lavacli coverage report
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/.gitignore 0000664 0000000 0000000 00000000144 15265406512 0022756 0 ustar 00root root 0000000 0000000 .coverage
.eggs
_build/
__pycache__/
dist/
lavacli.egg-info/
coverage.xml
report.xml
.venv/
uv.lock
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/.gitlab-ci.yml 0000664 0000000 0000000 00000006063 15265406512 0023430 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-12:
extends: .test
image: debian:bookworm
test-debian-13:
extends: .test
image: debian:trixie
test-debian-14:
extends: .test
image: debian:forky
test-ubuntu-22.04:
extends: .test
image: ubuntu:22.04
test-ubuntu-24.04:
extends: .test
image: ubuntu:24.04
test-ubuntu-26.04:
extends: .test
image: ubuntu:26.04
test-ubuntu-26.10:
extends: .test
image: ubuntu:26.10
###########
# Analyze #
###########
pylint:
extends: .analyze
script:
- make pylint
black:
extends: .analyze
script:
- make black
coverage:
extends: .analyze
image: debian:trixie
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-build python3-setuptools
script:
- python3 -m build --no-isolation --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-aiohttp python3-jinja2 python3-requests python3-ruamel.yaml python3-sphinx python3-voluptuous
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/LICENSE 0000664 0000000 0000000 00000103330 15265406512 0021774 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/MANIFEST.in 0000664 0000000 0000000 00000000215 15265406512 0022523 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/Makefile 0000664 0000000 0000000 00000001337 15265406512 0022433 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/README.md 0000664 0000000 0000000 00000001050 15265406512 0022242 0 ustar 00root root 0000000 0000000 lavacli
=======
lavacli is a command line tool to interact with LAVA instances using XML-RPC.
It 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.
The documentation can be found at: https://docs.lavasoftware.org/lavacli/
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/ 0000775 0000000 0000000 00000000000 15265406512 0022211 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/changelog 0000664 0000000 0000000 00000030770 15265406512 0024072 0 ustar 00root root 0000000 0000000 lavacli (3.1.0-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Rémi Duraffort Mon, 19 Oct 2026 14:29:43 +0200
lavacli (3.0.0-1) unstable; urgency=medium
[ Rémi Duraffort ]
* New upstream release
-- Rémi Duraffort Mon, 28 Sep 2026 15:48:59 +0200
lavacli (2.9.0-1) unstable; urgency=medium
[ Andrej Shadura ]
* Bump debhelper from old 12 to 13
* Use dh-sequence-python3
* Simplify debian/rules
* Point Vcs-* to Salsa
* Bump Standards-Version to 4.7.2
* Require Python Version 3.7 or newer
* Add python3-voluptuous to Build-Depends
* Mark test-only dependencies as
* Wrap and sort debian/control
* Add myself to the Uploaders
* Make voluptuous a hard dependency as it should be
* Build-depend on python3-zmq
* Update copyrights
[ Christopher Obbard ]
* d/gbp.conf: Update for DEP-14 branch names
* d/watch: Fix upstream tag scanning
* d/control: Set Maintainer to Debian Python Team
* d/control: Add myself to Uploaders
* d/control: Update Vcs-* fields
* d/control: Bump Standards-version to 4.7.3
* d/salsa-ci.yml: Enable Salsa CI
* d/rules: Fix clean target (Closes: #1049177)
* d/gbp.conf: Override settings for all commands
* d/watch: switch to version 5 format
* d/control: bump Standards-Version to 4.7.4
[ Antonio Terceiro ]
* Drop myself from Uploaders:
[ Alexandre Detiste ]
* drop Python2 debian/pydist-overrides
[ Rémi Duraffort ]
* New upstream release
-- Mon, 22 Jun 2026 09:31:12 +0200
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/control 0000664 0000000 0000000 00000003146 15265406512 0023620 0 ustar 00root root 0000000 0000000 Source: lavacli
Maintainer: Debian Python Team
Uploaders:
Remi Duraffort ,
Andrej Shadura ,
Christopher Obbard ,
Section: admin
Build-Depends:
debhelper-compat (= 13),
dh-sequence-python3,
pybuild-plugin-pyproject,
python3-aiohttp,
python3-all,
python3-jinja2,
python3-pytest ,
python3-requests,
python3-ruamel.yaml,
python3-setuptools,
python3-sphinx,
python3-voluptuous,
python3-zmq,
X-Python-Version: >= 3.7
Standards-Version: 4.7.4
Homepage: https://gitlab.com/lava/lavacli
Vcs-Git: https://salsa.debian.org/python-team/packages/lavacli.git
Vcs-Browser: https://salsa.debian.org/python-team/packages/lavacli
Package: lavacli
Architecture: all
Depends:
${misc:Depends},
${python3:Depends},
python3-zmq,
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/copyright 0000664 0000000 0000000 00000107510 15265406512 0024150 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: 2017—2023 Linaro Limited
2017—2023 Remi Duraffort
License: AGPL-3.0
Files: debian/*
Copyright:
2018 Senthil Kumaran S
2018—2019 Neil Williams
2019 Steve McIntyre <93sam@debian.org>
2019—2023 Rémi Duraffort
2019—2023 Antonio Terceiro
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/gbp.conf 0000664 0000000 0000000 00000000153 15265406512 0023627 0 ustar 00root root 0000000 0000000 [DEFAULT]
debian-branch = debian/main
upstream-tree = TAG
upstream-tag = v%(version)s
pristine-tar = False
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/install 0000664 0000000 0000000 00000000050 15265406512 0023575 0 ustar 00root root 0000000 0000000 share/lavacli.yaml ./usr/share/lavacli/
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/lavacli.manpages 0000664 0000000 0000000 00000000031 15265406512 0025333 0 ustar 00root root 0000000 0000000 doc/_build/man/lavacli.1
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/rules 0000775 0000000 0000000 00000001010 15265406512 0023261 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 $@ --buildsystem=pybuild
execute_after_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_clean:
dh_auto_clean
$(RM) -r doc/_build
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/salsa-ci.yml 0000664 0000000 0000000 00000000137 15265406512 0024431 0 ustar 00root root 0000000 0000000 ---
include:
- https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/recipes/debian.yml
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/source/ 0000775 0000000 0000000 00000000000 15265406512 0023511 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/source/format 0000664 0000000 0000000 00000000014 15265406512 0024717 0 ustar 00root root 0000000 0000000 3.0 (quilt)
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/tests/ 0000775 0000000 0000000 00000000000 15265406512 0023353 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/tests/control 0000664 0000000 0000000 00000000107 15265406512 0024754 0 ustar 00root root 0000000 0000000 Tests: testsuite
Depends: @, python3-pytest
Restrictions: allow-stderr
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/tests/testsuite 0000664 0000000 0000000 00000000422 15265406512 0025325 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/debian/watch 0000664 0000000 0000000 00000000103 15265406512 0023234 0 ustar 00root root 0000000 0000000 Version: 5
Template: GitLab
Dist: https://gitlab.com/lava/lavacli
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/ 0000775 0000000 0000000 00000000000 15265406512 0021534 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/Makefile 0000664 0000000 0000000 00000001134 15265406512 0023173 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/conf.py 0000664 0000000 0000000 00000012447 15265406512 0023043 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 pathlib
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.
#
# "lavacli --version" prints "lavacli "
version_str = (
subprocess.check_output(
["python3", "-m", "lavacli", "--version"],
stderr=subprocess.DEVNULL,
cwd=pathlib.Path(__file__).parent.parent,
)
.decode("utf-8")
.split()[-1]
)
# 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 = "en"
# 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/configuration.rst 0000664 0000000 0000000 00000005003 15265406512 0025133 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 **$XDG_CONFIG_HOME/lavacli.yaml**,
defaulting to **~/.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
identical:
.. 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
* **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 (only for servers older than 2020.09)
On servers older than 2020.09, events are received with zmq and 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
On newer servers, events are received through the websocket at the root of the
instance (derived from **uri**) and the **events** key is ignored.
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/index.rst 0000664 0000000 0000000 00000001023 15265406512 0023371 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
* groups
* jobs
* lab
* results
* system
* tags
* tokens
* users
* workers
It also provides an MCP server, helpers to print logs and render templates, and
manages the local identities.
Table of Contents
=================
.. toctree::
:maxdepth: 2
install
configuration
usage
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/install.rst 0000664 0000000 0000000 00000001307 15265406512 0023735 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/doc/usage.rst 0000664 0000000 0000000 00000026505 15265406512 0023402 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 devices [--health ]
lavacli device-types health-check delete
lavacli device-types health-check get
lavacli device-types health-check set
lavacli device-types list [--all]
lavacli device-types perms add
lavacli device-types perms delete
lavacli device-types perms list
lavacli device-types show
lavacli device-types template delete
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 delete
lavacli devices dict get [] [--render] [--context ]
lavacli devices dict set
lavacli devices list [--all]
lavacli devices maintenance [--force] [--no-wait] [--reason ]
lavacli devices perms add
lavacli devices perms delete
lavacli devices perms list
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 [--filter (device|event|testjob|worker)]
lavacli events wait device [--state ] [--health ]
lavacli events wait job [--state ] [--health ]
lavacli events wait worker [--state ] [--health ]
Groups
======
LAVA groups can be managed by:
.. code-block:: shell
lavacli groups add
lavacli groups delete
lavacli groups list
lavacli groups perms add
lavacli groups perms delete
lavacli groups perms list
lavacli groups show
Identities
==========
lavacli identities can be managed by:
.. code-block:: shell
lavacli identities add --uri [--username ] [--token ] [--proxy ]
lavacli identities delete
lavacli identities list
lavacli identities show
Jobs
====
LAVA jobs can be managed by:
.. code-block:: shell
lavacli jobs autocancel --duration [--dry-run]
lavacli jobs cancel [ ...]
lavacli jobs config [--dest ]
lavacli jobs definition
lavacli jobs find-errors [--limit ] [--since ]
lavacli jobs list [...]
lavacli jobs logs [...]
lavacli jobs queue [ ...]
lavacli jobs resubmit [--follow] [...]
lavacli jobs run [...]
lavacli jobs show
lavacli jobs submit [ ...] [--follow] [...]
lavacli jobs validate [--strict]
lavacli jobs wait [--polling ] [--timeout ]
The commands printing logs (**logs**, **run** and **submit** or **resubmit**
with **--follow**) accept the **--filters**, **--quiet** and **--raw** options
described in `Printing logs`_.
Lab
===
LAVA lab can be managed by:
.. code-block:: shell
lavacli lab apply [--dry-run] [--resources ] [--delete]
lavacli lab import [--resources ] [--exclude ]
lavacli lab validate
**--resources** can be given multiple times to restrict the command to some
resources (groups, users, devices, device-types and workers).
MCP
===
Start an MCP server for the selected LAVA instance. You can then connect your
LLM to LAVA via this MCP server:
.. code-block:: shell
lavacli mcp
lavacli mcp --transport streamable-http [--host ] [--port ]
The instance is the one selected by **--identity** or **--uri**, reached over
the same XML-RPC calls as every other lavacli command.
The server provides tools to list and show jobs, device-types, devices and
workers, to read the job queue, a job definition, its logs, a device-type
template and health-check and a device dictionary, to browse the results of a
job (its suites, test cases and metadata), and to read the official LAVA
documentation. The documentation is read from the markdown sources of the lava
repository, at the tag of the release the instance runs when there is one,
falling back to the development branch.
The job list can be narrowed down to one device, device-type, worker,
submitter or error type, on top of the state, health and time window the
server filters on. LAVA does not know about these filters: the MCP server reads
the jobs of the time window, which is then required, a page at a time and keeps
the matching ones, reading at most 5000 jobs per call. A worker filter keeps
the jobs of the devices attached to the worker now. Another tool counts the
finished jobs of every device over a time window, optionally for one
device-type or worker, and ranks the devices by failure rate (incomplete jobs
out of the complete and incomplete ones), with the number of failures per
error type: the LLM finds the failing devices without reading every job.
The server also provides prompts, ready-made requests that walk the LLM
through a common investigation with these tools, optionally for one
device-type or worker:
* ``devices_status`` looks at the jobs of the last hours (24 by default),
groups the failures by root cause, tells for each one whether it looks like
an infrastructure or a test issue and ranks the devices by failure rate.
* ``device_dictionaries_review`` reads the device dictionaries and looks for
configuration mistakes, like a command reaching the port of another device or
a resource assigned to two devices.
A few tools change the instance: submitting and canceling a job, setting a
device-type template or a device dictionary. They are advertised as
such in their MCP annotations, so that the client can ask for a confirmation
before running them, while the other tools are flagged read-only. The tools act
with the permissions of the token used by **--identity** or **--uri**: give the
server a token without the matching permissions to keep it read-only.
This command requires the ``mcp`` python module, which is not installed by
default:
.. code-block:: shell
pip install lavacli[mcp]
Only the FastMCP 1.x series is supported.
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 certificate
lavacli system maintenance [--force] [--exclude ]
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 maintenance immediately, adding **--force** will:
* set all workers health to *MAINTENANCE*
* cancel all running jobs
* wait for all jobs to finish
It is also possible to exclude some workers with **--exclude**, using a comma
separated list of workers.
When the maintenance is finished, calling **system active** will set the health
of every worker to *ACTIVE*, whatever its current health.
Tags
====
LAVA tags can be managed by:
.. code-block:: shell
lavacli tags add [--description ]
lavacli tags delete
lavacli tags list
lavacli tags show
Tokens
======
Manage user remote artifact tokens:
.. code-block:: shell
lavacli tokens add --token
lavacli tokens delete
lavacli tokens list
lavacli tokens show
Users
=====
Manage LAVA users with:
.. code-block:: shell
lavacli users add [...]
lavacli users delete
lavacli users groups add
lavacli users groups delete
lavacli users groups list
lavacli users perms add
lavacli users perms delete
lavacli users perms list
lavacli users list
lavacli users show
lavacli users update [...]
Utils
=====
Some utilities are available with:
.. code-block:: shell
lavacli utils logs print
lavacli utils templates render [--path ] [--context ] [--trim]
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 --filters target,input
Available log levels are: exception, error, warning, info, debug, target,
input, feedback, results.
To only print the job phases (deploy, boot, ...) and the DUT output, use
**--quiet**. The job definition can be given with **--job-definition** to
improve the result. Use **--raw** to print the logs as is.
Workers
=======
LAVA workers can be managed by:
.. code-block:: shell
lavacli workers add [--description ] [--disabled]
lavacli workers config delete
lavacli workers config get
lavacli workers config set
lavacli workers env delete
lavacli workers env get
lavacli workers env set
lavacli workers env-dut delete
lavacli workers env-dut get
lavacli workers env-dut set
lavacli workers list [--all]
lavacli workers maintenance [--force] [--no-wait]
lavacli workers show
lavacli workers update [...]
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/ 0000775 0000000 0000000 00000000000 15265406512 0022402 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/__about__.py 0000664 0000000 0000000 00000002470 15265406512 0024665 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__ = "3.1.0"
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/__init__.py 0000664 0000000 0000000 00000023405 15265406512 0024517 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,
mcp,
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,
"mcp": mcp,
"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
# Keep the version string: parse_version drops the '.devNNNN' suffix
# of development builds.
config["server_version"] = str(version)
# 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/__main__.py 0000664 0000000 0000000 00000001523 15265406512 0024475 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/colors.py 0000664 0000000 0000000 00000000157 15265406512 0024260 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/ 0000775 0000000 0000000 00000000000 15265406512 0024203 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/__init__.py 0000664 0000000 0000000 00000000000 15265406512 0026302 0 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/aliases.py 0000664 0000000 0000000 00000007641 15265406512 0026206 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/device_types.py 0000664 0000000 0000000 00000036074 15265406512 0027252 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 binary2str, 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(binary2str(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(binary2str(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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/devices.py 0000664 0000000 0000000 00000045026 15265406512 0026206 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 binary2str, 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",
)
if version >= (2025, 12):
devices_maintenance.add_argument(
"--reason", default=None, help="reason of health change"
)
# "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(binary2str(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":
ret = proxy.scheduler.devices.set_dictionary(options.name, "")
if not ret:
print("Unable to delete the configuration", file=sys.stderr)
return 0 if ret else 1
elif options.sub_sub_sub_command == "get":
config = binary2str(
proxy.scheduler.devices.get_dictionary(
options.name, options.render, options.context
)
)
if not options.field:
print(config.rstrip("\n"))
return 0
if options.render:
value = safe_yaml.load(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, config):
if config["version"] < (2025, 12):
proxy.scheduler.devices.update(
options.name, None, None, None, None, "MAINTENANCE", None
)
else:
proxy.scheduler.devices.update(
options.name,
None,
None,
None,
None,
"MAINTENANCE",
None,
None,
options.reason,
)
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/events.py 0000664 0000000 0000000 00000023067 15265406512 0026071 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__
from lavacli.utils import uri_hostname
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:
url = url.replace("*", uri_hostname(options.uri))
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/groups.py 0000664 0000000 0000000 00000013207 15265406512 0026077 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/identities.py 0000664 0000000 0000000 00000010074 15265406512 0026720 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/jobs.py 0000664 0000000 0000000 00000105466 15265406512 0025526 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 ast
import contextlib
import datetime
import json
import os
import pathlib
import re
import shlex
import sys
import time
import xmlrpc.client
from collections import defaultdict
from urllib.parse import urlparse
from ruamel.yaml.error import YAMLError
from lavacli.utils import (
JOB_HEALTHS,
JOB_STATES,
binary2str,
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(
"--quiet",
default=False,
action="store_true",
help="only print the job phases (deploy, boot, ...) and the DUT output",
)
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=JOB_STATES,
help="filter jobs by state",
)
jobs_list.add_argument(
"--health",
type=str,
default=None,
choices=JOB_HEALTHS,
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(
"--no-follow",
default=False,
action="store_true",
help="do not keep polling until the end of the job",
)
configure_log_options(jobs_run)
# "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
# The server sends the files as bytes, so they are received as Binary.
# Any of them can be None when the job did not use the corresponding file.
for filename, data in [
("definition.yaml", definition),
("device.yaml", device),
("dispatcher.yaml", dispatcher),
("env.yaml", env),
("env.dut.yaml", env_dut),
]:
if isinstance(data, xmlrpc.client.Binary):
data = data.data.decode("utf-8")
if data is None:
continue
with (dest / filename).open("w", encoding="utf-8") as f_out:
f_out.write(data)
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",
"action": "\033[1m",
"command": "\033[1;36m",
"dt": "\033[0;90m",
"end": "\033[0m",
}
else:
COLORS = {
"exception": "",
"error": "",
"warning": "",
"info": "",
"debug": "",
"target": "",
"input": "",
"feedback": "",
"results": "",
"action": "",
"command": "",
"dt": "",
"end": "",
}
# Top level actions are logged at the info level with a level without any dot
# (sub actions are "1.1", "1.2", ...)
QUIET_ACTION_PATTERN = re.compile(r"^start: (\d+) (\S+)")
QUIET_DOWNLOAD_PATTERN = re.compile(r"^downloading (\S+)", re.IGNORECASE)
QUIET_FETCHING_TEST = re.compile(r"^Fetching tests from (\S+)")
# "88MB downloaded in 2.42s (36.41MB/s)"
QUIET_DOWNLOADED_PATTERN = re.compile(
r"\b(?:downloaded|transferred) in\b", re.IGNORECASE
)
# "Calling: ['laacli', 'power', '12v', 'off']" and "Returned 0 in 41 seconds"
QUIET_CALLING_PATTERN = re.compile(r"^Calling: (\[.*\])$")
QUIET_RETURNED_PATTERN = re.compile(r"^Returned \d+ in \d+ seconds?")
def deploy_images(params):
"""List the images to deploy, looking for dicts with an url"""
names = []
for key, value in params.items():
if not isinstance(value, dict):
continue
if "url" in value:
names.append(key)
else:
# "images" is a dict of dicts
names.extend(
k for (k, v) in value.items() if isinstance(v, dict) and "url" in v
)
return names
def describe_deploy(params):
msg = "deploy"
if params.get("to"):
msg += " to %s" % params["to"]
details = deploy_images(params)
if params.get("os"):
details.insert(0, params["os"])
if details:
msg += " (%s)" % ", ".join(str(d) for d in details)
if params.get("postprocess"):
msg += " with postprocess"
return msg
def describe_boot(params):
msg = "boot"
if params.get("method"):
msg += " with %s" % params["method"]
details = []
for key in ["commands", "media", "type"]:
# "commands" can also be a list of bootloader commands
if isinstance(params.get(key), str):
details.append(params[key])
if details:
msg += " (%s)" % ", ".join(details)
return msg
def describe_test(params):
names = []
for key in ["definitions", "monitors", "interactive"]:
for item in params.get(key) or []:
if isinstance(item, dict) and item.get("name"):
names.append(str(item["name"]))
msg = "test"
if names:
msg += " (%s)" % ", ".join(names)
return msg
def describe_action(name, params):
"""Describe one action of the job definition"""
if name == "deploy":
return describe_deploy(params)
if name == "boot":
return describe_boot(params)
if name == "test":
return describe_test(params)
if params.get("name"):
return "%s (%s)" % (name, params["name"])
return str(name)
def job_definition(proxy, job_id):
"""Download and parse the job definition"""
try:
return safe_yaml.load(proxy.scheduler.jobs.definition(job_id))
except (xmlrpc.client.Error, YAMLError):
return None
def describe_command(msg):
"""Format a command, from ['laacli', 'power', 'off'] to $ laacli power off"""
try:
cmd = shlex.join(ast.literal_eval(msg))
except (SyntaxError, ValueError, TypeError):
cmd = msg
return COLORS["command"] + "$ " + cmd + COLORS["end"]
RESULT_ICONS = {
"pass": "\u2713", # check mark
"fail": "\u2717", # ballot X
"skip": "\u2298", # circled division slash
"unknown": "\u003f", # question mark
}
def describe_result(msg):
"""Format a lava result as .: """
case = str(msg.get("case", ""))
definition = msg.get("definition")
name = "%s.%s" % (definition, case) if definition else case
result = msg.get("result", "")
icon = RESULT_ICONS.get(result, "\u2022") # bullet
text = "%s %s: %s" % (icon, name, result)
if msg.get("measurement") is not None:
text += " (%s%s)" % (msg["measurement"], msg.get("units") or "")
return text
class QuietFilter:
"""
Filter and reformat the logs to only print top level actions and DUT
interaction
"""
def __init__(self, definition=None):
self.actions = {}
self.level = None
actions = definition.get("actions") if isinstance(definition, dict) else None
for index, action in enumerate(actions or [], start=1):
if not isinstance(action, dict) or not action:
continue
(name, params) = next(iter(action.items()))
if not isinstance(params, dict):
params = {}
self.actions[str(index)] = describe_action(name, params)
def __call__(self, logs):
lines = []
for line in logs:
level = line["lvl"]
msg = line["msg"]
if level in ["input", "target", "feedback", "error", "exception"]:
lines.append(line)
continue
if level == "results" and isinstance(msg, dict):
# Indent the results under the current action and print the
# failures in red
if msg.get("result") == "fail":
level = "error"
lines.append(dict(line, lvl=level, msg=" " + describe_result(msg)))
continue
if isinstance(msg, dict) and "sending" in msg:
# Commands sent to the DUT, formatted by print_logs
lines.append(line)
continue
if not isinstance(msg, str):
continue
if msg.startswith("[lavacli]"):
lines.append(line)
continue
match = QUIET_ACTION_PATTERN.match(msg)
if level == "info" and match:
(self.level, name) = match.groups()
description = self.actions.get(self.level, name)
lines.append(
dict(line, lvl="action", msg=f"{self.level}. {description}")
)
continue
match = QUIET_DOWNLOAD_PATTERN.match(msg)
if match:
# Indent the downloads under the current action
lines.append(dict(line, msg=" \u2192 " + match.group(1)))
continue
if QUIET_DOWNLOADED_PATTERN.search(msg):
# Size, duration and speed, below the corresponding url
lines.append(dict(line, msg=" " + msg))
continue
match = QUIET_FETCHING_TEST.match(msg)
if match:
lines.append(dict(line, msg=" \u2192 " + match.group(1)))
match = QUIET_CALLING_PATTERN.match(msg)
if match:
command = describe_command(match.group(1))
lines.append(dict(line, msg=" " + command))
continue
if msg.startswith(">>"):
# Output of a command, that can be multi lines
output = "\n".join(
" " + out for out in msg[2:].lstrip(" ").splitlines()
)
lines.append(dict(line, msg=output))
continue
if QUIET_RETURNED_PATTERN.match(msg):
lines.append(dict(line, msg=" " + msg))
continue
return lines
def print_logs(logs, raw, filters, quiet=None):
filters = [] if filters is None else filters.split(",")
if quiet is not None:
logs = quiet(logs)
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(binary2str(data))
return (finished, logs)
def handle_logs(proxy, options, config):
# In quiet mode, describe the actions using the job definition
quiet = None
if options.quiet:
quiet = QuietFilter(job_definition(proxy, options.job_id))
# 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, quiet)
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 0
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 is always sent by the server, but is None when
# the job does not have any metadata.
error_msg = (job_data.get("error_msg") or "").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)
return 0
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/lab.py 0000664 0000000 0000000 00000140103 15265406512 0025312 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 binary2str, 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 = binary2str(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 = binary2str(
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 = binary2str(
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 = binary2str(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 = binary2str(
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 = binary2str(
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 = binary2str(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 = binary2str(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 = binary2str(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 = binary2str(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 = binary2str(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 = binary2str(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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/mcp.py 0000664 0000000 0000000 00000120232 15265406512 0025334 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2026 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
# The mcp module is an optional dependency: every import of it is local, so
# that the other lavacli commands keep working without it installed.
# pylint: disable=import-outside-toplevel
import os
import signal
import sys
import threading
import xmlrpc.client
from lavacli import docs
from lavacli.__about__ import __version__
from lavacli.utils import JOB_HEALTHS, JOB_STATES, exc2str, safe_yaml, uri_hostname
# Jobs read at most by one filtered jobs_list call
JOBS_SCAN_LIMIT = 5000
def configure_parser(parser, version):
parser.add_argument(
"--transport",
default="stdio",
choices=["stdio", "streamable-http"],
help="MCP transport [default=stdio]",
)
parser.add_argument(
"--host", default="127.0.0.1", help="listening address for streamable-http"
)
parser.add_argument(
"--port", type=int, default=8000, help="listening port for streamable-http"
)
def help_string():
return "start a MCP server"
def create_server(options, instance):
# Create the MCP server and return it with the arguments for run().
from mcp.server.transport_security import TransportSecuritySettings
from mcp.server.fastmcp import FastMCP
instructions = f"""Read and Write access to the LAVA instance at {instance}.
LAVA runs test jobs on real and virtual boards.
A *job* is submitted against a *device-type* (a model of board, like 'qemu' or
'bcm2711-rpi-4-b'), scheduled on a *device* (one physical board, also called
'DUT' by users) which is attached to a *worker* (the machine driving that
board).
Jobs, devices and workers all carry a *state* (where they are in their
lifecycle) and a *health* (whether they are usable or, for a finished job,
whether it passed).
For each job, a set of results are created. When a job health is COMPLETE,
every steps in the job definition where able to complete and you can inspect
the results to know which tests passed or failed. When a job is INCOMPLETE, one
or multiple steps where not ran properly and the results may be incomplete or
invalid.
Most tools only read the instance. A few change it: job_submit, job_cancel,
device_type_template_set and device_dictionary_set.
A device-type template or a device dictionary is the configuration LAVA uses to
run every job on the matching boards: read the current one and check the
documentation before replacing it, a wrong value breaks every job of that
device-type or device.
Use documentation_list and documentation_fetch to read the official LAVA
documentation before guessing how a field or a job definition works.
To find out why a job is INCOMPLETE, or why its results are wrong, read the
'user/advanced-tutorials/debugging-job' page: it lists the common failures,
how to recognize them in the logs and how to fix them."""
server = FastMCP(
"lavacli",
instructions=instructions,
host=options.host,
port=options.port,
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=False,
),
)
server.settings.streamable_http_path = "/"
return (server, {})
def to_json(data):
"""Make an XML-RPC answer JSON serializable."""
if isinstance(data, xmlrpc.client.DateTime):
return data.value
if isinstance(data, xmlrpc.client.Binary):
return data.data.decode("utf-8", errors="replace")
if isinstance(data, bytes):
return data.decode("utf-8", errors="replace")
if isinstance(data, dict):
return {k: to_json(v) for k, v in data.items()}
if isinstance(data, (list, tuple)):
return [to_json(v) for v in data]
return data
def to_cases(data, metadata):
"""Parse a YAML list of test cases, dropping the bulky metadata."""
cases = safe_yaml.load(str(data)) or []
if not metadata:
for case in cases:
case.pop("metadata", None)
return to_json(cases)
def handle(proxy, options, config):
version = config["version"]
# Only the hostname: the uri carries the username and the token, which
# have no reason to be handed over to an LLM.
instance = uri_hostname(options.uri)
# Imported here: the mcp module is an optional dependency, every other
# lavacli command works without it.
try:
from mcp.server.fastmcp.exceptions import ToolError
from mcp.types import ToolAnnotations
mcp, run_args = create_server(options, instance)
except ImportError as exc:
# Report the real import error: the module is sometimes installed but
# in a version this command cannot drive.
print(
f"Unable to start the MCP server: {exc}\n"
"The 'mcp' python module, version 1.x, is required by 'lavacli mcp'.\n"
"Install it with: pip install lavacli[mcp]",
file=sys.stderr,
)
return 1
# Annotations tell the client what a tool does before it runs it, so that
# it can ask the user about the few tools changing the instance and leave
# the others alone.
READ_ONLY = ToolAnnotations(
readOnlyHint=True, destructiveHint=False, idempotentHint=True
)
WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=True)
# The XML-RPC proxy is not reentrant while the server answers requests
# from several threads.
lock = threading.Lock()
def rpc(method, *args):
"""Call an XML-RPC method and return a JSON serializable answer."""
try:
with lock:
return to_json(method(*args))
except xmlrpc.client.Error as exc:
raise ToolError(exc2str(exc, options.uri)) from exc
def worker_device_names(worker):
"""Return the hostnames of the devices of a worker, None for no worker."""
if worker is None:
return None
return set(rpc(proxy.scheduler.workers.show, worker)["devices"])
########
# Jobs #
########
@mcp.tool(annotations=READ_ONLY)
def jobs_list(
state: str | None = None,
health: str | None = None,
start: int = 0,
limit: int = 25,
since: int = 0,
verbose: bool = False,
device: str | None = None,
device_type: str | None = None,
submitter: str | None = None,
error_type: str | None = None,
worker: str | None = None,
) -> list:
"""List the test jobs of the instance, most recent first.
Args:
state: Keep only jobs in this state — one of: SUBMITTED,
SCHEDULING, SCHEDULED, RUNNING, CANCELING, FINISHED
health: Keep only jobs with this health — one of: UNKNOWN,
COMPLETE, INCOMPLETE, CANCELED
start: Skip the N first jobs (default: 0)
limit: Return at most N jobs (default: 25)
since: Keep only jobs that finished in the last N minutes
(default: 0, no filter). Required with the filters below.
verbose: Add the error_type and error_msg of failing jobs
(default: False)
device: Keep only the jobs that ran on this device, e.g. 'qemu-01'
device_type: Keep only the jobs of this device-type, e.g. 'qemu'
submitter: Keep only the jobs of this user, e.g. 'lava-health'
for the health-checks
error_type: Keep only the jobs that failed with this error type,
e.g. 'Infrastructure', 'Job', 'Test'
worker: Keep only the jobs that ran on the devices attached to this
worker, e.g. 'worker-01'. The devices attached now: a
device moved from another worker brings its older jobs.
When filtering per device, device_type, submitter, error_type and
worker: the jobs of the 'since' window are read here, a page at a time,
until 'limit' of them match. At most 5000 jobs are read per call: when
that stops the search, a last entry {"scan_limit_reached": true,
"scanned": N} is added. Narrow the window with 'since', 'state' or
'health' and call again.
Returns:
One entry per job with its id, description, submitter, device-type,
device ('actual_device'), start and end times, state and health.
"""
if state is not None and state not in JOB_STATES:
raise ToolError(f"invalid state '{state}': expected one of {JOB_STATES}")
if health is not None and health not in JOB_HEALTHS:
raise ToolError(f"invalid health '{health}': expected one of {JOB_HEALTHS}")
def clean(job):
# The verbose answer is always requested from the server: it is the
# only one carrying the device. Drop what was not asked for.
if not verbose:
job.pop("error_msg", None)
job.pop("error_type", None)
return job
filters = {
"actual_device": device,
"device_type": device_type,
"submitter": submitter,
"error_type": error_type,
}
filters = {k: v for k, v in filters.items() if v is not None}
if not filters and worker is None:
jobs = rpc(
proxy.scheduler.jobs.list, state, health, start, limit, since, True
)
return [clean(job) for job in jobs]
if since <= 0:
raise ToolError(
"'since' is required with device, device_type, submitter, "
"error_type or worker: every job of the window has to be read"
)
worker_devices = worker_device_names(worker)
matches = []
skipped = 0
scanned = 0
while len(matches) < limit and scanned < JOBS_SCAN_LIMIT:
jobs = rpc(
proxy.scheduler.jobs.list, state, health, scanned, 100, since, True
)
if not jobs:
return matches
# Advance by what the server actually returned, not by what was asked.
scanned += len(jobs)
for job in jobs:
if any(job.get(k) != v for k, v in filters.items()):
continue
if worker_devices is not None and (
job.get("actual_device") not in worker_devices
):
continue
if skipped < start:
skipped += 1
continue
matches.append(clean(job))
if len(matches) == limit:
return matches
if len(matches) < limit:
matches.append({"scan_limit_reached": True, "scanned": scanned})
return matches
@mcp.tool(annotations=READ_ONLY)
def jobs_stats(
since: int = 1440, device_type: str | None = None, worker: str | None = None
) -> list:
"""Count the finished jobs of every device, to rank them by failure rate.
Use it instead of paging through jobs_list to find out which devices
fail the most: the jobs are counted here, only one line per device is
returned.
Args:
since: Count the jobs that finished in the last N minutes
(default: 1440, the last 24 hours)
device_type: Keep only the devices of this device-type
(default: every device-type)
worker: Keep only the devices attached to this worker
(default: every worker)
Returns:
One entry per device, the highest failure rate first, with its
'device', 'device_type', the number of 'total', 'complete',
'incomplete' and 'canceled' jobs, the 'failure_rate' (incomplete
out of complete + incomplete, canceled jobs left out) and
'error_types', the number of incomplete jobs per error type
(Infrastructure, Job, Test, ...). Look at the failing jobs of one
device with jobs_list(device=..., health='INCOMPLETE', since=...,
verbose=True).
"""
if since <= 0:
raise ToolError("'since' should be a positive number of minutes")
worker_devices = worker_device_names(worker)
stats = {}
start = 0
while True:
jobs = rpc(
proxy.scheduler.jobs.list, "FINISHED", None, start, 100, since, True
)
if not jobs:
break
# Advance by what the server actually returned, not by what was asked.
start += len(jobs)
for job in jobs:
if device_type is not None and job.get("device_type") != device_type:
continue
# Jobs canceled before being scheduled never got a device.
device = job.get("actual_device")
if not device:
continue
if worker_devices is not None and device not in worker_devices:
continue
entry = stats.setdefault(
device,
{
"device": device,
"device_type": job.get("device_type"),
"total": 0,
"complete": 0,
"incomplete": 0,
"canceled": 0,
"error_types": {},
},
)
entry["total"] += 1
health = (job.get("health") or "").lower()
if health in ("complete", "incomplete", "canceled"):
entry[health] += 1
if health == "incomplete":
error_type = job.get("error_type") or "Unknown"
entry["error_types"][error_type] = (
entry["error_types"].get(error_type, 0) + 1
)
for entry in stats.values():
ran = entry["complete"] + entry["incomplete"]
entry["failure_rate"] = round(entry["incomplete"] / ran, 4) if ran else 0.0
return sorted(
stats.values(),
key=lambda e: (e["failure_rate"], e["incomplete"]),
reverse=True,
)
@mcp.tool(annotations=READ_ONLY)
def job_show(job_id: str) -> dict:
"""Show the details of one test job.
Args:
job_id: Job id, e.g. '1234' or '1234.0' for a multinode sub-job
Returns:
The job id, description, submitter, device-type, device, state,
health, timings and, when it failed, its failure comment and
error type.
"""
return rpc(proxy.scheduler.jobs.show, job_id)
@mcp.tool(annotations=READ_ONLY)
def job_definition(job_id: str) -> str:
"""Return the yaml definition submitted for one test job.
This is what the job was asked to do: the images deployed, the boot
method and the test suites.
Args:
job_id: Job id, e.g. '1234'
"""
return str(rpc(proxy.scheduler.jobs.definition, job_id))
@mcp.tool(annotations=READ_ONLY)
def job_logs(job_id: str, start: int = 0, limit: int = 100) -> dict:
"""Return the logs of one test job.
Use it to find out what actually happened on the board: the serial
output, the commands LAVA sent and the errors it hit.
Jobs log up to tens of thousands of lines. When a job fails, the
error is usually at the end of the log: start with start=-100 to get
the last 100 lines.
To read the whole log:
* in chunks: call with start=0, then again with start increased by
the 'count' of the previous answer. The end of the log is reached
when 'count' is lower than 'limit'.
* in one call: set limit=0, every line from start to the end is
returned. Keep it for short logs (see 'total'): a long log can
exceed what the client accepts in a single answer.
Args:
job_id: Job id, e.g. '1234'
start: First log line to return (default: 0). A negative value
counts from the end of the log: -100 for the last 100
lines.
limit: How many lines to return (default: 100), 0 to return every
line up to the end of the log.
Returns:
'finished' tells whether the job is over (when False, more lines
will show up later), 'total' is the number of lines of the log
(missing before LAVA 2026.10 unless start is negative), 'start'
and 'count' locate the returned lines, and each entry of 'logs'
has 'dt' (timestamp), 'lvl' (one of exception, error, warning,
info, debug, target, input, feedback, results) and 'msg'.
'target' is the board output. 'input' is the content written to
the board serial by LAVA.
"""
# scheduler.jobs.logs_count was added in LAVA 2026.10
total = None
if version >= (2026, 10):
total = rpc(proxy.scheduler.jobs.logs_count, job_id)
if start < 0:
if total is None:
# Download the whole log and keep the requested lines from the
# end of the buffer.
finished, data = rpc(proxy.scheduler.jobs.logs, job_id, 0, None)
logs = safe_yaml.load(str(data)) or []
total = len(logs)
start = max(0, total + start)
logs = logs[start : start + limit if limit else None]
else:
# The number of log lines is known, request only the end
start = max(0, total + start)
finished, data = rpc(
proxy.scheduler.jobs.logs,
job_id,
start,
start + limit if limit else None,
)
logs = safe_yaml.load(str(data)) or []
else:
# Download the requested chunk
finished, data = rpc(
proxy.scheduler.jobs.logs,
job_id,
start,
start + limit if limit else None,
)
logs = safe_yaml.load(str(data)) or []
answer = {
"finished": finished,
"start": start,
"count": len(logs),
"logs": to_json(logs),
}
if total is not None:
answer["total"] = total
return answer
@mcp.tool(annotations=READ_ONLY)
def jobs_queue(device_types: list[str] | None = None, limit: int = 25) -> list:
"""List the jobs waiting for a device to become available.
Args:
device_types: Only queue the jobs requesting these device-types
(default: every device-type)
limit: Return at most N jobs (default: 25)
"""
return rpc(proxy.scheduler.jobs.queue, device_types or None, 0, limit)
@mcp.tool(annotations=WRITE)
def job_submit(definition: str) -> dict:
"""Submit a new test job to the instance.
The job is queued: the scheduler runs it once a device of the
requested device-type is free. Follow it with job_show and job_logs.
Writing a definition from scratch rarely works: start from the
job_definition of a job that ran on the same device-type, or read the
documentation of the job definition format first.
Args:
definition: The yaml job definition
Returns:
'job_ids', the ids of the jobs that were created: one, or one per
role for a multinode definition.
"""
job_ids = rpc(proxy.scheduler.jobs.submit, definition)
if not isinstance(job_ids, list):
job_ids = [job_ids]
return {"job_ids": [str(job_id) for job_id in job_ids]}
@mcp.tool(annotations=WRITE)
def job_cancel(job_id: str) -> str:
"""Cancel one test job.
The job moves to the CANCELING state, then ends up FINISHED with the
CANCELED health. A job that already finished cannot be canceled.
Args:
job_id: Job id, e.g. '1234' or '1234.0' for a multinode sub-job
"""
rpc(proxy.scheduler.jobs.cancel, job_id)
return f"job {job_id} canceled"
###########
# Results #
###########
@mcp.tool(annotations=READ_ONLY)
def job_suites(job_id: str) -> list:
"""List the test suites of one finished test job.
A job stores its results as test cases grouped in test suites. LAVA
adds a 'lava' suite holding the result of every action it ran, next
to one suite per test definition of the job.
Args:
job_id: Job id, e.g. '1234'
Returns:
One entry per suite with its 'name', its database 'id' and the
'job' it belongs to. Feed a name to job_results.
"""
suites = rpc(proxy.results.get_testjob_suites_list_yaml, job_id)
return to_json(safe_yaml.load(str(suites)) or [])
@mcp.tool(annotations=READ_ONLY)
def job_results(
job_id: str,
suite: str | None = None,
case: str | None = None,
start: int = 0,
limit: int = 100,
metadata: bool = False,
) -> dict:
"""List the test case results of one test job.
Narrow it down the way the 'lavacli results' command does: the whole
job, one of its suites, or a single test case.
Args:
job_id: Job id, e.g. '1234'
suite: Keep only this suite, as named by job_suites, e.g. 'lava'
(default: every suite of the job)
case: Keep only this test case, as named by a previous call.
Requires 'suite'.
start: Skip the N first test cases (default: 0)
limit: Return at most N test cases (default: 100)
metadata: Keep the per-case metadata, which is bulky but holds
the details of a failure. Turn it on once narrowed
down to the failing case (default: False)
Returns:
'start' and 'count' locate the returned cases and 'total' counts
the cases of the whole job, or is null when 'suite' asked the
server for a single page: there, keep paging while 'count'
equals 'limit'. Each entry of 'results' has its 'name', 'suite',
'result' (pass, fail, skip or unknown), 'measurement' and 'unit'
when the test recorded one, 'url' and the log lines it came from.
"""
if case is not None:
if suite is None:
raise ToolError("'suite' is required to name a 'case'")
data = rpc(proxy.results.get_testcase_results_yaml, job_id, suite, case)
cases = to_cases(data, metadata)
return {
"start": 0,
"count": len(cases),
"total": len(cases),
"results": cases,
}
if suite is not None:
# The server pages this one, so the total is not known.
data = rpc(
proxy.results.get_testsuite_results_yaml, job_id, suite, limit, start
)
cases = to_cases(data, metadata)
return {
"start": start,
"count": len(cases),
"total": None,
"results": cases,
}
# The whole job comes as one answer: page through it here.
data = rpc(proxy.results.get_testjob_results_yaml, job_id)
cases = to_cases(data, metadata)
page = cases[start : start + limit] if limit else cases[start:]
return {
"start": start,
"count": len(page),
"total": len(cases),
"results": page,
}
@mcp.tool(annotations=READ_ONLY)
def job_metadata(job_id: str) -> dict:
"""Return the metadata of one test job.
Mixes what the job definition declared with what LAVA recorded while
running it: the git revisions of the test definitions, the boot
commands, the images deployed.
Args:
job_id: Job id, e.g. '1234'
"""
return rpc(proxy.results.get_testjob_metadata, job_id)
################
# Device types #
################
@mcp.tool(annotations=READ_ONLY)
def device_types_list(all_device_types: bool = False) -> list:
"""List the device-types of the instance.
A device-type is a model of board. Jobs request a device-type, the
scheduler then picks one of its devices.
Args:
all_device_types: Include the device-types without any device
(default: False)
Returns:
One entry per device-type with its name and the number of devices
that are installed, idle and busy.
"""
return rpc(proxy.scheduler.device_types.list, all_device_types)
@mcp.tool(annotations=READ_ONLY)
def device_type_show(name: str) -> dict:
"""Show the details of one device-type.
Args:
name: Device-type name, e.g. 'qemu'
Returns:
The name, description, aliases, health-check settings and the
number of devices of this device-type.
"""
return rpc(proxy.scheduler.device_types.show, name)
@mcp.tool(annotations=READ_ONLY)
def device_type_devices(name: str, health: str | None = None) -> list:
"""List the devices of one device-type.
Args:
name: Device-type name, e.g. 'qemu'
health: Keep only the devices with this health — one of: UNKNOWN,
MAINTENANCE, GOOD, BAD, LOOPING, RETIRED
"""
return rpc(proxy.scheduler.device_types.devices, name, health)
@mcp.tool(annotations=READ_ONLY)
def device_type_template(name: str) -> str:
"""Return the jinja2 template of one device-type.
The template is the configuration shared by every device of the
device-type: the boot and deploy methods it supports, its timeouts
and its default bootloader settings. Each device extends it with its
own device dictionary, so read both to know how a device is really
configured.
A device-type template is generic to every devices of this type while
the device dictionary is board specific.
Args:
name: Device-type name, e.g. 'qemu'
"""
return str(rpc(proxy.scheduler.device_types.get_template, name))
@mcp.tool(annotations=WRITE)
def device_type_template_set(name: str, template: str) -> str:
"""Replace the jinja2 template of one device-type.
The template is picked up by every job started from then on, on every
device of the device-type at once: read the current one with
device_type_template and keep everything that is not being changed.
Args:
name: Device-type name, e.g. 'qemu'
template: The whole jinja2 template, not a patch of it
"""
rpc(proxy.scheduler.device_types.set_template, name, template)
return f"template of device-type '{name}' updated"
@mcp.tool(annotations=READ_ONLY)
def device_type_health_check(name: str) -> str:
"""Return the health-check job definition of one device-type.
The health-check is the job LAVA submits by itself, on a schedule, to
tell whether the devices of this device-type still work. A device
failing it goes to the BAD health and stops taking jobs.
Not every device-type has one: the call fails when there is none.
Args:
name: Device-type name, e.g. 'qemu'
"""
return str(rpc(proxy.scheduler.device_types.get_health_check, name))
###########
# Devices #
###########
@mcp.tool(annotations=READ_ONLY)
def devices_list(all_devices: bool = False) -> list:
"""List the devices of the instance.
A device is one board, attached to a worker and running the jobs
submitted for its device-type.
Args:
all_devices: Include the retired devices (default: False)
Returns:
One entry per device with its hostname, device-type, state,
health and current job.
"""
return rpc(proxy.scheduler.devices.list, all_devices)
@mcp.tool(annotations=READ_ONLY)
def device_show(name: str) -> dict:
"""Show the details of one device.
Args:
name: Device hostname, e.g. 'qemu-01'
Returns:
The hostname, device-type, state, health, description, worker,
tags, current job and whether a device dictionary is set.
"""
return rpc(proxy.scheduler.devices.show, name)
@mcp.tool(annotations=READ_ONLY)
def device_dictionary(name: str, render: bool = True) -> str:
"""Return the device dictionary of one device.
The dictionary holds the per-device configuration the dispatcher
needs: the power commands, the serial connection and the bootloader
settings.
Args:
name: Device hostname, e.g. 'qemu-01'
render: Render the jinja2 template into the final yaml
configuration, instead of returning the template
(default: True)
"""
return str(rpc(proxy.scheduler.devices.get_dictionary, name, render, None))
@mcp.tool(annotations=WRITE)
def device_dictionary_set(name: str, config: str) -> str:
"""Replace the device dictionary of one device.
The dictionary is picked up by every job started on that device from
then on: read the current one with device_dictionary(render=False),
which returns the jinja2 source this tool expects back, and keep
everything that is not being changed.
Args:
name: Device hostname, e.g. 'qemu-01'
config: The whole jinja2 dictionary, not a patch of it. It extends
the template of the device-type, so it usually starts with
'{% extends "qemu.jinja2" %}'.
"""
if not rpc(proxy.scheduler.devices.set_dictionary, name, config):
raise ToolError(f"unable to set the dictionary of device '{name}'")
return f"dictionary of device '{name}' updated"
###########
# Workers #
###########
@mcp.tool(annotations=READ_ONLY)
def workers_list(all_workers: bool = False) -> list:
"""List the workers of the instance.
A worker is a machine running lava-dispatcher: it drives the devices
attached to it and runs their jobs.
Args:
all_workers: Include the retired workers (default: False).
Ignored by servers older than 2023.3.
"""
if version >= (2023, 3):
return rpc(proxy.scheduler.workers.list, all_workers)
return rpc(proxy.scheduler.workers.list)
@mcp.tool(annotations=READ_ONLY)
def worker_show(name: str) -> dict:
"""Show the details of one worker.
Args:
name: Worker hostname, e.g. 'worker-01'
Returns:
The hostname, description, state, health, the devices attached to
it and the last time it pinged the server.
"""
worker = rpc(proxy.scheduler.workers.show, name)
# The token lets anyone holding it act as the worker: it has no
# reason to be handed over to an LLM.
worker.pop("token", None)
return worker
#################
# Documentation #
#################
# The documentation of the release the instance runs, or the development
# branch for a development build. The version string is needed: the
# parsed version drops the '.devNNNN' suffix of development builds.
doc_ref = docs.ref_for_version(config.get("server_version"))
@mcp.tool(annotations=READ_ONLY)
def documentation_list() -> dict[str, str]:
"""List the pages of the official LAVA documentation.
The pages are the ones of the LAVA version this instance runs.
Returns:
A mapping of page name -> page title. Page names are the argument
expected by documentation_fetch, e.g. 'admin/first-steps'.
"""
try:
return docs.pages(doc_ref)
except (OSError, ValueError) as exc:
raise ToolError(f"unable to list the documentation: {exc}") from exc
@mcp.tool(annotations=READ_ONLY)
def documentation_fetch(page: str) -> str:
"""Download one page of the official LAVA documentation, as markdown.
Covers the job definition format, the test definitions, the device
dictionaries, the scheduler and the administration of an instance.
Args:
page: Page name from documentation_list, e.g.
'user/basic-tutorials/job-definition'
"""
try:
return docs.fetch(page, doc_ref)
except (OSError, ValueError) as exc:
raise ToolError(str(exc)) from exc
###########
# Prompts #
###########
def scope(device_type, worker):
"""Describe the devices a prompt is restricted to."""
parts = []
if device_type:
parts.append(f"of the device-type '{device_type}'")
if worker:
parts.append(f"attached to the worker '{worker}'")
return " ".join(parts)
def scope_filters(device_type, worker):
"""Render the filters of a prompt as tool arguments."""
return "".join(
f", {key}='{value}'"
for key, value in (("device_type", device_type), ("worker", worker))
if value
)
@mcp.prompt()
def devices_status(
hours: int = 24, device_type: str | None = None, worker: str | None = None
) -> str:
"""Report the status of the devices from the jobs of the last hours.
Args:
hours: Look at the jobs that finished in the last N hours
(default: 24)
device_type: Only look at the devices of this device-type
worker: Only look at the devices attached to this worker
"""
since = hours * 60
devices = scope(device_type, worker)
filters = scope_filters(device_type, worker)
return f"""Look at the jobs that finished in the last {hours} hours on the \
LAVA instance at {instance}{" for the devices " + devices if devices else ""}. \
Group the failures by root cause and, for each group, tell me which \
device-types and devices are affected and whether it looks like an \
infrastructure or a test issue. Then tell me which devices fail the most.
1. Read the documentation with \
documentation_fetch(page='user/advanced-tutorials/debugging-job'): it lists \
the common failures and how to recognize them in the logs.
2. Rank the devices with jobs_stats(since={since}{filters}). Rank them by \
failure rate, not by number of failures: a device running many jobs fails more \
often without being worse than the others.
3. List the failing jobs with jobs_list(health='INCOMPLETE', since={since}, \
verbose=True{filters}). Keep reading while the answer is full, and never take \
an answer ending with 'scan_limit_reached' for the complete list.
4. For each failure, read the end of its log with job_logs(start=-100) and, \
when that is not enough, the lines before. Read job_definition to know what \
was under test (the images, the firmware or kernel builds) and device_show \
to know whether the device is still usable.
5. Group the failures by root cause, from what the logs show, not from the \
error_type or the error_msg alone: LAVA sometimes labels a dead board or a \
power failure as a Test error.
6. Decide between infrastructure and test for each group:
* a health-check (submitter 'lava-health') runs a known-good image: when it \
fails, suspect the board, its power control or its serial line;
* compare the failing device with the other devices of its device-type, \
with jobs_list(device_type=..., since={since}) or jobs_stats: a failure seen on \
one board only points at that board, the same failure on every board points at \
the job or the software under test;
* compare the devices of the same worker: failures shared by every device \
of a worker point at the worker, failures of a few devices at their own \
hardware or configuration;
* failures of many devices within a few minutes point at a shared \
resource, like a download server or the network.
When a device shows hardware or power failures, read its \
device_dictionary(render=False): a wrong value (port, serial number, \
command copied from another device) explains failures that the logs alone do \
not.
7. When the window holds too few failures to tell, say so and widen it.
Answer with one section per root cause (the jobs, device-types and devices \
affected, what happened, the infrastructure or test verdict and why, how \
confident you are), then a table of the devices ranked by failure rate and \
the next steps. Do not change the instance: no job submission, cancellation or \
configuration change without asking first."""
@mcp.prompt()
def device_dictionaries_review(
device_type: str | None = None, worker: str | None = None
) -> str:
"""Look for mistakes in the device dictionaries of the devices.
Args:
device_type: Only review the devices of this device-type
worker: Only review the devices attached to this worker
"""
devices = scope(device_type, worker)
filters = scope_filters(device_type, worker)
if device_type:
listing = f"device_type_devices(name='{device_type}')"
else:
listing = "devices_list()"
if worker:
listing += f", keeping the devices listed by worker_show(name='{worker}')"
return f"""Look at the device dictionary of every \
device{" " + devices if devices else ""} of the LAVA instance at {instance} \
and find the configuration mistakes, like a value copied from another device \
and never updated.
1. List the devices with {listing}. Leave out the retired devices.
2. Read the dictionary of each one with device_dictionary(render=False): it \
holds the per-device values, without the device-type template around them.
3. Within each device-type, compare the values of every device, line by line. \
A device usually differs from its siblings only by its own resources: a value \
that matches a sibling's resource, or a command not using the device's own \
values, is suspicious. For instance a power or reset command reaching another \
device's port, or a serial number that is not the one the device declares \
elsewhere in its dictionary. Check if the two devices are on the same worker \
or not as two devices on two different workers, might use the exact same \
commands. \
4. Across every device read, look for a physical resource assigned to two \
devices: servo or debug ports, serial numbers of the boards and the debug \
cables, console ports on each worker, PDU outlets and relays, USB hub ports, \
SD-mux ids, IP and MAC addresses.
5. Also report the commands that cannot work: an empty power-off command, a \
reset that never powers the board off, a command that only echoes.
6. For each suspicious device, check with jobs_stats(since=10080{filters}) and \
jobs_list(device=..., health='INCOMPLETE', since=10080, verbose=True) whether \
it fails, and whether the logs show the wrong value in use.
Answer with a table of the findings ranked by severity: a bug causing \
failures, a mistake not failing yet, probably deliberate, cosmetic. For each \
one, give the devices, the faulty lines and the value they should have when \
it is known. Say how many dictionaries were read and which checks found \
nothing. Do not change any device dictionary: propose the fix and wait for a \
confirmation."""
# Could be removed once
# https://github.com/modelcontextprotocol/python-sdk/issues/2663 is merged
signal.signal(signal.SIGINT, lambda *_: os._exit(0))
mcp.run(options.transport, **run_args)
return 0
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/results.py 0000664 0000000 0000000 00000006221 15265406512 0026257 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/system.py 0000664 0000000 0000000 00000011733 15265406512 0026106 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 time
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")
# "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_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())
return 0
def handle(proxy, options, config):
handlers = {
"active": handle_active,
"api": handle_api,
"certificate": handle_certificate,
"maintenance": handle_maintenance,
"methods": handle_methods,
"version": handle_version,
"whoami": handle_whoami,
}
return handlers[options.sub_sub_command](proxy, options, config)
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/tags.py 0000664 0000000 0000000 00000007151 15265406512 0025517 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/tokens.py 0000664 0000000 0000000 00000006043 15265406512 0026063 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/users.py 0000664 0000000 0000000 00000026172 15265406512 0025726 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/utils.py 0000664 0000000 0000000 00000011532 15265406512 0025717 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(
"--quiet",
default=False,
action="store_true",
help="only print the job phases (deploy, boot, ...) and the DUT output",
)
logs_print.add_argument(
"--job-definition",
default=None,
type=argparse.FileType("r"),
help="job definition for quiet printing",
)
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):
quiet = None
if options.quiet:
quiet = jobs.QuietFilter(safe_yaml.load(options.job_definition.read()))
if options.filename.name == "":
for line in options.filename:
try:
jobs.print_logs(
[safe_yaml.load(line)], options.raw, options.filters, quiet
)
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, quiet)
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/commands/workers.py 0000664 0000000 0000000 00000031355 15265406512 0026260 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 binary2str, 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(binary2str(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(binary2str(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(binary2str(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(binary2str(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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/docs.py 0000664 0000000 0000000 00000017557 15265406512 0023723 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2026 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
"""Access the official LAVA documentation.
The documentation is published on https://lava.readthedocs.io but built from
the markdown sources of the lava repository: they are read straight from
GitLab, so no markup has to be stripped. The list of pages comes from the
navigation of the mkdocs configuration.
"""
import posixpath
import re
from urllib.parse import quote
import requests
from ruamel.yaml import YAML
PROJECT = "lava/lava"
API_URL = "https://gitlab.com/api/v4/projects"
DEFAULT_REF = "master"
TIMEOUT = (10, 10)
CONFIG = "doc/mkdocs.yml"
CONTENT = "doc/content"
SNIPPETS = "doc/content/_snippets"
# mkdocs includes another file with '--8<-- "name"', or with a block listing
# one file per line between two '--8<--' markers.
SNIPPET = re.compile(r'^([ \t]*)--8<--[ \t]*"([^"]+)"[ \t]*$', re.MULTILINE)
SNIPPET_BLOCK = re.compile(
r"^([ \t]*)--8<--[ \t]*\n(.*?)^[ \t]*--8<--[ \t]*$", re.MULTILINE | re.DOTALL
)
# A LAVA release version, also the name of its git tag: '2026.09' or a bugfix
# release like '2022.01.1'.
RELEASE = re.compile(r"^20\d{2}\.\d{2}(\.\d+)?$")
# includes max depth (to be safe)
MAX_DEPTH = 5
# The target of a markdown link pointing at another page, with its optional
# anchor. Only '.md' targets match, so images, reference definitions and the
# content of the code blocks are left alone.
LINK = re.compile(r"\]\(([^)\s]+\.md(?:#[^)\s]*)?)\)")
# mkdocs.yml holds '!!python/name:' tags that no safe loader knows about.
# Only the navigation is needed: ignore the rest instead of failing.
_yaml = YAML(typ="safe")
_yaml.constructor.add_multi_constructor("", lambda loader, suffix, node: None)
# The documentation changes per release, not per minute: cache for the
# lifetime of the process.
_refs: dict[str, str] = {}
_pages_cache: dict[str, dict[str, str]] = {}
_source_cache: dict[tuple[str, str], str] = {}
_snippet_cache: dict[tuple[str, str], str] = {}
def _get(path, ref):
"""Return one file of the lava repository, at the given ref."""
url = (
f"{API_URL}/{quote(PROJECT, safe='')}"
f"/repository/files/{quote(path, safe='')}/raw"
)
response = requests.get(url, params={"ref": ref}, timeout=TIMEOUT)
response.raise_for_status()
return response.text
def _is_missing(exc):
return exc.response is not None and exc.response.status_code == 404
def _check(page):
"""Return a page name usable as a path, or fail."""
# The links of a page carry the anchor of the section they point at.
page = page.partition("#")[0]
page = page.strip("/").removesuffix(".html").removesuffix(".md")
# 'page' comes from the caller: keep it inside the documentation.
if ".." in page.split("/"):
raise ValueError(f"invalid page name '{page}': expected e.g. 'admin/basics'")
return page if page else "index"
def _snippets(text, ref, depth=0):
"""Replace the mkdocs includes of 'text' by the files they point at."""
if depth >= MAX_DEPTH:
return text
def include(name, indent):
name = name.strip()
if not name or ".." in name.split("/"):
return indent + name
key = (ref, name)
if key not in _snippet_cache:
try:
_snippet_cache[key] = _get(f"{SNIPPETS}/{name}", ref)
except requests.HTTPError as exc:
if not _is_missing(exc):
raise
# Leave the include alone rather than dropping content.
return f'{indent}--8<-- "{name}"'
body = _snippets(_snippet_cache[key], ref, depth + 1)
return "\n".join(indent + line for line in body.rstrip("\n").split("\n"))
def one(match):
return include(match.group(2), match.group(1))
def block(match):
indent = match.group(1)
return "\n".join(
include(name, indent) for name in match.group(2).split("\n") if name.strip()
)
return SNIPPET.sub(one, SNIPPET_BLOCK.sub(block, text))
def _links(text, page):
"""Rewrite the links of a page into the page names fetch() expects.
mkdocs links pages by relative path, e.g. '../../foo/bar.md' from
'a/b/page.md', which is 'foo/bar' here.
"""
base = posixpath.dirname(page)
def rewrite(match):
target = match.group(1)
path, sep, anchor = target.partition("#")
# Another website that happens to serve a '.md' file.
if "://" in path or path.startswith("/"):
return match.group(0)
name = posixpath.normpath(posixpath.join(base, path)).removesuffix(".md")
# A link out of the documentation is left as it is.
if name.startswith(".."):
return match.group(0)
return f"]({name}{sep}{anchor})"
return LINK.sub(rewrite, text)
def pages(ref=DEFAULT_REF):
"""Return every documentation page as {page name: title}."""
resolved = _refs.get(ref, ref)
if resolved in _pages_cache:
return dict(_pages_cache[resolved])
try:
config = _get(CONFIG, resolved)
except requests.HTTPError as exc:
if resolved == DEFAULT_REF or not _is_missing(exc):
raise
# An unreleased version has no tag: fall back to the branch.
resolved = DEFAULT_REF
config = _get(CONFIG, resolved)
_refs[ref] = resolved
found = {}
def walk(node):
if isinstance(node, dict):
entries = list(node.items())
elif isinstance(node, list):
entries = [(None, item) for item in node]
else:
return
for title, value in entries:
# A nav entry is either 'title: page.md' or a nested section.
if isinstance(value, str):
if value.endswith(".md"):
name = value.removesuffix(".md")
found[name] = title if title else name
else:
walk(value)
walk((_yaml.load(config) or {}).get("nav"))
if not found:
raise ValueError("Empty documentation index")
_pages_cache[resolved] = found
return dict(found)
def fetch(page, ref=DEFAULT_REF):
"""Return the markdown of one documentation page.
'page' is a name as returned by pages(), e.g. 'admin/first-steps'.
"""
page = _check(page)
if ref not in _refs:
# Resolves the ref, falling back to the branch for an unknown tag.
pages(ref)
resolved = _refs[ref]
if (resolved, page) not in _source_cache:
try:
text = _get(f"{CONTENT}/{page}.md", resolved)
except requests.HTTPError as exc:
if not _is_missing(exc):
raise
raise ValueError(f"no such documentation page: '{page}'") from exc
# The snippets are inlined first: their links are page links too.
_source_cache[(resolved, page)] = _links(_snippets(text, resolved), page)
return _source_cache[(resolved, page)]
def ref_for_version(version):
"""Return the git ref of a LAVA version string.
A release is its own tag: '2026.09' -> '2026.09', '2022.01.1' ->
'2022.01.1'. A development build ('2026.09.dev0130') runs commits made
after its tag, so it gets the development branch, like anything unknown.
"""
if isinstance(version, str) and RELEASE.match(version):
return version
return DEFAULT_REF
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/schemas.py 0000664 0000000 0000000 00000011716 15265406512 0024405 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/lavacli/utils.py 0000664 0000000 0000000 00000013652 15265406512 0024123 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
JOB_HEALTHS = ["UNKNOWN", "COMPLETE", "INCOMPLETE", "CANCELED"]
JOB_STATES = [
"SUBMITTED",
"SCHEDULING",
"SCHEDULED",
"RUNNING",
"CANCELING",
"FINISHED",
]
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 binary2str(value):
"""
Decode a file sent by the server over XML-RPC.
The server sends files as bytes, so they are received as Binary. Decode the
payload as utf-8.
"""
if isinstance(value, xmlrpc.client.Binary):
value = value.data
if isinstance(value, bytes):
return value.decode("utf-8")
return str(value)
def uri_hostname(uri):
"""Return the hostname of an uri, dropping the username, token and port."""
return urlparse(uri).hostname or ""
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)
# Advance by what the server actually returned, not by what was asked.
start += len(job_ids)
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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/pyproject.toml 0000664 0000000 0000000 00000004362 15265406512 0023710 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2026-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
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "lavacli"
dynamic = ["version"]
description = "LAVA XML-RPC command line interface"
readme = "README.md"
authors = [{name = "Rémi Duraffort", email = "remi.duraffort@linaro.org"}]
license = {text = "AGPLv3+"}
requires-python = ">=3.11"
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.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Communications",
"Topic :: Software Development :: Testing",
"Topic :: System :: Networking",
]
dependencies = [
"aiohttp",
"jinja2",
"requests",
"ruamel.yaml",
"voluptuous",
]
optional-dependencies.mcp = ["mcp<2"]
[project.urls]
Homepage = "https://gitlab.com/lava/lavacli"
"Bug Tracker" = "https://gitlab.com/lava/lavacli/issues/"
"Source Code" = "https://gitlab.com/lava/lavacli/"
[project.scripts]
lavacli = "lavacli:main"
[dependency-groups]
dev = [
"black",
"pylint",
"pytest",
"pytest-cov",
"pyzmq",
]
doc = [
"sphinx",
"sphinx-autobuild",
]
[tool.setuptools]
packages = ["lavacli", "lavacli.commands"]
[tool.setuptools.dynamic]
version = {attr = "lavacli.__about__.__version__"}
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/requirements.txt 0000664 0000000 0000000 00000000057 15265406512 0024255 0 ustar 00root root 0000000 0000000 aiohttp
jinja2
requests
ruamel.yaml
voluptuous
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/share/ 0000775 0000000 0000000 00000000000 15265406512 0022071 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/share/lavacli.yaml 0000664 0000000 0000000 00000001506 15265406512 0024372 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/share/release.sh 0000775 0000000 0000000 00000003705 15265406512 0024055 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 --ignore-branch --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..."
uv build --sdist
gbp buildpackage --git-ignore-branch -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 "* uv publish dist"
read
uv publish dist/*
echo "done"
echo
fi
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/ 0000775 0000000 0000000 00000000000 15265406512 0022131 5 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/__init__.py 0000664 0000000 0000000 00000000000 15265406512 0024230 0 ustar 00root root 0000000 0000000 lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/conftest.py 0000664 0000000 0000000 00000003701 15265406512 0024331 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_aliases.py 0000664 0000000 0000000 00000021426 15265406512 0025170 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_device_types.py 0000664 0000000 0000000 00000047137 15265406512 0026241 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_devices.py 0000664 0000000 0000000 00000100562 15265406512 0025170 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_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),
# The server sends the dictionary as bytes: it is received
# as Binary.
"ret": xmlrpc.client.Binary("yaml_dict é".encode("utf-8")),
},
],
)
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 safe_yaml.load(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_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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_docs.py 0000664 0000000 0000000 00000016354 15265406512 0024503 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2026 Rémi Duraffort
# This file is part of lavacli.
#
# lavacli is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# lavacli is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with lavacli. If not, see
import pytest
import requests
from lavacli import docs
# mkdocs.yml holds tags that no safe loader knows about: they have to be
# ignored, not to make the whole file unreadable.
MKDOCS = """
site_name: LAVA Documentation
docs_dir: content/
markdown_extensions:
- pymdownx.superfences:
custom_fences:
- name: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
nav:
- Home: index.md
- User guide:
- First steps: user/first-steps.md
- Basic tutorials:
- Job definition: user/basic-tutorials/job-definition.md
- Changelog: https://example.com/changelog
"""
PAGE = """# Job definition
Let's look at this example:
```yaml
--8<-- "jobs/qemu.yaml"
```
Read [the job](../technical-references/job.md) reference, its
[priority](../technical-references/job.md#priority), the
[index](../index.md), an [image](../assets/logo.png), a
[site](https://example.com/README.md) and an [anchor](#example).
--8<--
refs.txt
--8<--
"""
PAGE_MD = """# Job definition
Let's look at this example:
```yaml
device_type: qemu
job_name: simple qemu job
```
Read [the job](user/technical-references/job) reference, its
[priority](user/technical-references/job#priority), the
[index](user/index), an [image](../assets/logo.png), a
[site](https://example.com/README.md) and an [anchor](#example).
[bandit]: https://bandit.readthedocs.io/
*[DUT]: Device Under Test
"""
FILES = {
"doc/mkdocs.yml": MKDOCS,
"doc/content/user/basic-tutorials/job-definition.md": PAGE,
"doc/content/index.md": "# Welcome\n",
"doc/content/_snippets/jobs/qemu.yaml": "device_type: qemu\njob_name: simple qemu job\n",
# An include of includes: that is how the documentation pulls its links.
"doc/content/_snippets/refs.txt": "--8<--\nlinks.txt\nabbr.txt\n--8<--\n",
"doc/content/_snippets/links.txt": "[bandit]: https://bandit.readthedocs.io/\n",
"doc/content/_snippets/abbr.txt": "*[DUT]: Device Under Test\n",
}
@pytest.fixture(autouse=True)
def caches(monkeypatch):
monkeypatch.setattr(docs, "_refs", {})
monkeypatch.setattr(docs, "_pages_cache", {})
monkeypatch.setattr(docs, "_source_cache", {})
monkeypatch.setattr(docs, "_snippet_cache", {})
def http_error(status_code):
response = requests.Response()
response.status_code = status_code
return requests.HTTPError(response=response)
@pytest.fixture
def gitlab(monkeypatch):
"""Serve FILES, recording every (path, ref) that was asked for."""
calls = []
def get(path, ref):
calls.append((path, ref))
# Only 'master' and the '2026.07' tag exist.
if ref not in ("master", "2026.07"):
raise http_error(404)
if path not in FILES:
raise http_error(404)
return FILES[path]
monkeypatch.setattr(docs, "_get", get)
return calls
def test_pages(gitlab):
assert docs.pages() == { # nosec
"index": "Home",
"user/first-steps": "First steps",
"user/basic-tutorials/job-definition": "Job definition",
}
assert gitlab == [("doc/mkdocs.yml", "master")] # nosec
# The configuration is downloaded once per process.
assert docs.pages() == docs.pages() # nosec
assert len(gitlab) == 1 # nosec
def test_pages_without_nav(monkeypatch, gitlab):
monkeypatch.setitem(docs._pages_cache, "unused", {})
monkeypatch.setattr(docs, "_get", lambda path, ref: "site_name: LAVA\n")
with pytest.raises(ValueError, match="Empty documentation index"):
docs.pages()
def test_fetch(gitlab):
# The snippets are inlined, the nested ones too.
assert docs.fetch("user/basic-tutorials/job-definition") == PAGE_MD # nosec
# The '.md' suffix and the leading '/' are accepted too, and the page is
# downloaded only once.
before = len(gitlab)
assert docs.fetch("/user/basic-tutorials/job-definition.md") == PAGE_MD # nosec
assert len(gitlab) == before # nosec
def test_fetch_root(gitlab):
assert docs.fetch("/") == "# Welcome\n" # nosec
assert ("doc/content/index.md", "master") in gitlab # nosec
def test_fetch_unknown_page(gitlab):
with pytest.raises(ValueError, match="no such documentation page: 'nope'"):
docs.fetch("nope")
@pytest.mark.parametrize("page", ["../../../etc/passwd", "a/../../b", "..", "a/../b"])
def test_fetch_outside_the_documentation(gitlab, page):
with pytest.raises(ValueError, match="invalid page name"):
docs.fetch(page)
def test_fetch_server_error(monkeypatch, gitlab):
def get(path, ref):
raise http_error(500)
monkeypatch.setattr(docs, "_get", get)
with pytest.raises(requests.HTTPError):
docs.fetch("index")
def test_fetch_keeps_an_unknown_snippet(monkeypatch, gitlab):
monkeypatch.setitem(FILES, "doc/content/index.md", '--8<-- "gone.yaml"\n')
try:
assert docs.fetch("index") == '--8<-- "gone.yaml"\n' # nosec
finally:
FILES["doc/content/index.md"] = "# Welcome\n"
def test_released_version(gitlab):
assert len(docs.pages("2026.07")) == 3 # nosec
docs.fetch("index", "2026.07")
# Everything is read at the tag of the release the instance runs.
assert {ref for _, ref in gitlab} == {"2026.07"} # nosec
def test_unreleased_version_falls_back_to_master(gitlab):
assert len(docs.pages("9999.01")) == 3 # nosec
assert gitlab == [ # nosec
("doc/mkdocs.yml", "9999.01"),
("doc/mkdocs.yml", "master"),
]
# The fallback is remembered: the missing tag is not asked for again.
docs.fetch("index", "9999.01")
assert gitlab[-1] == ("doc/content/index.md", "master") # nosec
@pytest.mark.parametrize(
"version,ref",
[
("2026.09", "2026.09"),
("2026.11", "2026.11"),
("2022.01.1", "2022.01.1"),
# Development builds run commits made after their tag.
("2026.09.dev0130", "master"),
("2026.09-dirty", "master"),
(None, "master"),
((2026, 9), "master"),
],
)
def test_ref_for_version(version, ref):
assert docs.ref_for_version(version) == ref # nosec
def test_fetch_accepts_a_link_target(gitlab):
"""A rewritten link, pasted as it is, has to be fetchable."""
assert docs.fetch("index#welcome") == "# Welcome\n" # nosec
assert ("doc/content/index.md", "master") in gitlab # nosec
def test_links_out_of_the_documentation_are_kept(monkeypatch, gitlab):
# 'index' sits at the root: '../' escapes the documentation.
monkeypatch.setitem(FILES, "doc/content/index.md", "[x](../setup.md)\n")
try:
assert docs.fetch("index") == "[x](../setup.md)\n" # nosec
finally:
FILES["doc/content/index.md"] = "# Welcome\n"
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_events.py 0000664 0000000 0000000 00000057703 15265406512 0025062 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_helpers.py 0000664 0000000 0000000 00000004660 15265406512 0025212 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 xmlrpc.client
import pytest
from lavacli.utils import VERSION_LATEST, binary2str, parse_version, uri_hostname
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
def test_binary2str():
# The server sends files as bytes: they are received as Binary, whose
# str() would decode them as latin-1.
data = "device — élan\n"
assert binary2str(xmlrpc.client.Binary(data.encode("utf-8"))) == data # nosec
assert binary2str(data.encode("utf-8")) == data # nosec
# Older servers sending a plain string are left untouched.
assert binary2str(data) == data # nosec
@pytest.mark.parametrize(
"uri,hostname",
[
("https://lava.example.com/RPC2", "lava.example.com"),
("https://lava.example.com:8080/RPC2", "lava.example.com"),
("https://user:token@lava.example.com/RPC2", "lava.example.com"),
("https://user:token@lava.example.com:8080/RPC2", "lava.example.com"),
# A token is not url-encoded by lavacli: it can hold an '@' itself.
("https://user:to@ken@lava.example.com/RPC2", "lava.example.com"),
("https://user:token@[::1]:8080/RPC2", "::1"),
("not-an-uri", ""),
],
)
def test_uri_hostname(uri, hostname):
assert uri_hostname(uri) == hostname # nosec
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_identities.py 0000664 0000000 0000000 00000016520 15265406512 0025707 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_jobs.py 0000664 0000000 0000000 00000213010 15265406512 0024474 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.commands.jobs import QuietFilter
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",),
# The server sends the files as bytes: they are received as
# Binary. A file that the job did not use is None.
"ret": [
xmlrpc.client.Binary("definition é".encode("utf-8")),
xmlrpc.client.Binary(b"device"),
xmlrpc.client.Binary(b"dispatcher"),
xmlrpc.client.Binary(b"env"),
None,
],
},
],
)
assert main() == 0 # nosec
assert capsys.readouterr()[0] == "" # nosec
with (tmp_path / "definition.yaml").open(encoding="utf-8") as f_in:
assert f_in.read() == "definition é" # nosec
with (tmp_path / "device.yaml").open(encoding="utf-8") as f_in:
assert f_in.read() == "device" # nosec
with (tmp_path / "dispatcher.yaml").open(encoding="utf-8") as f_in:
assert f_in.read() == "dispatcher" # nosec
with (tmp_path / "env.yaml").open(encoding="utf-8") as f_in:
assert f_in.read() == "env" # nosec
assert not (tmp_path / "env.dut.yaml").exists() # 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": "Finished",
"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: Finished,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": "Finished",
"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": "Finished",
"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": "Finished",
"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 safe_yaml.load(capsys.readouterr()[0]) == [ # nosec
{
"id": "16",
"description": "hello",
"device_type": "bbb",
"health": "Complete",
"state": "Finished",
"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_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 safe_yaml.load(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_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]
def test_jobs_submit_follow_quiet(setup, monkeypatch, capsys, tmp_path):
version = "2019.1"
definition = """
device_type: bcm2837-rpi-3-b-32
job_name: quiet
actions:
- deploy:
to: tftp
kernel:
url: http://example.com/zImage
type: zimage
nfsrootfs:
url: http://example.com/rootfs.tar.xz
dtb:
url: http://example.com/bcm2837.dtb
- boot:
method: u-boot
commands: nfs
prompts: ["/ #"]
- test:
definitions:
- name: smoke-tests
repository: http://example.com/tests.git
from: git
path: smoke.yaml
"""
with (tmp_path / "job.yaml").open("w") as f_out:
f_out.write(definition)
monkeypatch.setattr(
sys,
"argv",
[
"lavacli",
"jobs",
"submit",
"--follow",
"--quiet",
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": (definition,),
"ret": 5689,
},
{
"request": "scheduler.jobs.definition",
"args": ("5689",),
"ret": definition,
},
{
"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"}
- {"dt": "2018-04-23T12:07:02.572789", "lvl": "info", "msg": "start: 1 tftp-deploy (timeout 00:05:00) [common]"}
- {"dt": "2018-04-23T12:07:02.573414", "lvl": "debug", "msg": "start: 1.1 download-retry (timeout 00:02:00) [common]"}
- {"dt": "2018-04-23T12:07:03.573414", "lvl": "info", "msg": "downloading http://example.com/zImage"}
- {"dt": "2018-04-23T12:07:03.673414", "lvl": "debug", "msg": "saving as /var/lib/lava/dispatcher/tmp/5689/zImage"}
- {"dt": "2018-04-23T12:07:03.723414", "lvl": "info", "msg": "progress 50% (4194304 bytes)"}
- {"dt": "2018-04-23T12:07:03.743414", "lvl": "info", "msg": "8MB downloaded in 0.17s (47.06MB/s)"}
- {"dt": "2018-04-23T12:07:03.773414", "lvl": "results", "msg": {"case": "validate", "definition": "lava", "result": "pass"}}
- {"dt": "2018-04-23T12:07:04.573414", "lvl": "info", "msg": "start: 2 uboot-action (timeout 00:10:00) [common]"}
- {"dt": "2018-04-23T12:07:05.573414", "lvl": "target", "msg": "Welcome to Buildroot"}
- {"dt": "2018-04-23T12:07:05.673414", "lvl": "debug", "msg": {"sending": "lava-test-runner"}}
- {"dt": "2018-04-23T12:07:05.773414", "lvl": "results", "msg": {"case": "lscpu", "definition": "smoke-tests", "result": "pass", "measurement": "1.05", "units": "s"}}
- {"dt": "2018-04-23T12:07:06.573414", "lvl": "info", "msg": "start: 3 lava-test-retry (timeout 00:05:00) [common]"}
- {"dt": "2018-04-23T12:07:07.573414", "lvl": "info", "msg": "start: 4 finalize (timeout 00:01:00) [common]"}
- {"dt": "2018-04-23T12:07:08.573414", "lvl": "error", "msg": "Test failed"}""",
),
},
{
"request": "scheduler.jobs.show",
"args": ("5689",),
"ret": {
"id": "5689",
"description": "desc",
"device": "rpi3",
"device_type": "bcm2837-rpi-3-b-32",
"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": "job failed",
},
},
],
)
assert main() == 0 # nosec
# The lines are prefixed by the timestamp (19 characters) and a space
lines = [line[20:] for line in capsys.readouterr()[0].split("\n")[:-1]]
assert lines == [ # nosec
"1. deploy to tftp (kernel, nfsrootfs, dtb)",
" \u2192 http://example.com/zImage",
" 8MB downloaded in 0.17s (47.06MB/s)",
" \u2713 lava.validate: pass",
"2. boot with u-boot (nfs)",
"Welcome to Buildroot",
"lava-test-runner",
" \u2713 smoke-tests.lscpu: pass (1.05s)",
"3. test (smoke-tests)",
"4. finalize",
"Test failed",
"[lavacli] Failure comment: job failed",
]
def test_jobs_logs_quiet_flasher(setup, monkeypatch, capsys):
version = "2019.1"
now = xmlrpc.client.DateTime("20180128T01:01:01")
definition = """
device_type: kria
job_name: flash
actions:
- deploy:
to: flasher
images:
boot:
url: https://example.com/recovery-boot.bin
- boot:
method: minimal
"""
monkeypatch.setattr(sys, "argv", ["lavacli", "jobs", "logs", "--quiet", "414223"])
monkeypatch.setattr(
xmlrpc.client.ServerProxy,
"data",
[
{"request": "system.version", "args": (), "ret": version},
{
"request": "scheduler.jobs.definition",
"args": ("414223",),
"ret": definition,
},
{
"request": "scheduler.jobs.logs",
"args": ("414223", 0, None),
"ret": (
True,
"""- {"dt": "2018-04-23T12:07:02.569264", "lvl": "info", "msg": "start: 1 deploy-flasher-retry (timeout 00:20:00) [common]"}
- {"dt": "2018-04-23T12:07:02.669264", "lvl": "debug", "msg": "start: 1.1 deploy-flasher (timeout 00:20:00) [common]"}
- {"dt": "2018-04-23T12:07:03.569264", "lvl": "info", "msg": "downloading https://example.com/recovery-boot.bin"}
- {"dt": "2018-04-23T12:07:03.669264", "lvl": "debug", "msg": "saving as /var/lib/lava/dispatcher/tmp/414223/boot/recovery-boot.bin"}
- {"dt": "2018-04-23T12:07:03.769264", "lvl": "info", "msg": "progress 1 % (0 MB)"}
- {"dt": "2018-04-23T12:07:04.069264", "lvl": "info", "msg": "1 MB downloaded in 0.44 s (4.05 MB/s)"}
- {"dt": "2018-04-23T12:07:05.069264", "lvl": "debug", "msg": "Calling: ['laacli', 'power', '12v', 'off']"}
- {"dt": "2018-04-23T12:07:05.169264", "lvl": "debug", "msg": "Returned 0 in 0 seconds"}
- {"dt": "2018-04-23T12:07:06.069264", "lvl": "debug", "msg": "Calling: ['/usr/local/bin/kria-deploy.sh', '198.18.0.2', '.']"}
- {"dt": "2018-04-23T12:07:06.169264", "lvl": "debug", "msg": ">> Update Boot Image A with boot.bin\\nErasing 13312 Kibyte @ 0 -- 100 % complete"}
- {"dt": "2018-04-23T12:07:47.069264", "lvl": "debug", "msg": "Returned 0 in 41 seconds"}
- {"dt": "2018-04-23T12:07:48.069264", "lvl": "info", "msg": "start: 2 minimal-boot (timeout 00:05:00) [common]"}
- {"dt": "2018-04-23T12:07:48.169264", "lvl": "debug", "msg": "Calling: ['laacli', 'power', '12v', 'on']"}
- {"dt": "2018-04-23T12:07:49.069264", "lvl": "target", "msg": "Xilinx Zynq MP First Stage Boot Loader"}""",
),
},
{
"request": "scheduler.jobs.show",
"args": ("414223",),
"ret": {
"id": "414223",
"description": "flash",
"device": "kria01",
"device_type": "kria",
"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
# The lines are prefixed by the timestamp (19 characters) and a space,
# except the continuation lines of a multi lines message
lines = [
line[20:] if line[:4].isdigit() else line
for line in capsys.readouterr()[0].split("\n")[:-1]
]
assert lines == [ # nosec
"1. deploy to flasher (boot)",
" → https://example.com/recovery-boot.bin",
" 1 MB downloaded in 0.44 s (4.05 MB/s)",
" $ laacli power 12v off",
" Returned 0 in 0 seconds",
" $ /usr/local/bin/kria-deploy.sh 198.18.0.2 .",
" Update Boot Image A with boot.bin",
" Erasing 13312 Kibyte @ 0 -- 100 % complete",
" Returned 0 in 41 seconds",
"2. boot with minimal",
" $ laacli power 12v on",
"Xilinx Zynq MP First Stage Boot Loader",
]
def test_jobs_quiet_filter_results():
logs = [
{
"dt": "2018-04-23T12:07:05.1",
"lvl": "results",
"msg": {"case": "lscpu", "definition": "smoke-tests", "result": "pass"},
},
{
"dt": "2018-04-23T12:07:06.1",
"lvl": "results",
"msg": {"case": "ping", "definition": "smoke-tests", "result": "fail"},
},
]
# The failures are printed in red, using the "error" level
assert QuietFilter()(logs) == [ # nosec
{
"dt": "2018-04-23T12:07:05.1",
"lvl": "results",
"msg": " \u2713 smoke-tests.lscpu: pass",
},
{
"dt": "2018-04-23T12:07:06.1",
"lvl": "error",
"msg": " \u2717 smoke-tests.ping: fail",
},
]
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_lab.py 0000664 0000000 0000000 00000430225 15265406512 0024306 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_lavacli.py 0000664 0000000 0000000 00000003117 15265406512 0025157 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_mcp.py 0000664 0000000 0000000 00000103533 15265406512 0024326 0 ustar 00root root 0000000 0000000 # vim: set ts=4
# Copyright 2026 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
# pylint: disable=import-outside-toplevel
import asyncio
import json
import sys
import xmlrpc.client
import pytest
from lavacli import docs, main
from lavacli.commands import mcp as mcp_command
TOOLS = [
"device_dictionary",
"device_dictionary_set",
"device_show",
"device_type_devices",
"device_type_health_check",
"device_type_show",
"device_type_template",
"device_type_template_set",
"device_types_list",
"devices_list",
"documentation_fetch",
"documentation_list",
"job_cancel",
"job_definition",
"job_logs",
"job_metadata",
"job_results",
"job_show",
"job_submit",
"job_suites",
"jobs_list",
"jobs_queue",
"jobs_stats",
"worker_show",
"workers_list",
]
def server_class():
"""Return the FastMCP class, skipping the test without the mcp module."""
pytest.importorskip("mcp.server.fastmcp")
from mcp.server.fastmcp import FastMCP
return FastMCP
def tool_error():
from mcp.server.fastmcp.exceptions import ToolError
return ToolError
@pytest.fixture
def server(setup, monkeypatch):
"""Start 'lavacli mcp', catch the server instead of serving requests."""
cls = server_class()
started = {}
def fake_run(self, transport="stdio", **kwargs):
started["server"] = self
started["transport"] = transport
started["kwargs"] = kwargs
monkeypatch.setattr(cls, "run", fake_run)
def start(data, argv=None):
monkeypatch.setattr(sys, "argv", argv or ["lavacli", "mcp"])
monkeypatch.setattr(xmlrpc.client.ServerProxy, "data", data)
assert main() == 0 # nosec
return started
return start
def call(server, tool, /, **arguments):
"""Call one tool and return the text it answered, error included."""
try:
result = asyncio.run(server.call_tool(tool, arguments))
except tool_error() as exc:
return str(exc)
# mcp 1.x returns the content blocks (possibly with the structured
# output), mcp 2.x a CallToolResult.
content = getattr(result, "content", result)
if isinstance(content, tuple):
content = content[0]
return "".join(block.text for block in content if block.type == "text")
def version(value="2025.01"):
return {"request": "system.version", "args": (), "ret": value}
def logs_count(value, job_id="1234"):
return {"request": "scheduler.jobs.logs_count", "args": (job_id,), "ret": value}
def test_mcp_tools(server):
started = server([version()])
tools = asyncio.run(started["server"].list_tools())
assert sorted(tool.name for tool in tools) == TOOLS # nosec
assert started["transport"] == "stdio" # nosec
assert started["kwargs"] == {} # nosec
def test_mcp_streamable_http(server):
started = server(
[version()],
["lavacli", "mcp", "--transport", "streamable-http", "--port", "8080"],
)
assert started["transport"] == "streamable-http" # nosec
# FastMCP takes the transport options in the constructor.
assert started["server"].settings.host == "127.0.0.1" # nosec
assert started["server"].settings.port == 8080 # nosec
assert started["server"].settings.streamable_http_path == "/" # nosec
def test_mcp_devices_list(server):
devices = [
{
"hostname": "qemu-01",
"type": "qemu",
"state": "Idle",
"health": "Good",
"current_job": None,
}
]
started = server(
[
version(),
{"request": "scheduler.devices.list", "args": (False,), "ret": devices},
{"request": "scheduler.devices.list", "args": (True,), "ret": devices},
]
)
assert json.loads(call(started["server"], "devices_list")) == devices[0] # nosec
call(started["server"], "devices_list", all_devices=True)
def test_mcp_job_show(server):
started = server(
[
version(),
{
"request": "scheduler.jobs.show",
"args": ("1234",),
"ret": {
"id": 1234,
"state": "Finished",
"health": "Complete",
"submit_time": xmlrpc.client.DateTime("20260101T10:00:00"),
},
},
]
)
job = json.loads(call(started["server"], "job_show", job_id="1234"))
# The XML-RPC dates are not JSON serializable.
assert job["submit_time"] == "20260101T10:00:00" # nosec
def test_mcp_jobs_list_invalid_state(server):
started = server([version()])
assert "invalid state 'BOGUS'" in call( # nosec
started["server"], "jobs_list", state="BOGUS"
)
def job_entry(job_id, device, health="Complete", error_type=None, **kwargs):
entry = {
"id": job_id,
"actual_device": device,
"device_type": "qemu",
"submitter": "lava-health",
"health": health,
"error_type": error_type,
"error_msg": "failed" if error_type else None,
}
entry.update(kwargs)
return entry
def decode_all(answer):
"""Decode the JSON objects of a list answer, one text block each."""
decoder = json.JSONDecoder()
objects, index = [], 0
while index < len(answer):
obj, index = decoder.raw_decode(answer, index)
objects.append(obj)
return objects
def test_mcp_jobs_list(server):
started = server(
[
version(),
{
# The verbose answer is always requested: it carries the device
"request": "scheduler.jobs.list",
"args": (None, "INCOMPLETE", 0, 25, 0, True),
"ret": [job_entry(1, "qemu-01", "Incomplete", "Test")],
},
{
"request": "scheduler.jobs.list",
"args": (None, "INCOMPLETE", 0, 25, 0, True),
"ret": [job_entry(1, "qemu-01", "Incomplete", "Test")],
},
]
)
job = json.loads(call(started["server"], "jobs_list", health="INCOMPLETE"))
assert job["actual_device"] == "qemu-01" # nosec
assert "error_type" not in job and "error_msg" not in job # nosec
job = json.loads(
call(started["server"], "jobs_list", health="INCOMPLETE", verbose=True)
)
assert job["error_type"] == "Test" # nosec
def test_mcp_jobs_list_filters(server):
def page(start, ret):
return {
"request": "scheduler.jobs.list",
"args": ("FINISHED", None, start, 100, 60, True),
"ret": ret,
}
started = server(
[
version(),
page(
0,
[
job_entry(6, "qemu-01", "Incomplete", "Infrastructure"),
job_entry(5, "qemu-02", "Incomplete", "Infrastructure"),
job_entry(4, "qemu-01", submitter="ci"),
],
),
page(
3,
[
job_entry(3, "qemu-01", "Incomplete", "Infrastructure"),
job_entry(2, "qemu-01", "Incomplete", "Test"),
],
),
page(5, []),
]
)
jobs = decode_all(
call(
started["server"],
"jobs_list",
state="FINISHED",
since=60,
device="qemu-01",
submitter="lava-health",
error_type="Infrastructure",
start=1,
)
)
# Job 6 is skipped by start=1, the others do not match every filter
assert [job["id"] for job in jobs] == [3] # nosec
def test_mcp_jobs_list_filters_limit(server):
started = server(
[
version(),
{
"request": "scheduler.jobs.list",
"args": (None, None, 0, 100, 60, True),
"ret": [job_entry(i, "qemu-01") for i in range(3, 0, -1)],
},
]
)
# The search stops as soon as 'limit' jobs matched
jobs = decode_all(
call(started["server"], "jobs_list", since=60, device="qemu-01", limit=2)
)
assert [job["id"] for job in jobs] == [3, 2] # nosec
def test_mcp_jobs_list_filters_scan_limit(server, monkeypatch):
monkeypatch.setattr(mcp_command, "JOBS_SCAN_LIMIT", 2)
started = server(
[
version(),
{
"request": "scheduler.jobs.list",
"args": (None, None, 0, 100, 60, True),
"ret": [job_entry(2, "qemu-02"), job_entry(1, "qemu-01")],
},
]
)
jobs = decode_all(call(started["server"], "jobs_list", since=60, device="qemu-01"))
assert jobs[0]["id"] == 1 # nosec
assert jobs[-1] == {"scan_limit_reached": True, "scanned": 2} # nosec
def test_mcp_jobs_list_filters_without_since(server):
started = server([version()])
assert "'since' is required" in call( # nosec
started["server"], "jobs_list", device="qemu-01"
)
def worker_show(devices, name="worker-01"):
return {
"request": "scheduler.workers.show",
"args": (name,),
"ret": {"hostname": name, "devices": devices},
}
def test_mcp_jobs_list_worker(server):
started = server(
[
version(),
worker_show(["qemu-01", "qemu-03"]),
{
"request": "scheduler.jobs.list",
"args": (None, None, 0, 100, 60, True),
"ret": [
job_entry(3, "qemu-03"),
job_entry(2, "qemu-02"),
job_entry(1, "qemu-01", device_type="juno"),
],
},
{
"request": "scheduler.jobs.list",
"args": (None, None, 3, 100, 60, True),
"ret": [],
},
]
)
jobs = decode_all(
call(
started["server"],
"jobs_list",
since=60,
worker="worker-01",
device_type="qemu",
)
)
# qemu-02 is on another worker, job 1 is not a qemu job
assert [job["id"] for job in jobs] == [3] # nosec
def test_mcp_jobs_list_unknown_worker(server):
started = server(
[
version(),
{
"request": "scheduler.workers.show",
"args": ("worker-99",),
"ret": {"fault_code": 404},
},
]
)
assert "fault string" in call( # nosec
started["server"], "jobs_list", since=60, worker="worker-99"
)
def test_mcp_jobs_stats_worker(server):
started = server(
[
version(),
worker_show(["qemu-01"]),
{
"request": "scheduler.jobs.list",
"args": ("FINISHED", None, 0, 100, 1440, True),
"ret": [job_entry(2, "qemu-02"), job_entry(1, "qemu-01")],
},
{
"request": "scheduler.jobs.list",
"args": ("FINISHED", None, 2, 100, 1440, True),
"ret": [],
},
]
)
stats = json.loads(call(started["server"], "jobs_stats", worker="worker-01"))
assert stats["device"] == "qemu-01" # nosec
assert stats["total"] == 1 # nosec
def test_mcp_jobs_stats(server):
def job(device, health, error_type=None, device_type="qemu"):
return {
"actual_device": device,
"device_type": device_type,
"health": health,
"error_type": error_type,
}
def jobs_list(start, ret):
return {
"request": "scheduler.jobs.list",
"args": ("FINISHED", None, start, 100, 60, True),
"ret": ret,
}
started = server(
[
version(),
jobs_list(
0,
[
job("qemu-01", "Complete"),
job("qemu-01", "Incomplete", "Infrastructure"),
job("qemu-02", "Complete"),
# Canceled before being scheduled: no device
job(None, "Canceled"),
],
),
jobs_list(
4,
[
job("qemu-01", "Canceled"),
job("juno-01", "Incomplete", "Test", "juno"),
],
),
jobs_list(6, []),
]
)
stats = decode_all(call(started["server"], "jobs_stats", since=60))
assert [e["device"] for e in stats] == ["juno-01", "qemu-01", "qemu-02"] # nosec
assert stats[1] == { # nosec
"device": "qemu-01",
"device_type": "qemu",
"total": 3,
"complete": 1,
"incomplete": 1,
"canceled": 1,
"error_types": {"Infrastructure": 1},
"failure_rate": 0.5,
}
assert stats[2]["failure_rate"] == 0.0 # nosec
def test_mcp_jobs_stats_device_type(server):
started = server(
[
version(),
{
"request": "scheduler.jobs.list",
"args": ("FINISHED", None, 0, 100, 1440, True),
"ret": [
{
"actual_device": "qemu-01",
"device_type": "qemu",
"health": "Complete",
},
{
"actual_device": "juno-01",
"device_type": "juno",
"health": "Complete",
},
],
},
{
"request": "scheduler.jobs.list",
"args": ("FINISHED", None, 2, 100, 1440, True),
"ret": [],
},
]
)
answer = json.loads(call(started["server"], "jobs_stats", device_type="juno"))
assert answer["device"] == "juno-01" # nosec
assert "positive number" in call(started["server"], "jobs_stats", since=0) # nosec
def test_mcp_job_logs(server):
logs = '- {"dt": "2026-01-01T10:00:00", "lvl": "target", "msg": "booting"}\n'
started = server(
[
version("2026.10"),
logs_count(1),
{
"request": "scheduler.jobs.logs",
"args": ("1234", 0, 100),
"ret": [False, xmlrpc.client.Binary(logs.encode("utf-8"))],
},
]
)
answer = json.loads(call(started["server"], "job_logs", job_id="1234"))
assert answer["finished"] is False # nosec
assert answer["total"] == 1 # nosec
assert answer["count"] == 1 # nosec
assert answer["logs"][0]["msg"] == "booting" # nosec
def test_mcp_job_logs_until_the_end(server):
logs = '- {"dt": "2026-01-01T10:00:00", "lvl": "target", "msg": "login:"}\n'
started = server(
[
version(),
{
# limit=0: no end line, the server returns the rest of the log.
"request": "scheduler.jobs.logs",
"args": ("1234", 42, None),
"ret": [True, xmlrpc.client.Binary(logs.encode("utf-8"))],
},
]
)
answer = json.loads(
call(started["server"], "job_logs", job_id="1234", start=42, limit=0)
)
assert answer["finished"] is True # nosec
assert answer["start"] == 42 # nosec
assert answer["count"] == 1 # nosec
def test_mcp_job_logs_from_the_end(server):
logs = '- {"dt": "2026-01-01T10:00:00", "lvl": "error", "msg": "failed"}\n'
started = server(
[
version("2026.10"),
logs_count(1500),
{
# The last 100 lines
"request": "scheduler.jobs.logs",
"args": ("1234", 1400, 1500),
"ret": [True, xmlrpc.client.Binary(logs.encode("utf-8"))],
},
logs_count(1500),
{
# More lines asked than the log has: from the first line
"request": "scheduler.jobs.logs",
"args": ("1234", 0, None),
"ret": [True, xmlrpc.client.Binary(logs.encode("utf-8"))],
},
]
)
answer = json.loads(call(started["server"], "job_logs", job_id="1234", start=-100))
assert answer["total"] == 1500 # nosec
assert answer["start"] == 1400 # nosec
answer = json.loads(
call(started["server"], "job_logs", job_id="1234", start=-5000, limit=0)
)
assert answer["start"] == 0 # nosec
def test_mcp_job_logs_before_2026_10(server):
logs = '- {"dt": "2026-01-01T10:00:00", "lvl": "target", "msg": "booting"}\n'
started = server(
[
# Development builds of 2026.09 are too old as well
version("2026.09.dev0130"),
# scheduler.jobs.logs_count is never called
{
"request": "scheduler.jobs.logs",
"args": ("1234", 0, 100),
"ret": [True, xmlrpc.client.Binary(logs.encode("utf-8"))],
},
]
)
answer = json.loads(call(started["server"], "job_logs", job_id="1234"))
assert "total" not in answer # nosec
assert answer["count"] == 1 # nosec
def test_mcp_job_logs_from_the_end_before_2026_10(server):
logs = "".join(
f'- {{"dt": "2026-01-01T10:00:00", "lvl": "target", "msg": "line {i}"}}\n'
for i in range(5)
)
full_log = {
# Without the number of lines, the whole log is downloaded
"request": "scheduler.jobs.logs",
"args": ("1234", 0, None),
"ret": [True, xmlrpc.client.Binary(logs.encode("utf-8"))],
}
started = server([version("2026.09"), full_log, full_log, full_log])
answer = json.loads(call(started["server"], "job_logs", job_id="1234", start=-2))
assert answer["total"] == 5 # nosec
assert answer["start"] == 3 # nosec
assert [line["msg"] for line in answer["logs"]] == ["line 3", "line 4"] # nosec
answer = json.loads(
call(started["server"], "job_logs", job_id="1234", start=-4, limit=1)
)
assert answer["start"] == 1 # nosec
assert [line["msg"] for line in answer["logs"]] == ["line 1"] # nosec
answer = json.loads(
call(started["server"], "job_logs", job_id="1234", start=-5000, limit=0)
)
assert answer["start"] == 0 # nosec
assert answer["count"] == 5 # nosec
def test_mcp_job_logs_unknown_job(server):
started = server(
[
version("2026.10"),
{
"request": "scheduler.jobs.logs_count",
"args": ("1234",),
"ret": {"fault_code": 404},
},
]
)
assert "fault string" in call(started["server"], "job_logs", job_id="1234") # nosec
def test_mcp_workers_list_before_2023_03(server):
started = server(
[
version("2023.02"),
{"request": "scheduler.workers.list", "args": (), "ret": ["worker-01"]},
]
)
assert "worker-01" in call(started["server"], "workers_list") # nosec
def test_mcp_workers_list(server):
started = server(
[
version("2023.03"),
{
"request": "scheduler.workers.list",
"args": (False,),
"ret": ["worker-01"],
},
]
)
assert "worker-01" in call(started["server"], "workers_list") # nosec
def test_mcp_worker_show_hides_token(server):
started = server(
[
version(),
{
"request": "scheduler.workers.show",
"args": ("worker-01",),
"ret": {"hostname": "worker-01", "devices": [], "token": "s3cr3t"},
},
]
)
worker = json.loads(call(started["server"], "worker_show", name="worker-01"))
assert worker["hostname"] == "worker-01" # nosec
assert "token" not in worker # nosec
def test_mcp_fault(server):
started = server(
[
version(),
{
"request": "scheduler.workers.show",
"args": ("nope",),
"ret": {"fault_code": 404},
},
]
)
# The XML-RPC error is reported to the client, not swallowed.
assert "fault string" in call(
started["server"], "worker_show", name="nope"
) # nosec
def test_mcp_documentation(server, monkeypatch):
refs = []
def pages(ref):
refs.append(ref)
return {"index": "Welcome to LAVA"}
monkeypatch.setattr(docs, "pages", pages)
monkeypatch.setattr(docs, "fetch", lambda page, ref: f"# {page}@{ref}\n")
started = server([version("2026.07")])
assert "Welcome to LAVA" in call(started["server"], "documentation_list") # nosec
# The documentation follows the release the instance runs.
assert refs == ["2026.07"] # nosec
assert (
call(started["server"], "documentation_fetch", page="index")
== "# index@2026.07\n"
) # nosec
def test_mcp_documentation_development_build(server, monkeypatch):
refs = []
def pages(ref):
refs.append(ref)
return {"index": "Welcome to LAVA"}
monkeypatch.setattr(docs, "pages", pages)
started = server([version("2026.09.dev0130")])
call(started["server"], "documentation_list")
# A development build runs commits made after the 2026.09 tag.
assert refs == ["master"] # nosec
def test_mcp_instructions_point_to_debugging(server):
started = server([version()])
# Triaging a failure starts with the list of the common ones.
assert ( # nosec
"user/advanced-tutorials/debugging-job" in started["server"].instructions
)
def test_mcp_documentation_error(server, monkeypatch):
def fetch(page, ref):
raise ValueError(f"no such documentation page: '{page}'")
monkeypatch.setattr(docs, "fetch", fetch)
started = server([version()])
assert "no such documentation page" in call( # nosec
started["server"], "documentation_fetch", page="nope"
)
def test_mcp_without_the_mcp_module(setup, monkeypatch, capsys):
def create_server(options, instance):
raise ImportError("No module named 'mcp'")
monkeypatch.setattr(mcp_command, "create_server", create_server)
monkeypatch.setattr(sys, "argv", ["lavacli", "mcp"])
monkeypatch.setattr(xmlrpc.client.ServerProxy, "data", [version()])
assert main() == 1 # nosec
assert "pip install lavacli[mcp]" in capsys.readouterr()[1] # nosec
CASES = """
- {name: http-download, suite: lava, result: pass, measurement: '2.5', unit: seconds,
metadata: {case: http-download, definition: lava, level: '1.2'}}
- {name: smoke-tests, suite: 0_smoke-tests, result: fail, measurement: '', unit: '',
metadata: {case: smoke-tests, definition: 0_smoke-tests}}
"""
ONE_CASE = """
- {name: http-download, suite: lava, result: pass, measurement: '2.5', unit: seconds,
metadata: {case: http-download, definition: lava, level: '1.2'}}
"""
def test_mcp_job_suites(server):
suites = "- {name: lava, job: '1234', id: '1'}\n"
started = server(
[
version(),
{
"request": "results.get_testjob_suites_list_yaml",
"args": ("1234",),
"ret": suites,
},
]
)
answer = json.loads(call(started["server"], "job_suites", job_id="1234"))
assert answer["name"] == "lava" # nosec
def test_mcp_job_results(server):
started = server(
[
version(),
{
"request": "results.get_testjob_results_yaml",
"args": ("1234",),
"ret": CASES,
},
]
)
answer = json.loads(call(started["server"], "job_results", job_id="1234"))
assert answer["total"] == 2 # nosec
assert answer["count"] == 2 # nosec
assert answer["results"][0]["name"] == "http-download" # nosec
assert answer["results"][0]["result"] == "pass" # nosec
# The bulky metadata is dropped unless it is asked for.
assert "metadata" not in answer["results"][0] # nosec
def test_mcp_job_results_paging(server):
started = server(
[
version(),
{
"request": "results.get_testjob_results_yaml",
"args": ("1234",),
"ret": CASES,
},
]
)
answer = json.loads(
call(started["server"], "job_results", job_id="1234", start=1, limit=1)
)
assert answer["total"] == 2 # nosec
assert answer["start"] == 1 # nosec
assert [case["name"] for case in answer["results"]] == ["smoke-tests"] # nosec
def test_mcp_job_results_one_suite(server):
started = server(
[
version(),
{
"request": "results.get_testsuite_results_yaml",
# The server does the paging: limit then offset.
"args": ("1234", "lava", 100, 0),
"ret": CASES,
},
]
)
answer = json.loads(
call(started["server"], "job_results", job_id="1234", suite="lava")
)
assert answer["count"] == 2 # nosec
# The server only returned a page: the total is unknown.
assert answer["total"] is None # nosec
assert answer["results"][1]["suite"] == "0_smoke-tests" # nosec
def test_mcp_job_results_one_case(server):
started = server(
[
version(),
{
"request": "results.get_testcase_results_yaml",
"args": ("1234", "lava", "http-download"),
"ret": ONE_CASE,
},
]
)
answer = json.loads(
call(
started["server"],
"job_results",
job_id="1234",
suite="lava",
case="http-download",
metadata=True,
)
)
assert answer["count"] == 1 # nosec
# The metadata is where a failure is explained.
assert answer["results"][0]["metadata"]["level"] == "1.2" # nosec
def test_mcp_job_results_case_without_suite(server):
started = server([version()])
assert "'suite' is required" in call( # nosec
started["server"], "job_results", job_id="1234", case="http-download"
)
def test_mcp_job_metadata(server):
started = server(
[
version(),
{
"request": "results.get_testjob_metadata",
"args": ("1234",),
"ret": {"source": "https://gitlab.com/lava/functional-tests.git"},
},
]
)
answer = json.loads(call(started["server"], "job_metadata", job_id="1234"))
assert answer["source"].endswith("functional-tests.git") # nosec
def test_mcp_instructions_hide_the_token(server):
started = server(
[version()],
[
"lavacli",
"--uri",
"https://someone:s3cr3t-token@lava.example.com/RPC2",
"mcp",
],
)
instructions = started["server"].instructions
# The uri carries the credentials, only the hostname may reach the LLM.
assert "lava.example.com" in instructions # nosec
assert "s3cr3t-token" not in instructions # nosec
assert "someone" not in instructions # nosec
def test_mcp_device_type_template(server):
template = "{% extends 'base-uboot.jinja2' %}\n"
started = server(
[
version(),
{
"request": "scheduler.device_types.get_template",
"args": ("qemu",),
"ret": xmlrpc.client.Binary(template.encode("utf-8")),
},
]
)
assert (
call(started["server"], "device_type_template", name="qemu") == template
) # nosec
def test_mcp_device_type_health_check(server):
health_check = "job_name: qemu health check\n"
started = server(
[
version(),
{
"request": "scheduler.device_types.get_health_check",
"args": ("qemu",),
"ret": xmlrpc.client.Binary(health_check.encode("utf-8")),
},
]
)
assert ( # nosec
call(started["server"], "device_type_health_check", name="qemu") == health_check
)
def test_mcp_device_type_without_health_check(server):
started = server(
[
version(),
{
"request": "scheduler.device_types.get_health_check",
"args": ("qemu",),
"ret": {"fault_code": 404},
},
]
)
assert "fault string" in call( # nosec
started["server"], "device_type_health_check", name="qemu"
)
def test_mcp_job_submit(server):
started = server(
[
version(),
{
"request": "scheduler.jobs.submit",
"args": ("job: definition",),
"ret": 1234,
},
]
)
answer = json.loads(
call(started["server"], "job_submit", definition="job: definition")
)
assert answer["job_ids"] == ["1234"] # nosec
def test_mcp_job_submit_multinode(server):
started = server(
[
version(),
{
"request": "scheduler.jobs.submit",
"args": ("job: definition",),
"ret": ["1234.0", "1234.1"],
},
]
)
answer = json.loads(
call(started["server"], "job_submit", definition="job: definition")
)
assert answer["job_ids"] == ["1234.0", "1234.1"] # nosec
def test_mcp_job_cancel(server):
started = server(
[
version(),
{"request": "scheduler.jobs.cancel", "args": ("1234",), "ret": True},
]
)
assert "job 1234 canceled" in call( # nosec
started["server"], "job_cancel", job_id="1234"
)
def test_mcp_job_cancel_error(server):
started = server(
[
version(),
{
"request": "scheduler.jobs.cancel",
"args": ("1234",),
"ret": {"fault_code": 403},
},
]
)
assert "fault string" in call( # nosec
started["server"], "job_cancel", job_id="1234"
)
def test_mcp_device_type_template_set(server):
template = "{% extends 'base.jinja2' %}\n"
started = server(
[
version(),
{
"request": "scheduler.device_types.set_template",
"args": ("qemu", template),
"ret": True,
},
]
)
assert "updated" in call( # nosec
started["server"], "device_type_template_set", name="qemu", template=template
)
def test_mcp_device_dictionary_set(server):
config = "{% extends 'qemu.jinja2' %}\n"
started = server(
[
version(),
{
"request": "scheduler.devices.set_dictionary",
"args": ("qemu-01", config),
"ret": True,
},
]
)
assert "updated" in call( # nosec
started["server"], "device_dictionary_set", name="qemu-01", config=config
)
def test_mcp_device_dictionary_set_refused(server):
started = server(
[
version(),
{
"request": "scheduler.devices.set_dictionary",
"args": ("qemu-01", "broken"),
# The server answers False instead of raising.
"ret": False,
},
]
)
assert "unable to set the dictionary" in call( # nosec
started["server"], "device_dictionary_set", name="qemu-01", config="broken"
)
WRITE_TOOLS = [
"device_dictionary_set",
"device_type_template_set",
"job_cancel",
"job_submit",
]
def test_mcp_tools_annotations(server):
"""Only the tools changing the instance are flagged as such."""
started = server([version()])
tools = asyncio.run(started["server"].list_tools())
for tool in tools:
read_only = tool.name not in WRITE_TOOLS
assert tool.annotations.readOnlyHint is read_only # nosec
assert tool.annotations.destructiveHint is not read_only # nosec
PROMPTS = ["device_dictionaries_review", "devices_status"]
def prompt(server, name, /, **arguments):
"""Render one prompt and return its text."""
result = asyncio.run(server.get_prompt(name, arguments))
return "".join(message.content.text for message in result.messages)
def test_mcp_prompts(server):
started = server([version()])
prompts = asyncio.run(started["server"].list_prompts())
assert sorted(p.name for p in prompts) == PROMPTS # nosec
for p in prompts:
# Every argument is optional: the prompts work on the whole instance.
assert not any(arg.required for arg in p.arguments) # nosec
def test_mcp_prompt_devices_status(server):
started = server([version()])
text = prompt(started["server"], "devices_status")
assert "last 24 hours" in text # nosec
assert "jobs_stats(since=1440)" in text # nosec
assert "jobs_list(health='INCOMPLETE', since=1440, verbose=True)" in text # nosec
assert "device-type '" not in text # nosec
text = prompt(
started["server"], "devices_status", hours="48", device_type="juno", worker="w4"
)
assert "last 48 hours" in text # nosec
assert "of the device-type 'juno' attached to the worker 'w4'" in text # nosec
assert "jobs_stats(since=2880, device_type='juno', worker='w4')" in text # nosec
def test_mcp_prompt_device_dictionaries_review(server):
started = server([version()])
text = prompt(started["server"], "device_dictionaries_review")
assert "devices_list()" in text # nosec
assert "device_dictionary(render=False)" in text # nosec
text = prompt(
started["server"], "device_dictionaries_review", device_type="juno", worker="w4"
)
assert "device_type_devices(name='juno')" in text # nosec
assert "worker_show(name='w4')" in text # nosec
lavacli-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_results.py 0000664 0000000 0000000 00000026543 15265406512 0025255 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_schemas.py 0000664 0000000 0000000 00000005754 15265406512 0025200 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_system.py 0000664 0000000 0000000 00000045023 15265406512 0025072 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_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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_tags.py 0000664 0000000 0000000 00000014626 15265406512 0024511 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_tokens.py 0000664 0000000 0000000 00000011125 15265406512 0025045 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_users.py 0000664 0000000 0000000 00000012547 15265406512 0024714 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-v3.1.0-e68b3132f336d7cead4c8b76156d6ad6fc375405/tests/test_workers.py 0000664 0000000 0000000 00000060470 15265406512 0025245 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