Update README to explain ara-server was migrated back into ara

The ara-server standalone repository is being discontinued.
The clear and logical separation of components was nice but the overhead
in complexity was not worth it.

Change-Id: I9d5e3096db4972405932ae2af46ee63bfeef43b5
This commit is contained in:
David Moreau Simard 2019-03-01 15:55:33 -05:00
parent c0021b3e05
commit 33e4c1d841
No known key found for this signature in database
GPG Key ID: CBEB466764A9E621
66 changed files with 9 additions and 4527 deletions

View File

@ -1,17 +0,0 @@
# editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.py]
indent_size = 4

99
.gitignore vendored
View File

@ -1,99 +0,0 @@
# Created by .ignore support plugin (hsz.mobi)
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
pip-wheel-metadata/
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
reports/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
db.sqlite3
www/
data/
# Failed playbook integration test files
*.retry

View File

@ -1,4 +0,0 @@
[gerrit]
host=review.openstack.org
port=29418
project=openstack/ara-server.git

View File

@ -1,21 +0,0 @@
- job:
name: ara-tox-py3
parent: tox
nodeset: ubuntu-bionic
vars:
tox_envlist: py3
- job:
name: ara-tox-linters
parent: tox
nodeset: ubuntu-bionic
vars:
tox_envlist: linters
# TODO: Delete this, all linters have been merged into tox-linters
- job:
name: tox-format
parent: tox
nodeset: ubuntu-bionic
vars:
tox_envlist: format

View File

@ -1,19 +0,0 @@
- project:
vars:
rtd_webhook_id: '49230'
templates:
- docs-on-readthedocs
check:
jobs:
- ara-integration-fedora-2.7
- ara-integration-fedora-devel:
voting: false
- ara-integration-ubuntu-2.6
- ara-tox-linters
- ara-tox-py3
gate:
jobs:
- ara-integration-fedora-2.7
- ara-integration-ubuntu-2.6
- ara-tox-linters
- ara-tox-py3

674
LICENSE
View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,127 +1,10 @@
ara-server
==========
.. image:: doc/source/_static/ara-with-icon.png
This project is no longer maintained and has been folded into a single
ARA repository.
ARA Records Ansible playbook runs and makes the recorded data available and
intuitive for users and systems.
You can find the ARA repository at the following address:
https://github.com/openstack/ara
ara-server is a modern python 3 application built with the latest releases of
`Django <https://www.djangoproject.com/>`_ and `django-rest-framework <https://www.django-rest-framework.org/>`_.
``ara-server`` is the component from ARA that manages the REST API and the database.
.. image:: doc/source/_static/screenshot.png
- For the ARA Ansible callback plugin or the ``ara_record`` action module, look at `ara-plugins <https://github.com/openstack/ara-plugins>`_
- For the ARA REST API clients, look at `ara-clients <https://github.com/openstack/ara-clients>`_
- For the ARA web interface, look at `ara-web <https://github.com/openstack/ara-web>`_
Quickstart
==========
Here's how you can get started from scratch with default settings::
# Create a virtual environment
python3 -m venv ~/.ara/venv
# Install Ansible and the required ARA projects
~/.ara/venv/bin/pip install ansible ara-server ara-clients ara-plugins
# Tell Ansible to use the ARA callback plugin from ara-plugins
export ANSIBLE_CALLBACK_PLUGINS="$(~/.ara/venv/bin/python -m ara.plugins)/callback"
# Run your playbook as your normally would
~/.ara/venv/bin/ansible-playbook playbook.yml
The data is saved in real time during the Ansible playbook execution.
What happened behind the scenes is that the ARA Ansible callback plugin
(provided by ``ara-plugins``) used the offline API client
(provided by ``ara-clients``) to send your data to the ``ara-server`` API which
then saved it to a database located by default at
``~/.ara/server/ansible.sqlite``.
You're now ready to start poking at the API with the built-in API clients !
If you'd like to have the ARA web reporting interface, take a look at
`ara-web <https://github.com/openstack/ara-web>`_.
Documentation
=============
Documentation for installing, configuring, running and using ara-server is
available on `readthedocs.io <https://ara-server.readthedocs.io>`_.
Community and getting help
==========================
You can chat with the ARA community on Slack and IRC.
The two are transparently bridged with teamchat_ which broadcasts messages from
one platform to the other.
In addition, you can also find ARA on Twitter: `@ARecordsAnsible <https://twitter.com/ARecordsAnsible>`_
**IRC**
- Server: `irc.freenode.net`_
- Channel: #ara
**Slack**
- https://arecordsansible.slack.com
- Join with the `Slack invitation <https://join.slack.com/t/arecordsansible/shared_invite/enQtMjMxNzI4ODAxMDQxLWU4MmZhZTI4ZjRjOTUwZTM2MzM3MzcwNDU1YzFmNzRlMzI0NTUzNDY1MWJlNThhM2I4ZTViZjUwZTRkNTBiM2I>`_
.. _teamchat: https://github.com/dmsimard/teamchat
.. _irc.freenode.net: https://webchat.freenode.net/
Development
===========
**TL;DR**: Using tox is convenient for the time being::
# Retrieve the source
git clone https://github.com/openstack/ara-server
cd ara-server
# Install tox from pip or from your distro packages
pip install tox
# Run test server -> http://127.0.0.1:8000/api/v1/
tox -e runserver
# Run actual tests or get coverage
tox -e linters
tox -e py3
tox -e cover
# Build docs
tox -e docs
Authors and contributors
========================
ARA was created by David Moreau Simard (@dmsimard) and contributors can be
found on GitHub_.
.. _GitHub: https://github.com/openstack/ara-server/graphs/contributors
Copyright
=========
::
Copyright (c) 2018 Red Hat, Inc.
ARA is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ARA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ARA. If not, see <http://www.gnu.org/licenses/>.
More information about ARA can be found at https://ara.recordsansible.org.

View File

View File

@ -1,14 +0,0 @@
from django.contrib import admin
from django.contrib.auth.models import Group
from ara.api import models
class RecordAdmin(admin.ModelAdmin):
list_display = ("id", "key", "value", "type")
search_fields = ("key", "value", "type")
ordering = ("key",)
admin.site.register(models.Record, RecordAdmin)
admin.site.unregister(Group)

View File

@ -1,5 +0,0 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = "ara.api"

View File

@ -1,26 +0,0 @@
# Copyright (c) 2019 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from django.conf import settings
from rest_framework import permissions
class APIAccessPermission(permissions.BasePermission):
def has_permission(self, request, view):
if request.method in permissions.SAFE_METHODS:
return request.user.is_authenticated if settings.READ_LOGIN_REQUIRED else True
return request.user.is_authenticated if settings.WRITE_LOGIN_REQUIRED else True

View File

@ -1,216 +0,0 @@
# Generated by Django 2.1.5 on 2019-01-10 22:42
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='File',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('path', models.CharField(max_length=255)),
],
options={
'db_table': 'files',
},
),
migrations.CreateModel(
name='FileContent',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('sha1', models.CharField(max_length=40, unique=True)),
('contents', models.BinaryField(max_length=4294967295)),
],
options={
'db_table': 'file_contents',
},
),
migrations.CreateModel(
name='Host',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('facts', models.BinaryField(max_length=4294967295)),
('alias', models.CharField(max_length=255, null=True)),
],
options={
'db_table': 'hosts',
},
),
migrations.CreateModel(
name='Label',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('description', models.BinaryField(max_length=4294967295)),
],
options={
'db_table': 'labels',
},
),
migrations.CreateModel(
name='Play',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('started', models.DateTimeField(default=django.utils.timezone.now)),
('ended', models.DateTimeField(blank=True, null=True)),
('name', models.CharField(blank=True, max_length=255, null=True)),
('uuid', models.UUIDField()),
('status', models.CharField(choices=[('unknown', 'unknown'), ('running', 'running'), ('completed', 'completed')], default='unknown', max_length=25)),
],
options={
'db_table': 'plays',
},
),
migrations.CreateModel(
name='Playbook',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('started', models.DateTimeField(default=django.utils.timezone.now)),
('ended', models.DateTimeField(blank=True, null=True)),
('name', models.CharField(max_length=255, null=True)),
('ansible_version', models.CharField(max_length=255)),
('status', models.CharField(choices=[('unknown', 'unknown'), ('running', 'running'), ('completed', 'completed'), ('failed', 'failed')], default='unknown', max_length=25)),
('arguments', models.BinaryField(max_length=4294967295)),
('path', models.CharField(max_length=255)),
('labels', models.ManyToManyField(to='api.Label')),
],
options={
'db_table': 'playbooks',
},
),
migrations.CreateModel(
name='Record',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('key', models.CharField(max_length=255)),
('value', models.BinaryField(max_length=4294967295)),
('type', models.CharField(max_length=255)),
('playbook', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='records', to='api.Playbook')),
],
options={
'db_table': 'records',
},
),
migrations.CreateModel(
name='Result',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('started', models.DateTimeField(default=django.utils.timezone.now)),
('ended', models.DateTimeField(blank=True, null=True)),
('status', models.CharField(choices=[('ok', 'ok'), ('failed', 'failed'), ('skipped', 'skipped'), ('unreachable', 'unreachable'), ('changed', 'changed'), ('ignored', 'ignored'), ('unknown', 'unknown')], default='unknown', max_length=25)),
('content', models.BinaryField(max_length=4294967295)),
('host', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='results', to='api.Host')),
('playbook', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='results', to='api.Playbook')),
],
options={
'db_table': 'results',
},
),
migrations.CreateModel(
name='Stats',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('changed', models.IntegerField(default=0)),
('failed', models.IntegerField(default=0)),
('ok', models.IntegerField(default=0)),
('skipped', models.IntegerField(default=0)),
('unreachable', models.IntegerField(default=0)),
('host', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stats', to='api.Host')),
('playbook', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='stats', to='api.Playbook')),
],
options={
'db_table': 'stats',
},
),
migrations.CreateModel(
name='Task',
fields=[
('id', models.BigAutoField(editable=False, primary_key=True, serialize=False)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('started', models.DateTimeField(default=django.utils.timezone.now)),
('ended', models.DateTimeField(blank=True, null=True)),
('name', models.TextField(blank=True, null=True)),
('action', models.TextField()),
('lineno', models.IntegerField()),
('tags', models.BinaryField(max_length=4294967295)),
('handler', models.BooleanField()),
('status', models.CharField(choices=[('unknown', 'unknown'), ('running', 'running'), ('completed', 'completed')], default='unknown', max_length=25)),
('file', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='api.File')),
('play', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='api.Play')),
('playbook', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to='api.Playbook')),
],
options={
'db_table': 'tasks',
},
),
migrations.AddField(
model_name='result',
name='task',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='results', to='api.Task'),
),
migrations.AddField(
model_name='play',
name='playbook',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='plays', to='api.Playbook'),
),
migrations.AddField(
model_name='host',
name='playbook',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='hosts', to='api.Playbook'),
),
migrations.AddField(
model_name='file',
name='content',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='files', to='api.FileContent'),
),
migrations.AddField(
model_name='file',
name='playbook',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='files', to='api.Playbook'),
),
migrations.AlterUniqueTogether(
name='stats',
unique_together={('host', 'playbook')},
),
migrations.AlterUniqueTogether(
name='record',
unique_together={('key', 'playbook')},
),
migrations.AlterUniqueTogether(
name='host',
unique_together={('name', 'playbook')},
),
migrations.AlterUniqueTogether(
name='file',
unique_together={('path', 'playbook')},
),
]

View File

@ -1,290 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from django.db import models
from django.utils import timezone
class Base(models.Model):
"""
Abstract base model part of every model
"""
class Meta:
abstract = True
id = models.BigAutoField(primary_key=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Duration(Base):
"""
Abstract model for models with a concept of duration
"""
class Meta:
abstract = True
started = models.DateTimeField(default=timezone.now)
ended = models.DateTimeField(blank=True, null=True)
class Label(Base):
"""
A label is a generic container meant to group or correlate different
playbooks. It could be a single playbook run. It could be a "group" of
playbooks.
It could represent phases or dynamic logical grouping and tagging of
playbook runs.
You could have a label named "failures" and make it so failed playbooks
are added to this report, for example.
The main purpose of this is to make the labels customizable by the user.
"""
class Meta:
db_table = "labels"
name = models.CharField(max_length=255)
description = models.BinaryField(max_length=(2 ** 32) - 1)
def __str__(self):
return "<Label %s: %s>" % (self.id, self.name)
class Playbook(Duration):
"""
An entry in the 'playbooks' table represents a single execution of the
ansible or ansible-playbook commands. All the data for that execution
is tied back to this one playbook.
"""
class Meta:
db_table = "playbooks"
# A playbook in ARA can be running (in progress), completed (succeeded) or failed.
UNKNOWN = "unknown"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
STATUS = ((UNKNOWN, "unknown"), (RUNNING, "running"), (COMPLETED, "completed"), (FAILED, "failed"))
name = models.CharField(max_length=255, null=True)
ansible_version = models.CharField(max_length=255)
status = models.CharField(max_length=25, choices=STATUS, default=UNKNOWN)
arguments = models.BinaryField(max_length=(2 ** 32) - 1)
path = models.CharField(max_length=255)
labels = models.ManyToManyField(Label)
def __str__(self):
return "<Playbook %s>" % self.id
class FileContent(Base):
"""
Contents of a uniquely stored and compressed file.
Running the same playbook twice will yield two playbook files but just
one file contents.
"""
class Meta:
db_table = "file_contents"
sha1 = models.CharField(max_length=40, unique=True)
contents = models.BinaryField(max_length=(2 ** 32) - 1)
def __str__(self):
return "<FileContent %s:%s>" % (self.id, self.sha1)
class File(Base):
"""
Data about Ansible files (playbooks, tasks, role files, var files, etc).
Multiple files can reference the same FileContent record.
"""
class Meta:
db_table = "files"
unique_together = ("path", "playbook")
path = models.CharField(max_length=255)
content = models.ForeignKey(FileContent, on_delete=models.CASCADE, related_name="files")
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="files")
def __str__(self):
return "<File %s:%s>" % (self.id, self.path)
class Record(Base):
"""
A rudimentary key/value table to associate arbitrary data to a playbook.
Used with the ara_record and ara_read Ansible modules.
"""
class Meta:
db_table = "records"
unique_together = ("key", "playbook")
key = models.CharField(max_length=255)
value = models.BinaryField(max_length=(2 ** 32) - 1)
type = models.CharField(max_length=255)
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="records")
def __str__(self):
return "<Record %s:%s>" % (self.id, self.key)
class Play(Duration):
"""
Data about Ansible plays.
Hosts, tasks and results are childrens of an Ansible play.
"""
class Meta:
db_table = "plays"
# A play in ARA can be running (in progress) or completed (regardless of success or failure)
UNKNOWN = "unknown"
RUNNING = "running"
COMPLETED = "completed"
STATUS = ((UNKNOWN, "unknown"), (RUNNING, "running"), (COMPLETED, "completed"))
name = models.CharField(max_length=255, blank=True, null=True)
uuid = models.UUIDField()
status = models.CharField(max_length=25, choices=STATUS, default=UNKNOWN)
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="plays")
def __str__(self):
return "<Play %s:%s>" % (self.id, self.name)
class Task(Duration):
"""Data about Ansible tasks."""
class Meta:
db_table = "tasks"
# A task in ARA can be running (in progress) or completed (regardless of success or failure)
# Actual task statuses (such as failed, skipped, etc.) are actually in the Results table.
UNKNOWN = "unknown"
RUNNING = "running"
COMPLETED = "completed"
STATUS = ((UNKNOWN, "unknown"), (RUNNING, "running"), (COMPLETED, "completed"))
name = models.TextField(blank=True, null=True)
action = models.TextField()
lineno = models.IntegerField()
tags = models.BinaryField(max_length=(2 ** 32) - 1)
handler = models.BooleanField()
status = models.CharField(max_length=25, choices=STATUS, default=UNKNOWN)
play = models.ForeignKey(Play, on_delete=models.CASCADE, related_name="tasks")
file = models.ForeignKey(File, on_delete=models.CASCADE, related_name="tasks")
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="tasks")
def __str__(self):
return "<Task %s:%s>" % (self.name, self.id)
class Host(Base):
"""
Data about Ansible hosts.
"""
class Meta:
db_table = "hosts"
unique_together = ("name", "playbook")
name = models.CharField(max_length=255)
facts = models.BinaryField(max_length=(2 ** 32) - 1)
# Ansible doesn't supply a mechanism to uniquely identify a host out of
# the box.
# ARA can attempt to reconcile what it believes are the results same hosts
# based on user-supplied configuration or through a hashing algorithm.
# The goal is to "regroup" all unique hosts under a single alias if they
# are the same host.
# The logic for supplying aliases does not live here, it's provided by the
# clients and consumers.
alias = models.CharField(max_length=255, null=True)
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="hosts")
def __str__(self):
return "<Host %s:%s>" % (self.id, self.name)
class Stats(Base):
"""
Stats for a host for a playbook.
"""
class Meta:
db_table = "stats"
unique_together = ("host", "playbook")
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="stats")
host = models.ForeignKey(Host, on_delete=models.CASCADE, related_name="stats")
changed = models.IntegerField(default=0)
failed = models.IntegerField(default=0)
ok = models.IntegerField(default=0)
skipped = models.IntegerField(default=0)
unreachable = models.IntegerField(default=0)
def __str__(self):
# Verbose because it's otherwise kind of useless
return "<Stats for {host} ({id}) in playbook {playbook}>".format(
host=self.host.name, id=self.host.id, playbook=self.playbook.id
)
class Result(Duration):
"""
Data about Ansible results.
A task can have many results if the task is run on multiple hosts.
"""
class Meta:
db_table = "results"
# Ansible statuses
OK = "ok"
FAILED = "failed"
SKIPPED = "skipped"
UNREACHABLE = "unreachable"
# ARA specific statuses (derived or assumed)
CHANGED = "changed"
IGNORED = "ignored"
UNKNOWN = "unknown"
STATUS = (
(OK, "ok"),
(FAILED, "failed"),
(SKIPPED, "skipped"),
(UNREACHABLE, "unreachable"),
(CHANGED, "changed"),
(IGNORED, "ignored"),
(UNKNOWN, "unknown"),
)
status = models.CharField(max_length=25, choices=STATUS, default=UNKNOWN)
# todo use a single Content table
content = models.BinaryField(max_length=(2 ** 32) - 1)
host = models.ForeignKey(Host, on_delete=models.CASCADE, related_name="results")
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="results")
playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE, related_name="results")
def __str__(self):
return "<Result %s, %s>" % (self.id, self.status)

View File

@ -1,230 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import hashlib
import json
import logging
import zlib
from rest_framework import serializers
from ara.api import models
DATE_FORMAT = "(iso-8601: 2016-05-06T17:20:25.749489-04:00)"
DURATION_FORMAT = "([DD] [HH:[MM:]]ss[.uuuuuu])"
logger = logging.getLogger("ara.api.serializers")
class CompressedTextField(serializers.CharField):
"""
Compresses text before storing it in the database.
Decompresses text from the database before serving it.
"""
def to_representation(self, obj):
return zlib.decompress(obj).decode("utf8")
def to_internal_value(self, data):
return zlib.compress(data.encode("utf8"))
class CompressedObjectField(serializers.JSONField):
"""
Serializes/compresses an object (i.e, list, dict) before storing it in the
database.
Decompresses/deserializes an object before serving it.
"""
def to_representation(self, obj):
return json.loads(zlib.decompress(obj).decode("utf8"))
def to_internal_value(self, data):
return zlib.compress(json.dumps(data).encode("utf8"))
class DurationSerializer(serializers.ModelSerializer):
"""
Serializer for duration-based fields
"""
class Meta:
abstract = True
duration = serializers.SerializerMethodField()
@staticmethod
def get_duration(obj):
if obj.ended is None:
return obj.updated - obj.started
return obj.ended - obj.started
class FileContentSerializer(serializers.ModelSerializer):
class Meta:
model = models.FileContent
fields = "__all__"
class FileContentField(serializers.CharField):
"""
Compresses text before storing it in the database.
Decompresses text from the database before serving it.
"""
def to_representation(self, obj):
return zlib.decompress(obj.contents).decode("utf8")
def to_internal_value(self, data):
contents = data.encode("utf8")
sha1 = hashlib.sha1(contents).hexdigest()
content_file, created = models.FileContent.objects.get_or_create(
sha1=sha1, defaults={"sha1": sha1, "contents": zlib.compress(contents)}
)
return content_file
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = models.File
fields = "__all__"
sha1 = serializers.SerializerMethodField()
content = FileContentField()
@staticmethod
def get_sha1(obj):
return obj.content.sha1
class HostSerializer(serializers.ModelSerializer):
class Meta:
model = models.Host
fields = "__all__"
facts = CompressedObjectField(default=zlib.compress(json.dumps({}).encode("utf8")))
def get_unique_together_validators(self):
"""
Hosts have a "unique together" constraint for host.name and play.id.
We want to have a "get_or_create" facility and in order to do that, we
must manage the validation during the creation, not before.
Overriding this method effectively disables this validator.
"""
return []
def create(self, validated_data):
host, created = models.Host.objects.get_or_create(
name=validated_data["name"], playbook=validated_data["playbook"], defaults=validated_data
)
return host
class ResultSerializer(DurationSerializer):
class Meta:
model = models.Result
fields = "__all__"
content = CompressedObjectField(default=zlib.compress(json.dumps({}).encode("utf8")))
class LabelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Label
fields = "__all__"
description = CompressedTextField(
default=zlib.compress(json.dumps("").encode("utf8")), help_text="A textual description of the label"
)
class TaskSerializer(DurationSerializer):
class Meta:
model = models.Task
fields = "__all__"
tags = CompressedObjectField(
default=zlib.compress(json.dumps([]).encode("utf8")), help_text="A JSON list containing Ansible tags"
)
class SimpleTaskSerializer(serializers.ModelSerializer):
class Meta:
model = models.Task
fields = ("id", "name")
class RecordSerializer(serializers.ModelSerializer):
class Meta:
model = models.Record
fields = "__all__"
value = CompressedObjectField(
default=zlib.compress(json.dumps("").encode("utf8")),
help_text="A string, list, dict, json or other formatted data",
)
class PlaySerializer(DurationSerializer):
class Meta:
model = models.Play
fields = "__all__"
hosts = HostSerializer(read_only=True, many=True)
results = ResultSerializer(read_only=True, many=True)
class SimplePlaySerializer(serializers.ModelSerializer):
class Meta:
model = models.Play
fields = "__all__"
class StatsSerializer(serializers.ModelSerializer):
class Meta:
model = models.Stats
fields = "__all__"
class PlaybookSerializer(DurationSerializer):
class Meta:
model = models.Playbook
fields = "__all__"
arguments = CompressedObjectField(default=zlib.compress(json.dumps({}).encode("utf8")))
files = FileSerializer(many=True, default=[])
hosts = HostSerializer(many=True, default=[])
labels = LabelSerializer(many=True, default=[])
tasks = SimpleTaskSerializer(many=True, read_only=True, default=[])
plays = SimplePlaySerializer(many=True, read_only=True, default=[])
records = RecordSerializer(many=True, read_only=True, default=[])
def create(self, validated_data):
# Create the playbook without the file and label references for now
files = validated_data.pop("files")
hosts = validated_data.pop("hosts")
labels = validated_data.pop("labels")
playbook = models.Playbook.objects.create(**validated_data)
# Add the files, hosts and the labels in
for file_ in files:
playbook.hosts.add(models.File.objects.create(**file_))
for host in hosts:
playbook.hosts.add(models.Host.objects.create(**host))
for label in labels:
playbook.labels.add(models.Label.objects.create(**label))
return playbook

View File

@ -1,135 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import factory
from ara.api import models
from ara.api.tests import utils
# constants for things like compressed byte strings or objects
FILE_CONTENTS = "---\n# Example file"
HOST_FACTS = {"ansible_fqdn": "hostname", "ansible_distribution": "CentOS"}
PLAYBOOK_ARGUMENTS = {"ansible_version": "2.5.5", "inventory": "/etc/ansible/hosts"}
RESULT_CONTENTS = {"results": [{"msg": "something happened"}]}
LABEL_DESCRIPTION = "label description"
TASK_TAGS = ["always", "never"]
RECORD_LIST = ["one", "two", "three"]
class PlaybookFactory(factory.DjangoModelFactory):
class Meta:
model = models.Playbook
ansible_version = "2.4.0"
status = "running"
arguments = utils.compressed_obj(PLAYBOOK_ARGUMENTS)
path = "/path/playbook.yml"
class FileContentFactory(factory.DjangoModelFactory):
class Meta:
model = models.FileContent
django_get_or_create = ("sha1",)
sha1 = utils.sha1(FILE_CONTENTS)
contents = utils.compressed_str(FILE_CONTENTS)
class FileFactory(factory.DjangoModelFactory):
class Meta:
model = models.File
path = "/path/playbook.yml"
content = factory.SubFactory(FileContentFactory)
playbook = factory.SubFactory(PlaybookFactory)
class LabelFactory(factory.DjangoModelFactory):
class Meta:
model = models.Label
name = "test label"
description = utils.compressed_str(LABEL_DESCRIPTION)
class PlayFactory(factory.DjangoModelFactory):
class Meta:
model = models.Play
name = "test play"
status = "running"
uuid = "5c5f67b9-e63c-6297-80da-000000000005"
playbook = factory.SubFactory(PlaybookFactory)
class TaskFactory(factory.DjangoModelFactory):
class Meta:
model = models.Task
name = "test task"
status = "running"
action = "setup"
lineno = 2
handler = False
tags = utils.compressed_obj(TASK_TAGS)
play = factory.SubFactory(PlayFactory)
file = factory.SubFactory(FileFactory)
playbook = factory.SubFactory(PlaybookFactory)
class HostFactory(factory.DjangoModelFactory):
class Meta:
model = models.Host
facts = utils.compressed_obj(HOST_FACTS)
name = "hostname"
alias = "9f5d3ba7-e43d-4f3b-ab17-f90c39e43d07"
playbook = factory.SubFactory(PlaybookFactory)
class ResultFactory(factory.DjangoModelFactory):
class Meta:
model = models.Result
content = utils.compressed_obj(RESULT_CONTENTS)
status = "ok"
host = factory.SubFactory(HostFactory)
task = factory.SubFactory(TaskFactory)
playbook = factory.SubFactory(PlaybookFactory)
class RecordFactory(factory.DjangoModelFactory):
class Meta:
model = models.Record
key = "record-key"
value = utils.compressed_obj(RECORD_LIST)
type = "list"
playbook = factory.SubFactory(PlaybookFactory)
class StatsFactory(factory.DjangoModelFactory):
class Meta:
model = models.Stats
changed = 1
failed = 0
ok = 2
skipped = 1
unreachable = 0
playbook = factory.SubFactory(PlaybookFactory)
host = factory.SubFactory(HostFactory)

View File

@ -1,74 +0,0 @@
# Copyright (c) 2019 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from django.conf import settings
from django.test import RequestFactory, TestCase, override_settings
from ara.api.auth import APIAccessPermission
class User:
is_authenticated = True
class AnonymousUser(User):
is_authenticated = False
class PermissionBackendTestCase(TestCase):
def setUp(self):
factory = RequestFactory()
self.anon_get_request = factory.get("/")
self.anon_get_request.user = AnonymousUser()
self.anon_post_request = factory.post("/")
self.anon_post_request.user = AnonymousUser()
self.authed_get_request = factory.get("/")
self.authed_get_request.user = User()
self.authed_post_request = factory.post("/")
self.authed_post_request.user = User()
@override_settings(READ_LOGIN_REQUIRED=False, WRITE_LOGIN_REQUIRED=True)
def test_anonymous_read_access(self):
backend = APIAccessPermission()
# Writes are blocked (just to show it has no affect on read)
self.assertFalse(backend.has_permission(self.anon_post_request, None))
# Reads are allowed based on READ_LOGIN_REQUIRED
self.assertTrue(backend.has_permission(self.anon_get_request, None))
settings.READ_LOGIN_REQUIRED = True
self.assertFalse(backend.has_permission(self.anon_get_request, None))
@override_settings(READ_LOGIN_REQUIRED=True, WRITE_LOGIN_REQUIRED=False)
def test_anonymous_write_access(self):
backend = APIAccessPermission()
# Reads are blocked (just to show it has no affect on write)
self.assertFalse(backend.has_permission(self.anon_get_request, None))
# Writes are allowed based on WRITE_LOGIN_REQUIRED
self.assertTrue(backend.has_permission(self.anon_post_request, None))
settings.WRITE_LOGIN_REQUIRED = True
self.assertFalse(backend.has_permission(self.anon_post_request, None))
@override_settings(READ_LOGIN_REQUIRED=True, WRITE_LOGIN_REQUIRED=True)
def test_auth_access(self):
backend = APIAccessPermission()
self.assertTrue(backend.has_permission(self.authed_get_request, None))
self.assertTrue(backend.has_permission(self.authed_post_request, None))

View File

@ -1,112 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class FileTestCase(APITestCase):
def test_file_factory(self):
file_content = factories.FileContentFactory()
file = factories.FileFactory(path="/path/playbook.yml", content=file_content)
self.assertEqual(file.path, "/path/playbook.yml")
self.assertEqual(file.content.sha1, file_content.sha1)
def test_file_serializer(self):
playbook = factories.PlaybookFactory()
serializer = serializers.FileSerializer(
data={"path": "/path/playbook.yml", "content": factories.FILE_CONTENTS, "playbook": playbook.id}
)
serializer.is_valid()
file = serializer.save()
file.refresh_from_db()
self.assertEqual(file.content.sha1, utils.sha1(factories.FILE_CONTENTS))
def test_create_file_with_same_content_create_only_one_file_content(self):
playbook = factories.PlaybookFactory()
serializer = serializers.FileSerializer(
data={"path": "/path/1/playbook.yml", "content": factories.FILE_CONTENTS, "playbook": playbook.id}
)
serializer.is_valid()
file_content = serializer.save()
file_content.refresh_from_db()
serializer2 = serializers.FileSerializer(
data={"path": "/path/2/playbook.yml", "content": factories.FILE_CONTENTS, "playbook": playbook.id}
)
serializer2.is_valid()
file_content = serializer2.save()
file_content.refresh_from_db()
self.assertEqual(2, models.File.objects.all().count())
self.assertEqual(1, models.FileContent.objects.all().count())
def test_create_file(self):
self.assertEqual(0, models.File.objects.count())
playbook = factories.PlaybookFactory()
request = self.client.post(
"/api/v1/files", {"path": "/path/playbook.yml", "content": factories.FILE_CONTENTS, "playbook": playbook.id}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.File.objects.count())
def test_get_no_files(self):
request = self.client.get("/api/v1/files")
self.assertEqual(0, len(request.data["results"]))
def test_get_files(self):
file = factories.FileFactory()
request = self.client.get("/api/v1/files")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(file.path, request.data["results"][0]["path"])
def test_get_file(self):
file = factories.FileFactory()
request = self.client.get("/api/v1/files/%s" % file.id)
self.assertEqual(file.path, request.data["path"])
self.assertEqual(file.content.sha1, request.data["sha1"])
def test_update_file(self):
playbook = factories.PlaybookFactory()
file = factories.FileFactory(playbook=playbook)
old_sha1 = file.content.sha1
self.assertNotEqual("/path/new_playbook.yml", file.path)
request = self.client.put(
"/api/v1/files/%s" % file.id,
{"path": "/path/new_playbook.yml", "content": "# playbook", "playbook": playbook.id},
)
self.assertEqual(200, request.status_code)
file_updated = models.File.objects.get(id=file.id)
self.assertEqual("/path/new_playbook.yml", file_updated.path)
self.assertNotEqual(old_sha1, file_updated.content.sha1)
def test_partial_update_file(self):
file = factories.FileFactory()
self.assertNotEqual("/path/new_playbook.yml", file.path)
request = self.client.patch("/api/v1/files/%s" % file.id, {"path": "/path/new_playbook.yml"})
self.assertEqual(200, request.status_code)
file_updated = models.File.objects.get(id=file.id)
self.assertEqual("/path/new_playbook.yml", file_updated.path)
def test_delete_file(self):
file = factories.FileFactory()
self.assertEqual(1, models.File.objects.all().count())
request = self.client.delete("/api/v1/files/%s" % file.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.File.objects.all().count())

View File

@ -1,26 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api.tests import factories
class FileContentTestCase(APITestCase):
def test_file_content_factory(self):
file_content = factories.FileContentFactory(sha1="413a2f16b8689267b7d0c2e10cdd19bf3e54208d")
self.assertEqual(file_content.sha1, "413a2f16b8689267b7d0c2e10cdd19bf3e54208d")

View File

@ -1,108 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class HostTestCase(APITestCase):
def test_host_factory(self):
host = factories.HostFactory(name="testhost")
self.assertEqual(host.name, "testhost")
def test_host_serializer(self):
playbook = factories.PlaybookFactory()
serializer = serializers.HostSerializer(data={"name": "serializer", "playbook": playbook.id})
serializer.is_valid()
host = serializer.save()
host.refresh_from_db()
self.assertEqual(host.name, "serializer")
self.assertEqual(host.playbook.id, playbook.id)
def test_host_serializer_compress_facts(self):
playbook = factories.PlaybookFactory()
serializer = serializers.HostSerializer(
data={"name": "compress", "facts": factories.HOST_FACTS, "playbook": playbook.id}
)
serializer.is_valid()
host = serializer.save()
host.refresh_from_db()
self.assertEqual(host.facts, utils.compressed_obj(factories.HOST_FACTS))
def test_host_serializer_decompress_facts(self):
host = factories.HostFactory(facts=utils.compressed_obj(factories.HOST_FACTS))
serializer = serializers.HostSerializer(instance=host)
self.assertEqual(serializer.data["facts"], factories.HOST_FACTS)
def test_get_no_hosts(self):
request = self.client.get("/api/v1/hosts")
self.assertEqual(0, len(request.data["results"]))
def test_get_hosts(self):
host = factories.HostFactory()
request = self.client.get("/api/v1/hosts")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(host.name, request.data["results"][0]["name"])
def test_delete_host(self):
host = factories.HostFactory()
self.assertEqual(1, models.Host.objects.all().count())
request = self.client.delete("/api/v1/hosts/%s" % host.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Host.objects.all().count())
def test_create_host(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Host.objects.count())
request = self.client.post("/api/v1/hosts", {"name": "create", "playbook": playbook.id})
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Host.objects.count())
def test_post_same_host_for_a_playbook(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Host.objects.count())
request = self.client.post("/api/v1/hosts", {"name": "create", "playbook": playbook.id})
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Host.objects.count())
request = self.client.post("/api/v1/hosts", {"name": "create", "playbook": playbook.id})
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Host.objects.count())
def test_partial_update_host(self):
host = factories.HostFactory()
self.assertNotEqual("foo", host.name)
request = self.client.patch("/api/v1/hosts/%s" % host.id, {"name": "foo"})
self.assertEqual(200, request.status_code)
host_updated = models.Host.objects.get(id=host.id)
self.assertEqual("foo", host_updated.name)
def test_get_host(self):
host = factories.HostFactory()
request = self.client.get("/api/v1/hosts/%s" % host.id)
self.assertEqual(host.name, request.data["name"])
def test_get_hosts_by_playbook(self):
playbook = factories.PlaybookFactory()
host = factories.HostFactory(name="host1", playbook=playbook)
factories.HostFactory(name="host2", playbook=playbook)
request = self.client.get("/api/v1/hosts?playbook=%s" % playbook.id)
self.assertEqual(2, len(request.data["results"]))
self.assertEqual(host.name, request.data["results"][0]["name"])
self.assertEqual("host2", request.data["results"][1]["name"])

View File

@ -1,82 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class LabelTestCase(APITestCase):
def test_label_factory(self):
label = factories.LabelFactory(name="factory")
self.assertEqual(label.name, "factory")
def test_label_serializer(self):
serializer = serializers.LabelSerializer(data={"name": "serializer"})
serializer.is_valid()
label = serializer.save()
label.refresh_from_db()
self.assertEqual(label.name, "serializer")
def test_label_serializer_compress_description(self):
serializer = serializers.LabelSerializer(data={"name": "compress", "description": factories.LABEL_DESCRIPTION})
serializer.is_valid()
label = serializer.save()
label.refresh_from_db()
self.assertEqual(label.description, utils.compressed_str(factories.LABEL_DESCRIPTION))
def test_label_serializer_decompress_description(self):
label = factories.LabelFactory(description=utils.compressed_str(factories.LABEL_DESCRIPTION))
serializer = serializers.LabelSerializer(instance=label)
self.assertEqual(serializer.data["description"], factories.LABEL_DESCRIPTION)
def test_create_label(self):
self.assertEqual(0, models.Label.objects.count())
request = self.client.post("/api/v1/labels", {"name": "compress", "description": factories.LABEL_DESCRIPTION})
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Label.objects.count())
def test_get_no_labels(self):
request = self.client.get("/api/v1/labels")
self.assertEqual(0, len(request.data["results"]))
def test_get_labels(self):
label = factories.LabelFactory()
request = self.client.get("/api/v1/labels")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(label.name, request.data["results"][0]["name"])
def test_get_label(self):
label = factories.LabelFactory()
request = self.client.get("/api/v1/labels/%s" % label.id)
self.assertEqual(label.name, request.data["name"])
def test_partial_update_label(self):
label = factories.LabelFactory()
self.assertNotEqual("updated", label.name)
request = self.client.patch("/api/v1/labels/%s" % label.id, {"name": "updated"})
self.assertEqual(200, request.status_code)
label_updated = models.Label.objects.get(id=label.id)
self.assertEqual("updated", label_updated.name)
def test_delete_label(self):
label = factories.LabelFactory()
self.assertEqual(1, models.Label.objects.all().count())
request = self.client.delete("/api/v1/labels/%s" % label.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Label.objects.all().count())

View File

@ -1,120 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import datetime
from django.utils import timezone
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories
class PlayTestCase(APITestCase):
def test_play_factory(self):
play = factories.PlayFactory(name="play factory")
self.assertEqual(play.name, "play factory")
def test_play_serializer(self):
playbook = factories.PlaybookFactory()
serializer = serializers.PlaySerializer(
data={
"name": "serializer",
"status": "completed",
"uuid": "5c5f67b9-e63c-6297-80da-000000000005",
"playbook": playbook.id,
}
)
serializer.is_valid()
play = serializer.save()
play.refresh_from_db()
self.assertEqual(play.name, "serializer")
self.assertEqual(play.status, "completed")
def test_get_no_plays(self):
request = self.client.get("/api/v1/plays")
self.assertEqual(0, len(request.data["results"]))
def test_get_plays(self):
play = factories.PlayFactory()
request = self.client.get("/api/v1/plays")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(play.name, request.data["results"][0]["name"])
def test_delete_play(self):
play = factories.PlayFactory()
self.assertEqual(1, models.Play.objects.all().count())
request = self.client.delete("/api/v1/plays/%s" % play.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Play.objects.all().count())
def test_create_play(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Play.objects.count())
request = self.client.post(
"/api/v1/plays",
{
"name": "create",
"status": "running",
"uuid": "5c5f67b9-e63c-6297-80da-000000000005",
"playbook": playbook.id,
},
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Play.objects.count())
def test_partial_update_play(self):
play = factories.PlayFactory()
self.assertNotEqual("update", play.name)
request = self.client.patch("/api/v1/plays/%s" % play.id, {"name": "update"})
self.assertEqual(200, request.status_code)
play_updated = models.Play.objects.get(id=play.id)
self.assertEqual("update", play_updated.name)
def test_get_play(self):
play = factories.PlayFactory()
request = self.client.get("/api/v1/plays/%s" % play.id)
self.assertEqual(play.name, request.data["name"])
def test_get_play_by_playbook(self):
play = factories.PlayFactory(name="play1")
factories.PlayFactory(name="play2")
request = self.client.get("/api/v1/plays?playbook=1")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(play.name, request.data["results"][0]["name"])
def test_get_play_by_uuid(self):
play = factories.PlayFactory(name="play1", uuid="6b838b6f-cfc7-4e11-a264-73df8683ee0e")
factories.PlayFactory(name="play2")
request = self.client.get("/api/v1/plays?uuid=6b838b6f-cfc7-4e11-a264-73df8683ee0e")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(play.name, request.data["results"][0]["name"])
def test_get_play_duration(self):
started = timezone.now()
ended = started + datetime.timedelta(hours=1)
play = factories.PlayFactory(started=started, ended=ended)
request = self.client.get("/api/v1/plays/%s" % play.id)
self.assertEqual(request.data["duration"], datetime.timedelta(0, 3600))
def test_update_wrong_play_status(self):
play = factories.PlayFactory()
self.assertNotEqual("wrong", play.status)
request = self.client.patch("/api/v1/plays/%s" % play.id, {"status": "wrong"})
self.assertEqual(400, request.status_code)
play_updated = models.Play.objects.get(id=play.id)
self.assertNotEqual("wrong", play_updated.status)

View File

@ -1,132 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import datetime
from django.utils import timezone
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class PlaybookTestCase(APITestCase):
def test_playbook_factory(self):
playbook = factories.PlaybookFactory(ansible_version="2.4.0")
self.assertEqual(playbook.ansible_version, "2.4.0")
def test_playbook_serializer(self):
serializer = serializers.PlaybookSerializer(
data={"name": "serializer-playbook", "ansible_version": "2.4.0", "path": "/path/playbook.yml"}
)
serializer.is_valid()
playbook = serializer.save()
playbook.refresh_from_db()
self.assertEqual(playbook.name, "serializer-playbook")
self.assertEqual(playbook.ansible_version, "2.4.0")
self.assertEqual(playbook.status, "unknown")
def test_playbook_serializer_compress_arguments(self):
serializer = serializers.PlaybookSerializer(
data={"ansible_version": "2.4.0", "path": "/path/playbook.yml", "arguments": factories.PLAYBOOK_ARGUMENTS}
)
serializer.is_valid()
playbook = serializer.save()
playbook.refresh_from_db()
self.assertEqual(playbook.arguments, utils.compressed_obj(factories.PLAYBOOK_ARGUMENTS))
def test_playbook_serializer_decompress_arguments(self):
playbook = factories.PlaybookFactory(arguments=utils.compressed_obj(factories.PLAYBOOK_ARGUMENTS))
serializer = serializers.PlaybookSerializer(instance=playbook)
self.assertEqual(serializer.data["arguments"], factories.PLAYBOOK_ARGUMENTS)
def test_get_no_playbooks(self):
request = self.client.get("/api/v1/playbooks")
self.assertEqual(0, len(request.data["results"]))
def test_get_playbooks(self):
expected_playbook = factories.PlaybookFactory()
request = self.client.get("/api/v1/playbooks")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(1, request.data["count"])
playbook = request.data["results"][0]
self.assertEqual(playbook["ansible_version"], expected_playbook.ansible_version)
self.assertEqual(len(playbook["files"]), 0)
self.assertEqual(len(playbook["hosts"]), 0)
self.assertEqual(len(playbook["tasks"]), 0)
self.assertEqual(len(playbook["records"]), 0)
self.assertEqual(len(playbook["plays"]), 0)
def test_delete_playbook(self):
playbook = factories.PlaybookFactory()
self.assertEqual(1, models.Playbook.objects.all().count())
request = self.client.delete("/api/v1/playbooks/%s" % playbook.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Playbook.objects.all().count())
def test_create_playbook(self):
self.assertEqual(0, models.Playbook.objects.count())
request = self.client.post(
"/api/v1/playbooks", {"ansible_version": "2.4.0", "status": "running", "path": "/path/playbook.yml"}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Playbook.objects.count())
self.assertEqual(request.data["status"], "running")
def test_partial_update_playbook(self):
playbook = factories.PlaybookFactory()
self.assertNotEqual("completed", playbook.status)
request = self.client.patch("/api/v1/playbooks/%s" % playbook.id, {"status": "completed"})
self.assertEqual(200, request.status_code)
playbook_updated = models.Playbook.objects.get(id=playbook.id)
self.assertEqual("completed", playbook_updated.status)
def test_update_wrong_playbook_status(self):
playbook = factories.PlaybookFactory()
self.assertNotEqual("wrong", playbook.status)
request = self.client.patch("/api/v1/playbooks/%s" % playbook.id, {"status": "wrong"})
self.assertEqual(400, request.status_code)
playbook_updated = models.Playbook.objects.get(id=playbook.id)
self.assertNotEqual("wrong", playbook_updated.status)
def test_get_playbook(self):
playbook = factories.PlaybookFactory()
request = self.client.get("/api/v1/playbooks/%s" % playbook.id)
self.assertEqual(playbook.ansible_version, request.data["ansible_version"])
def test_get_playbook_by_name(self):
playbook = factories.PlaybookFactory(name="playbook1")
factories.PlaybookFactory(name="playbook2")
request = self.client.get("/api/v1/playbooks?name=playbook1")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(playbook.name, request.data["results"][0]["name"])
def test_get_playbook_by_status(self):
playbook = factories.PlaybookFactory(status="failed")
factories.PlaybookFactory(status="completed")
request = self.client.get("/api/v1/playbooks?status=failed")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(playbook.status, request.data["results"][0]["status"])
def test_get_playbook_duration(self):
started = timezone.now()
ended = started + datetime.timedelta(hours=1)
playbook = factories.PlaybookFactory(started=started, ended=ended)
request = self.client.get("/api/v1/playbooks/%s" % playbook.id)
self.assertEqual(request.data["duration"], datetime.timedelta(0, 3600))
# TODO: Add tests for incrementally updating files

View File

@ -1,148 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class RecordTestCase(APITestCase):
def test_record_factory(self):
record = factories.RecordFactory(key="test")
self.assertEqual(record.key, "test")
def test_record_serializer(self):
playbook = factories.PlaybookFactory()
serializer = serializers.RecordSerializer(
data={"key": "test", "value": factories.RECORD_LIST, "type": "list", "playbook": playbook.id}
)
serializer.is_valid()
record = serializer.save()
record.refresh_from_db()
self.assertEqual(record.key, "test")
self.assertEqual(record.value, utils.compressed_obj(factories.RECORD_LIST))
self.assertEqual(record.type, "list")
def test_get_no_records(self):
request = self.client.get("/api/v1/records")
self.assertEqual(0, len(request.data["results"]))
def test_get_record(self):
record = factories.RecordFactory()
request = self.client.get("/api/v1/records")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(record.key, request.data["results"][0]["key"])
def test_delete_record(self):
record = factories.RecordFactory()
self.assertEqual(1, models.Record.objects.all().count())
request = self.client.delete("/api/v1/records/%s" % record.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Record.objects.all().count())
def test_create_text_record(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Record.objects.count())
request = self.client.post(
"/api/v1/records", {"key": "test", "value": "value", "type": "text", "playbook": playbook.id}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Record.objects.count())
def test_create_list_record(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Record.objects.count())
test_list = factories.RECORD_LIST
request = self.client.post(
"/api/v1/records", {"key": "listrecord", "value": test_list, "type": "list", "playbook": playbook.id}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Record.objects.count())
self.assertEqual(test_list, request.data["value"])
def test_create_dict_record(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Record.objects.count())
test_dict = {"a": "dictionary"}
request = self.client.post(
"/api/v1/records", {"key": "dictrecord", "value": test_dict, "type": "dict", "playbook": playbook.id}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Record.objects.count())
self.assertEqual(test_dict, request.data["value"])
def test_create_json_record(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Record.objects.count())
test_json = '{"a": "dictionary"}'
request = self.client.post(
"/api/v1/records", {"key": "dictrecord", "value": test_json, "type": "json", "playbook": playbook.id}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Record.objects.count())
self.assertEqual(test_json, request.data["value"])
def test_create_url_record(self):
playbook = factories.PlaybookFactory()
self.assertEqual(0, models.Record.objects.count())
test_url = "https://ara.recordsansible.org"
request = self.client.post(
"/api/v1/records", {"key": "dictrecord", "value": test_url, "type": "url", "playbook": playbook.id}
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Record.objects.count())
self.assertEqual(test_url, request.data["value"])
def test_partial_update_record(self):
record = factories.RecordFactory()
self.assertNotEqual("update", record.key)
request = self.client.patch("/api/v1/records/%s" % record.id, {"key": "update"})
self.assertEqual(200, request.status_code)
record_updated = models.Record.objects.get(id=record.id)
self.assertEqual("update", record_updated.key)
def test_get_records_by_playbook(self):
playbook = factories.PlaybookFactory()
record = factories.RecordFactory(playbook=playbook, key="by_playbook")
factories.RecordFactory(key="another_record")
request = self.client.get("/api/v1/records?playbook=%s" % playbook.id)
self.assertEqual(2, models.Record.objects.all().count())
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(record.key, request.data["results"][0]["key"])
self.assertEqual(record.playbook.id, request.data["results"][0]["playbook"])
def test_get_records_by_key(self):
playbook = factories.PlaybookFactory()
record = factories.RecordFactory(playbook=playbook, key="by_key")
factories.RecordFactory(key="another_record")
request = self.client.get("/api/v1/records?key=%s" % record.key)
self.assertEqual(2, models.Record.objects.all().count())
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(record.key, request.data["results"][0]["key"])
self.assertEqual(record.playbook.id, request.data["results"][0]["playbook"])
def test_get_records_by_playbook_and_key(self):
playbook = factories.PlaybookFactory()
record = factories.RecordFactory(playbook=playbook, key="by_playbook_and_key")
factories.RecordFactory(playbook=playbook, key="another_record_in_playbook")
factories.RecordFactory(key="another_record_in_another_playbook")
request = self.client.get("/api/v1/records?playbook=%s&key=%s" % (playbook.id, record.key))
self.assertEqual(3, models.Record.objects.all().count())
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(record.key, request.data["results"][0]["key"])
self.assertEqual(record.playbook.id, request.data["results"][0]["playbook"])

View File

@ -1,134 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class ResultTestCase(APITestCase):
def test_result_factory(self):
result = factories.ResultFactory(status="failed")
self.assertEqual(result.status, "failed")
def test_result_serializer(self):
host = factories.HostFactory()
task = factories.TaskFactory()
serializer = serializers.ResultSerializer(
data={"status": "skipped", "host": host.id, "task": task.id, "playbook": task.playbook.id}
)
serializer.is_valid()
result = serializer.save()
result.refresh_from_db()
self.assertEqual(result.status, "skipped")
self.assertEqual(result.host.id, host.id)
self.assertEqual(result.task.id, task.id)
def test_result_serializer_compress_content(self):
host = factories.HostFactory()
task = factories.TaskFactory()
serializer = serializers.ResultSerializer(
data={"host": host.id, "task": task.id, "content": factories.RESULT_CONTENTS, "playbook": task.playbook.id}
)
serializer.is_valid()
result = serializer.save()
result.refresh_from_db()
self.assertEqual(result.content, utils.compressed_obj(factories.RESULT_CONTENTS))
def test_result_serializer_decompress_content(self):
result = factories.ResultFactory(content=utils.compressed_obj(factories.RESULT_CONTENTS))
serializer = serializers.ResultSerializer(instance=result)
self.assertEqual(serializer.data["content"], factories.RESULT_CONTENTS)
def test_get_no_results(self):
request = self.client.get("/api/v1/results")
self.assertEqual(0, len(request.data["results"]))
def test_get_results(self):
result = factories.ResultFactory()
request = self.client.get("/api/v1/results")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(result.status, request.data["results"][0]["status"])
def test_delete_result(self):
result = factories.ResultFactory()
self.assertEqual(1, models.Result.objects.all().count())
request = self.client.delete("/api/v1/results/%s" % result.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Result.objects.all().count())
def test_create_result(self):
host = factories.HostFactory()
task = factories.TaskFactory()
self.assertEqual(0, models.Result.objects.count())
request = self.client.post(
"/api/v1/results",
{
"status": "ok",
"host": host.id,
"task": task.id,
"content": factories.RESULT_CONTENTS,
"playbook": task.playbook.id,
},
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Result.objects.count())
def test_partial_update_result(self):
result = factories.ResultFactory()
self.assertNotEqual("unreachable", result.status)
request = self.client.patch("/api/v1/results/%s" % result.id, {"status": "unreachable"})
self.assertEqual(200, request.status_code)
result_updated = models.Result.objects.get(id=result.id)
self.assertEqual("unreachable", result_updated.status)
def test_get_result(self):
result = factories.ResultFactory()
request = self.client.get("/api/v1/results/%s" % result.id)
self.assertEqual(result.status, request.data["status"])
def test_get_result_by_playbook(self):
playbook = factories.PlaybookFactory()
host_one = factories.HostFactory(name="one")
host_two = factories.HostFactory(name="two")
result = factories.ResultFactory(playbook=playbook, host=host_one, status="failed")
factories.ResultFactory(playbook=playbook, host=host_two, status="skipped")
request = self.client.get("/api/v1/results?playbook=%s" % playbook.id)
self.assertEqual(2, len(request.data["results"]))
self.assertEqual(result.status, request.data["results"][0]["status"])
self.assertEqual("skipped", request.data["results"][1]["status"])
def test_get_result_by_statuses(self):
failed_result = factories.ResultFactory(status="failed")
skipped_result = factories.ResultFactory(status="skipped")
factories.ResultFactory(status="ok")
results = self.client.get("/api/v1/results").data["results"]
self.assertEqual(3, len(results))
results = self.client.get("/api/v1/results?status=failed").data["results"]
self.assertEqual(1, len(results))
self.assertEqual(failed_result.status, results[0]["status"])
results = self.client.get("/api/v1/results?status=skipped").data["results"]
self.assertEqual(1, len(results))
self.assertEqual(skipped_result.status, results[0]["status"])
results = self.client.get("/api/v1/results?status=failed&status=skipped").data["results"]
self.assertEqual(2, len(results))
self.assertEqual(failed_result.status, results[0]["status"])
self.assertEqual(skipped_result.status, results[1]["status"])

View File

@ -1,103 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories
class StatsTestCase(APITestCase):
def test_stats_factory(self):
stats = factories.StatsFactory(changed=2, failed=1, ok=3, skipped=2, unreachable=1)
self.assertEqual(stats.changed, 2)
self.assertEqual(stats.failed, 1)
self.assertEqual(stats.ok, 3)
self.assertEqual(stats.skipped, 2)
self.assertEqual(stats.unreachable, 1)
def test_stats_serializer(self):
playbook = factories.PlaybookFactory()
host = factories.HostFactory()
serializer = serializers.StatsSerializer(data=dict(playbook=playbook.id, host=host.id, ok=9001))
serializer.is_valid()
stats = serializer.save()
stats.refresh_from_db()
self.assertEqual(stats.playbook.id, playbook.id)
self.assertEqual(stats.host.id, host.id)
self.assertEqual(stats.ok, 9001)
def test_create_stats(self):
playbook = factories.PlaybookFactory()
host = factories.HostFactory()
self.assertEqual(0, models.Stats.objects.count())
request = self.client.post("/api/v1/stats", dict(playbook=playbook.id, host=host.id, ok=9001))
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Stats.objects.count())
def test_get_no_stats(self):
request = self.client.get("/api/v1/stats")
self.assertEqual(0, len(request.data["results"]))
def test_get_stats(self):
stats = factories.StatsFactory()
request = self.client.get("/api/v1/stats")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(stats.ok, request.data["results"][0]["ok"])
def test_get_stats_by_playbook(self):
playbook = factories.PlaybookFactory()
host_one = factories.HostFactory(name="one")
host_two = factories.HostFactory(name="two")
stats = factories.StatsFactory(host=host_one, playbook=playbook, ok=9001)
factories.StatsFactory(host=host_two, playbook=playbook)
request = self.client.get("/api/v1/stats?playbook=%s" % playbook.id)
self.assertEqual(2, len(request.data["results"]))
self.assertEqual(host_one.id, request.data["results"][0]["id"])
self.assertEqual(stats.ok, request.data["results"][0]["ok"])
self.assertEqual(host_two.id, request.data["results"][1]["id"])
def test_get_stats_by_host(self):
playbook = factories.PlaybookFactory()
host_one = factories.HostFactory(name="one")
host_two = factories.HostFactory(name="two")
stats = factories.StatsFactory(host=host_one, playbook=playbook, ok=9001)
factories.StatsFactory(host=host_two, playbook=playbook)
request = self.client.get("/api/v1/stats?host=%s" % host_one.id)
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(stats.ok, request.data["results"][0]["ok"])
self.assertEqual(host_one.id, request.data["results"][0]["id"])
def test_get_stats_id(self):
stats = factories.StatsFactory()
request = self.client.get("/api/v1/stats/%s" % stats.id)
self.assertEqual(stats.ok, request.data["ok"])
def test_partial_update_stats(self):
stats = factories.StatsFactory()
self.assertNotEqual(9001, stats.ok)
request = self.client.patch("/api/v1/stats/%s" % stats.id, dict(ok=9001))
self.assertEqual(200, request.status_code)
stats_updated = models.Stats.objects.get(id=stats.id)
self.assertEqual(9001, stats_updated.ok)
def test_delete_stats(self):
stats = factories.StatsFactory()
self.assertEqual(1, models.Stats.objects.all().count())
request = self.client.delete("/api/v1/stats/%s" % stats.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Stats.objects.all().count())

View File

@ -1,151 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import datetime
from django.utils import timezone
from rest_framework.test import APITestCase
from ara.api import models, serializers
from ara.api.tests import factories, utils
class TaskTestCase(APITestCase):
def test_task_factory(self):
task = factories.TaskFactory(name="factory")
self.assertEqual(task.name, "factory")
def test_task_serializer(self):
play = factories.PlayFactory()
file = factories.FileFactory()
serializer = serializers.TaskSerializer(
data={
"name": "serializer",
"action": "test",
"lineno": 2,
"status": "completed",
"handler": False,
"play": play.id,
"file": file.id,
"playbook": play.playbook.id,
}
)
serializer.is_valid()
task = serializer.save()
task.refresh_from_db()
self.assertEqual(task.name, "serializer")
self.assertEqual(task.status, "completed")
def test_task_serializer_compress_tags(self):
play = factories.PlayFactory()
file = factories.FileFactory()
serializer = serializers.TaskSerializer(
data={
"name": "compress",
"action": "test",
"lineno": 2,
"status": "running",
"handler": False,
"play": play.id,
"file": file.id,
"tags": factories.TASK_TAGS,
"playbook": play.playbook.id,
}
)
serializer.is_valid()
task = serializer.save()
task.refresh_from_db()
self.assertEqual(task.tags, utils.compressed_obj(factories.TASK_TAGS))
def test_task_serializer_decompress_tags(self):
task = factories.TaskFactory(tags=utils.compressed_obj(factories.TASK_TAGS))
serializer = serializers.TaskSerializer(instance=task)
self.assertEqual(serializer.data["tags"], factories.TASK_TAGS)
def test_get_no_tasks(self):
request = self.client.get("/api/v1/tasks")
self.assertEqual(0, len(request.data["results"]))
def test_get_tasks(self):
task = factories.TaskFactory()
request = self.client.get("/api/v1/tasks")
self.assertEqual(1, len(request.data["results"]))
self.assertEqual(task.name, request.data["results"][0]["name"])
def test_delete_task(self):
task = factories.TaskFactory()
self.assertEqual(1, models.Task.objects.all().count())
request = self.client.delete("/api/v1/tasks/%s" % task.id)
self.assertEqual(204, request.status_code)
self.assertEqual(0, models.Task.objects.all().count())
def test_create_task(self):
play = factories.PlayFactory()
file = factories.FileFactory()
self.assertEqual(0, models.Task.objects.count())
request = self.client.post(
"/api/v1/tasks",
{
"name": "create",
"action": "test",
"lineno": 2,
"handler": False,
"status": "running",
"play": play.id,
"file": file.id,
"playbook": play.playbook.id,
},
)
self.assertEqual(201, request.status_code)
self.assertEqual(1, models.Task.objects.count())
def test_partial_update_task(self):
task = factories.TaskFactory()
self.assertNotEqual("update", task.name)
request = self.client.patch("/api/v1/tasks/%s" % task.id, {"name": "update"})
self.assertEqual(200, request.status_code)
task_updated = models.Task.objects.get(id=task.id)
self.assertEqual("update", task_updated.name)
def test_get_task(self):
task = factories.TaskFactory()
request = self.client.get("/api/v1/tasks/%s" % task.id)
self.assertEqual(task.name, request.data["name"])
def test_get_tasks_by_playbook(self):
playbook = factories.PlaybookFactory()
task = factories.TaskFactory(name="task1", playbook=playbook)
factories.TaskFactory(name="task2", playbook=playbook)
request = self.client.get("/api/v1/tasks?playbook=%s" % playbook.id)
self.assertEqual(2, len(request.data["results"]))
self.assertEqual(task.name, request.data["results"][0]["name"])
self.assertEqual("task2", request.data["results"][1]["name"])
def test_get_task_duration(self):
started = timezone.now()
ended = started + datetime.timedelta(hours=1)
task = factories.TaskFactory(started=started, ended=ended)
request = self.client.get("/api/v1/tasks/%s" % task.id)
self.assertEqual(request.data["duration"], datetime.timedelta(0, 3600))
def test_update_wrong_task_status(self):
task = factories.TaskFactory()
self.assertNotEqual("wrong", task.status)
request = self.client.patch("/api/v1/tasks/%s" % task.id, {"status": "wrong"})
self.assertEqual(400, request.status_code)
task_updated = models.Task.objects.get(id=task.id)
self.assertNotEqual("wrong", task_updated.status)

View File

@ -1,25 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.test import APITestCase
class InfoTestCase(APITestCase):
def test_info_endpoint(self):
result = self.client.get("/api/v1/info")
self.assertEqual(set(result.data.keys()), set(["python_version", "ara_version"]))
self.assertTrue(result.data["python_version"].startswith("3."))

View File

@ -1,41 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import hashlib
import json
import zlib
def compressed_obj(obj):
"""
Returns a zlib compressed representation of an object
"""
return zlib.compress(json.dumps(obj).encode("utf-8"))
def compressed_str(obj):
"""
Returns a zlib compressed representation of a string
"""
return zlib.compress(obj.encode("utf-8"))
def sha1(obj):
"""
Returns the sha1 of a compressed string or an object
"""
return hashlib.sha1(obj.encode("utf8")).hexdigest()

View File

@ -1,34 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
from rest_framework.routers import DefaultRouter
from ara.api import views
router = DefaultRouter(trailing_slash=False)
router.register("labels", views.LabelViewSet, base_name="label")
router.register("playbooks", views.PlaybookViewSet, base_name="playbook")
router.register("plays", views.PlayViewSet, base_name="play")
router.register("tasks", views.TaskViewSet, base_name="task")
router.register("hosts", views.HostViewSet, base_name="host")
router.register("results", views.ResultViewSet, base_name="result")
router.register("files", views.FileViewSet, base_name="file")
router.register("records", views.RecordViewSet, base_name="record")
router.register("stats", views.StatsViewSet, base_name="stats")
router.register("info", views.InfoView, base_name="info")
urlpatterns = router.urls

View File

@ -1,91 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import sys
import pbr.version
from rest_framework import viewsets
from rest_framework.response import Response
from ara.api import models, serializers
class InfoView(viewsets.ViewSet):
def list(self, request):
return Response(
{
"python_version": ".".join(map(str, sys.version_info[:3])),
"ara_version": pbr.version.VersionInfo("ara-server").release_string(),
}
)
class LabelViewSet(viewsets.ModelViewSet):
queryset = models.Label.objects.all()
serializer_class = serializers.LabelSerializer
class PlaybookViewSet(viewsets.ModelViewSet):
queryset = models.Playbook.objects.all()
serializer_class = serializers.PlaybookSerializer
filter_fields = ("name", "status")
class PlayViewSet(viewsets.ModelViewSet):
queryset = models.Play.objects.all()
serializer_class = serializers.PlaySerializer
filter_fields = ("playbook", "uuid")
class TaskViewSet(viewsets.ModelViewSet):
queryset = models.Task.objects.all()
serializer_class = serializers.TaskSerializer
filter_fields = ("playbook",)
class HostViewSet(viewsets.ModelViewSet):
queryset = models.Host.objects.all()
serializer_class = serializers.HostSerializer
filter_fields = ("playbook",)
class ResultViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ResultSerializer
filter_fields = ("playbook",)
def get_queryset(self):
statuses = self.request.GET.getlist("status")
if statuses:
return models.Result.objects.filter(status__in=statuses)
return models.Result.objects.all()
class FileViewSet(viewsets.ModelViewSet):
queryset = models.File.objects.all()
serializer_class = serializers.FileSerializer
filter_fields = ("playbook", "path")
class RecordViewSet(viewsets.ModelViewSet):
queryset = models.Record.objects.all()
serializer_class = serializers.RecordSerializer
filter_fields = ("playbook", "key")
class StatsViewSet(viewsets.ModelViewSet):
queryset = models.Stats.objects.all()
serializer_class = serializers.StatsSerializer
filter_fields = ("playbook", "host")

View File

View File

@ -1,15 +0,0 @@
#!/usr/bin/env python
import os
import sys
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ara.server.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

View File

@ -1,6 +0,0 @@
from django.contrib import admin
class AraAdminSite(admin.AdminSite):
site_header = "Administration"
index_title = "Administration Ara"

View File

@ -1,5 +0,0 @@
from django.contrib.admin.apps import AdminConfig
class AraAdminConfig(AdminConfig):
default_site = "ara.server.admin.AraAdminSite"

View File

@ -1,225 +0,0 @@
import logging
import logging.config
import os
import textwrap
import yaml
from django.utils.crypto import get_random_string
from dynaconf import LazySettings
BASE_DIR = os.environ.get("ARA_BASE_DIR", os.path.expanduser("~/.ara/server"))
DEFAULT_SETTINGS = os.path.join(BASE_DIR, "settings.yaml")
settings = LazySettings(
GLOBAL_ENV_FOR_DYNACONF="ARA", ENVVAR_FOR_DYNACONF="ARA_SETTINGS", SETTINGS_MODULE_FOR_DYNACONF=DEFAULT_SETTINGS
)
# reread BASE_DIR since it might have gotten changed in the config file.
BASE_DIR = settings.get("BASE_DIR", BASE_DIR)
# Django doesn't set up logging until it's too late to use it in settings.py.
# Set it up from the configuration so we can use it.
DEBUG = settings.get("DEBUG", False, "@bool")
LOG_LEVEL = settings.get("LOG_LEVEL", "INFO")
# fmt: off
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"normal": {"format": "%(asctime)s %(levelname)s %(name)s: %(message)s"}},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "normal",
"level": LOG_LEVEL,
"stream": "ext://sys.stdout",
}
},
"loggers": {
"ara": {
"handlers": ["console"],
"level": LOG_LEVEL,
"propagate": 0
}
},
"root": {
"handlers": ["console"],
"level": LOG_LEVEL
},
}
# fmt: on
logging.config.dictConfig(LOGGING)
logger = logging.getLogger(__name__)
logger.debug("Loaded logging configuration")
# Django built-in server and npm development server
ALLOWED_HOSTS = settings.get("ALLOWED_HOSTS", ["::1", "127.0.0.1", "localhost"])
CORS_ORIGIN_WHITELIST = settings.get("CORS_ORIGIN_WHITELIST", ["127.0.0.1:8000", "localhost:3000"])
CORS_ORIGIN_ALLOW_ALL = settings.get("CORS_ORIGIN_ALLOW_ALL", False)
ADMINS = settings.get("ADMINS", ())
READ_LOGIN_REQUIRED = settings.get("READ_LOGIN_REQUIRED", False, "@bool")
WRITE_LOGIN_REQUIRED = settings.get("WRITE_LOGIN_REQUIRED", False, "@bool")
EXTERNAL_AUTH = settings.get("EXTERNAL_AUTH", False, "@bool")
def get_secret_key():
if not settings.get("SECRET_KEY"):
logger.warn(f"No setting found for SECRET_KEY. Generating a random key...")
return get_random_string(length=50)
return settings.get("SECRET_KEY")
SECRET_KEY = get_secret_key()
# We're not expecting ARA to use multiple concurrent databases.
# Make it easier for users to specify the configuration for a single database.
DATABASE_ENGINE = settings.get("DATABASE_ENGINE", "django.db.backends.sqlite3")
DATABASE_NAME = settings.get("DATABASE_NAME", os.path.join(BASE_DIR, "ansible.sqlite"))
DATABASE_USER = settings.get("DATABASE_USER", None)
DATABASE_PASSWORD = settings.get("DATABASE_PASSWORD", None)
DATABASE_HOST = settings.get("DATABASE_HOST", None)
DATABASE_PORT = settings.get("DATABASE_PORT", None)
DATABASES = {
"default": {
"ENGINE": DATABASE_ENGINE,
"NAME": DATABASE_NAME,
"USER": DATABASE_USER,
"PASSWORD": DATABASE_PASSWORD,
"HOST": DATABASE_HOST,
"PORT": DATABASE_PORT,
}
}
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"corsheaders",
"rest_framework",
"django_filters",
"ara.api",
"ara.server.apps.AraAdminConfig",
]
EXTERNAL_AUTH_MIDDLEWARE = []
if EXTERNAL_AUTH:
EXTERNAL_AUTH_MIDDLEWARE = ["django.contrib.auth.middleware.RemoteUserMiddleware"]
AUTHENTICATION_BACKENDS = ["django.contrib.auth.backends.RemoteUserBackend"]
# fmt: off
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
] + EXTERNAL_AUTH_MIDDLEWARE + [
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware"
]
# fmt: on
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
]
},
}
]
AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
USE_TZ = True
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = "en-us"
STATIC_URL = settings.get("STATIC_URL", "/static/")
STATIC_ROOT = settings.get("STATIC_ROOT", os.path.join(BASE_DIR, "www", "static"))
MEDIA_URL = settings.get("MEDIA_URL", "/media/")
MEDIA_ROOT = settings.get("MEDIA_ROOT", os.path.join(BASE_DIR, "www", "media"))
WSGI_APPLICATION = "ara.server.wsgi.application"
ROOT_URLCONF = "ara.server.urls"
APPEND_SLASH = False
REST_FRAMEWORK = {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 100,
"DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
"DEFAULT_RENDERER_CLASSES": (
"rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer",
),
"DEFAULT_PARSER_CLASSES": (
"rest_framework.parsers.JSONParser",
"rest_framework.parsers.FormParser",
"rest_framework.parsers.MultiPartParser",
),
"DEFAULT_AUTHENTICATION_CLASSES": ("rest_framework.authentication.BasicAuthentication",),
"DEFAULT_PERMISSION_CLASSES": ("ara.api.auth.APIAccessPermission",),
"TEST_REQUEST_DEFAULT_FORMAT": "json",
}
ARA_SETTINGS = os.getenv("ARA_SETTINGS", DEFAULT_SETTINGS)
logger.info(f"Using settings file: {ARA_SETTINGS}")
# TODO: Split this out to a CLI command (django-admin command ?)
# Ensure default base configuration/data directory exists
if not os.path.isdir(BASE_DIR):
logger.info(f"Creating data & configuration directory: {BASE_DIR}")
os.makedirs(BASE_DIR, mode=0o700)
if not os.path.exists(DEFAULT_SETTINGS) and "ARA_SETTINGS" not in os.environ:
SETTINGS = dict(
BASE_DIR=BASE_DIR,
ALLOWED_HOSTS=ALLOWED_HOSTS,
CORS_ORIGIN_WHITELIST=CORS_ORIGIN_WHITELIST,
CORS_ORIGIN_ALLOW_ALL=CORS_ORIGIN_ALLOW_ALL,
SECRET_KEY=SECRET_KEY,
DATABASES=DATABASES,
STATIC_URL=STATIC_URL,
STATIC_ROOT=STATIC_ROOT,
MEDIA_URL=MEDIA_URL,
MEDIA_ROOT=MEDIA_ROOT,
DEBUG=DEBUG,
LOG_LEVEL=LOG_LEVEL,
LOGGING=LOGGING,
READ_LOGIN_REQUIRED=READ_LOGIN_REQUIRED,
WRITE_LOGIN_REQUIRED=WRITE_LOGIN_REQUIRED,
)
with open(DEFAULT_SETTINGS, "w+") as settings_file:
comment = f"""
---
# This is a default settings template generated by ARA.
# To use a settings file such as this one, you need to export the
# ARA_SETTINGS environment variable like so:
# $ export ARA_SETTINGS="{DEFAULT_SETTINGS}"
"""
logger.info(f"Writing default settings to {DEFAULT_SETTINGS}")
settings_file.write(textwrap.dedent(comment))
yaml.dump({"default": SETTINGS}, settings_file, default_flow_style=False)

View File

@ -1,4 +0,0 @@
from django.contrib import admin
from django.urls import include, path
urlpatterns = [path("api/v1/", include("ara.api.urls")), path("admin/", admin.site.urls)]

View File

View File

@ -1,7 +0,0 @@
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ara.server.settings")
application = get_wsgi_application()

View File

@ -1,7 +0,0 @@
graph source files
==================
These are exports from the ARA diagrams and graphs made through draw.io.
We're keeping them for version control purposes but the documentation uses
actual images built from these from the ``doc/source/_static/graphs`` directory.

View File

@ -1 +0,0 @@
<mxfile userAgent="Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0" version="9.1.8" editor="www.draw.io" type="device"><diagram id="9906a0a6-bcd4-fe14-221d-85032a32ce87" name="Page-1">7Zxbc5s4FIB/DTPtQzISdx4T95Kd6c5mms5eHmWQbTYycgHnsr9+JZAwSGDjGDtugjvTwBFIQufjHOlIwrAmy6evKVotfqcRJoYJoifD+mSYJvRcl/3hkmchAVZQSuZpHAnZRnAX/4flhUK6jiOcNS7MKSV5vGoKQ5okOMwbMpSm9LF52YySZqkrNMea4C5ERJf+FUf5QkghAJuEGxzPF6Jo3xEJUxTez1O6TkR5hmnNil+ZvEQyL3F9tkARfayJrM+GNUkpzcuj5dMEE964stnK+750pFb1TnGS97nBEXp5QGQtnn1Fs3ye4uwnEVXMn2WzFA+G+a3QsK4fF3GO71Yo5KmPjAQmW+RLIpKrR+Mnc4IyrhPAjkO6jEMhJ2iKyXXVaBNKaMqSEppgnkWe0nsshawt3eJXpUjd8JxmMSG1K2cO/8flNMm/oGVMOIt/4jRCCRJiwR00xXntdlD8mByReJ4wWcgaFLPEa72FRaM/4DTHTzWRaPGvmC5xnj6zS0SqZ1vlLeL1sMXr8rhBzRN8LGqQ2RJwAfe8ynijYHYgdNyhb1/Tt2G6hJVwHcUPPHPxvEz6c80pvBZPXp2zo7n4W9zHW66BibyQJ1xkRRtfsQuguXqq5wJmJTkbmdSOVtTyuaCxLI89YllksxpMXDyBlL41dL+twzhibQMmNMkof6wGw/apGZYkCYY9X2PYDVoYBoczbO5guCQApehiRdbzOMm6ENHu+cA8AOEm/KNMnKZ7csbQWfHD9ZJ8i2eYxAUNK5zG7Dl5438iQny7ke3ikbm5HLFb0uqcELTK4mlRKldxisN1msUP+Dsu37hCStc5L2lSecni0sab0ED93VtmCzYtM5QdkhrWgaNjzV6HAbjWfbGGVw2KFY2TvCjOuTacTwplNM0XdE4TROqcbXQPBtR9pZKduv9S/E6i+8pK9Fa+9K9C94GuetjilZ0BLFrQZtFGze+heU3LbTD01bwJdGd2LNV7UzRFMLSnoenN7Cm4sPo6t5DEmGPQ37kVN4yu7X26Ntuxd7u2FsgHcW0a5bAN89HivRCGTiPyUt8HITyd83NGFI7q/Nrp6I2C7146r+cO7b7uMMPpQxGm6OkNr25/G13h+3SFLvTOyBXq5i/7SRgoOpwfIjxDa8K7cCOPb4hHz/Wkid1CpG+fikh9NHqzXqJkpO5NUQfVLp+OXNssxHGQG0NfxxwO7B0Ks0CDDc/r1QE0rWOMFN0RjdfsKzmu4ptM2+5Fw3HiBp5Gw+0fdz8ygy8Q4P8tWL8JsL79Nkb408chIleivaY0z+mSJeAkuuKrB7iM0PB+p9J7KgxHc3wnqoLJlD5+3giuCwFLkLXahmCnQnkJDUGO0jnusgfyncroOhVzsF0hmk4wwCWoSEgxQTlzyI0atOld5HbLX9JNVo6sjyTMUbIo6ynu2tDDdIWea5eJd7+7HNNuLWcDY5lj+92ub22vZdnkWi03GckL6WyW4dxQ34OqjV/4aow+9DUNpQ8UuOT09y6neQwzKZcX1Vi4Qw+4MpMRytkdGR6t5DYrGfSxkm47FQeaRDdQaPLNXiZRy8h3rO0ZdVitQSwS1ChESTGSu1gR9Dyl9P6dAbgVpaAV0sHRkkv+qsnOfs5Wywf6zUECDIJeZO3rtSEM1OiIKKnVbw8Crh51noiVQdx6M26ztwkuforzv2vH/3BXf+kCW5zXOgNFF6C/pd1uRIFxDNJNZZ1ltep2X9Qtx1IHQWpWA8FeLQVRyhkKdUcn+45RmYk+wRun+tJqcu07+3Jdx9jsa7A3IybgivHrgWRbnoKj5b2MbDsASkb2gVyfethjakBflX0MjeUxXP1Lh6utZo+4LV4N5RjsBAtY9BHWNuM5jrb3i1ib++JhN6d0e0ash1iyAMG4lunEC1jMfVCoXNopAjG6VbhhJTAJwQ/FJrlHmt7PCNMeO1zgpOgKhDSN4mRe9cHALGUdKxNUjqwM2qBG4AZM+SNffb/SWDt8q8srO5wz2+qiTZRqOLkyVFTnyR3Atvjdq4HjF+/Dgs19WGJtCeudFT0iE7BGZU/H62iCmx8/bj8aO3dexZ0rpVgb5wpxDVzkkKDGhRBpqlQHIMs4igo42hDvsJjAaN/QBYYatHSB2cvQbefQUZYtmTK0VzdsVptlG4JEfRr2w6wgBaOQG7gcZfeGOSkMWrZmYBTHOA8v9eVK7wkKeFwoYKDGOFpW7rpHgiLQowktSy0//YuSOe29MrPm4pZyZ3nKhk9p51aHs6NrIMd6oMkprhPNYg5Dm282TVCbBWobgw2yTlyf+v+O83XK93cKm/NGo7JGe0h13/kFOcten/QqF98PP33lNScZLLmjat/4lAN3ZDTc9JWcvhj56seX3LfRwKljn92BOKlRSstyXoaT5e3IaDicINAjkzfFjCdrDYHVCFMFk6/DJAIrg9NkAQUCdaTWlyZTqlhm5IDLfjztOy3UVeWhpoUqp70thlVDL+T9Ga7yzlDCgT3jOo6bkFidyXCdPlSdrb7Q6SzVei7OlgDhgcipc+WWo0yzvHTS/fD5mo5yVOBEhTvrBdrrNRygeu9PmpH+PX8emwp9PJ3pkagIYX8W/pJjgG3vUYSyRVUdfnKLcvZYSSExi3l94/BhQaDsp3L06Lv8HMPQQ1AI9N0quukawXgdMNTFRrDlM0HHI0Pv0FsjGWdChg2bC11gYJ6OjJbJW3sk40zIcFwlzN0y0X88MvQlq85IxpmQ4ZlKJ9PWw4/HI0MfzrsjGWdChmozLBk2PAkZ+iStN5JxJmTYphrxOyUZelTFH8k4EzLUsYnl6p+5OR4Z+lc/gpGMMyEDAmU/qg9bPoE0EBvsdPO57zIytvmouvX5fw==</diagram></mxfile>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

View File

@ -1,7 +0,0 @@
graph image files
=================
These are image files for the ARA diagrams and graphs made through draw.io.
The source files used to generate these graphs are located in
``doc/source/_graphs``.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

View File

@ -1,23 +0,0 @@
Architecture and Workflows
==========================
Recording data from Ansible
---------------------------
.. image:: _static/graphs/recording-workflow.png
0. A human (*or a system, script, etc.*) installs ARA and configures Ansible to use the ARA callback
1. A human (*or a system, script, etc.*) executes an ``ansible-playbook`` command
2. Ansible sends hooks for every event to `callback plugins`_ (``v2_playbook_on_start``, ``v2_runner_on_failed``, etc.)
3. The callback plugin, provided by ara-plugins_, organizes the data sent by Ansible and sends it to the API client
4. The API client, provided by ara-clients_, takes care of actually sending the data to the API over HTTP or locally offline through an internal implementation
5. The API server, provided by ara-server_, receives the POST from the client, validates it and sends it to the database model backend
6. The API server sends a response back to the client with the results
7. The API client sends the response back to the callback with the results
8. The callback plugin returns, ending the callback hook
9. Ansible continues running until it is complete (back to step 2)
.. _callback plugins: https://docs.ansible.com/ansible/latest/plugins/callback.html
.. _ara-plugins: https://github.com/openstack/ara-plugins
.. _ara-clients: https://github.com/openstack/ara-clients
.. _ara-server: https://github.com/openstack/ara-server

View File

@ -1,87 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA Records Ansible.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import sphinx_rtd_theme
import pbr.version
version_info = pbr.version.VersionInfo('ara-server')
sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosectionlabel'
]
# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'ara-server'
copyright = u'2018, Red Hat'
author = 'OpenStack community'
# The short X.Y version.
version = version_info.version_string()
# The full version, including alpha/beta/rc tags.
release = version_info.release_string()
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_static_path = ['_static']
# Output file base name for HTML help builder.
htmlhelp_basename = '%sdoc' % project
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index',
'%s.tex' % project,
u'%s Documentation' % project,
u'Red Hat', 'manual'),
]
# Example configuration for intersphinx: refer to the Python standard library.
#intersphinx_mapping = {'http://docs.python.org/': None}

View File

@ -1,415 +0,0 @@
.. _configuring:
ara-server configuration
========================
ara-server ships with sane defaults, supports the notion of different
environments (*such as dev, staging, prod*) and allows you to customize the
configuration with files, environment variables or a combination of both.
ara-server is a Django application that leverages django-rest-framework.
Both `Django <https://docs.djangoproject.com/en/2.1/ref/settings/>`_ and
`django-rest-framework <https://www.django-rest-framework.org/api-guide/settings/>`_
have extensive configuration options which are not necessarily exposed or made
customizable by ARA for the sake of simplicity.
Overview
--------
This is a brief overview of the different configuration options for ara-server.
For more details, click on the configuration parameters.
+--------------------------------+------------------------------------------------------+------------------------------------------+
| Environment Variable | Usage | default |
+================================+======================================================+==========================================+
| ARA_BASE_DIR_ | Default directory for storing data and configuration | ``~/.ara/server`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_SETTINGS_ | Path to an ara-server configuration file | ``None`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_ENV_ | Environment to load configuration for | ``default`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_READ_LOGIN_REQUIRED_ | Whether authentication is required for reading data | ``False`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_WRITE_LOGIN_REQUIRED_ | Whether authentication is required for writing data | ``False`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_ENV_ | Environment to load configuration for | ``development`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_LOG_LEVEL_ | Log level of the different components | ``INFO`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_LOGGING_ | Logging configuration | See ARA_LOGGING_ |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_CORS_ORIGIN_WHITELIST_ | django-cors-headers's CORS_ORIGIN_WHITELIST_ setting | ``["127.0.0.1:8000", "localhost:3000"]`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_ALLOWED_HOSTS_ | Django's ALLOWED_HOSTS_ setting | ``["127.0.0.1", "localhost", "::1"]`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_STATIC_ROOT_ | Django's STATIC_ROOT_ setting | ``~/.ara/server/www/static`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DEBUG_ | Django's DEBUG_ setting | ``false`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_SECRET_KEY_ | Django's SECRET_KEY_ setting | Randomized token, see ARA_SECRET_KEY_ |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DATABASE_ENGINE_ | Django's ENGINE_ database setting | ``django.db.backends.sqlite3`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DATABASE_NAME_ | Django's NAME_ database setting | ``~/.ara/server/ansible.sqlite`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DATABASE_USER_ | Django's USER_ database setting | ``None`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DATABASE_PASSWORD_ | Django's PASSWORD_ database setting | ``None`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DATABASE_HOST_ | Django's HOST_ database setting | ``None`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
| ARA_DATABASE_PORT_ | Django's PORT_ database setting | ``None`` |
+--------------------------------+------------------------------------------------------+------------------------------------------+
.. _CORS_ORIGIN_WHITELIST: https://github.com/ottoyiu/django-cors-headers
.. _STATIC_ROOT: https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-STATIC_ROOT
.. _ALLOWED_HOSTS: https://docs.djangoproject.com/en/2.1/ref/settings/#allowed-hosts
.. _DEBUG: https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-DEBUG
.. _SECRET_KEY: https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-SECRET_KEY
.. _ENGINE: https://docs.djangoproject.com/en/2.1/ref/settings/#engine
.. _NAME: https://docs.djangoproject.com/en/2.1/ref/settings/#name
.. _USER: https://docs.djangoproject.com/en/2.1/ref/settings/#user
.. _PASSWORD: https://docs.djangoproject.com/en/2.1/ref/settings/#password
.. _HOST: https://docs.djangoproject.com/en/2.1/ref/settings/#host
.. _PORT: https://docs.djangoproject.com/en/2.1/ref/settings/#port
Configuration variables
-----------------------
ARA_BASE_DIR
~~~~~~~~~~~~
- **Environment variable**: ``ARA_BASE_DIR``
- **Configuration file variable**: ``BASE_DIR``
- **Type**: ``string``
- **Default**: ``~/.ara/server``
The directory where data will be stored by default.
Changing this location influences the default root directory for the
``ARA_STATIC_ROOT`` and ``ARA_DATABASE_NAME`` parameters.
This is also used to determine the location where the default configuration
file, ``settings.yaml``, will be generated by ara-server.
ARA_SETTINGS
~~~~~~~~~~~~
- **Environment variable**: ``ARA_SETTINGS``
- **Configuration file variable**: None, this variable defines the configuration file itself.
- **Type**: ``string``
- **Default**: ``None``
- **Provided by**: dynaconf_
Location of an ara-server configuration file to load settings from.
``ara-server`` generates a default configuration file at
``~/.ara/server/settings.yaml`` that you can use to get started.
Note that while the configuration file is in YAML by default, it is possible
to have configuration files written in ``ini``, ``json`` and ``toml`` as well.
Settings and configuration parsing in ara-server is provided by the dynaconf_
python module.
.. _dynaconf: https://github.com/rochacbruno/dynaconf
ARA_ENV
~~~~~~~
- **Environment variable**: ``ARA_ENV``
- **Configuration file variable**: None, this variable defines which section of a configuration file is loaded.
- **Type**: ``string``
- **Default**: ``development``
- **Provided by**: dynaconf_
If you are using ara-server in different environments and would like keep your
configuration in a single file, you can use this variable to select a specific
environment's settings.
For example::
# Default settings are used only when not provided in the environments
default:
READ_LOGIN_REQUIRED: false
WRITE_LOGIN_REQUIRED: false
LOG_LEVEL: INFO
DEBUG: false
# Increase verbosity and debugging for the default development environment
development:
LOG_LEVEL: DEBUG
DEBUG: true
SECRET_KEY: dev
# Enable write authentication when using the production environment
production:
WRITE_LOGIN_REQUIRED: true
SECRET_KEY: prod
With the example above, loading the development environment would yield the
following settings:
- READ_LOGIN_REQUIRED: ``false``
- WRITE_LOGIN_REQUIRED: ``false``
- LOG_LEVEL: ``DEBUG``
- DEBUG: ``true``
- SECRET_KEY: ``dev``
Another approach to environment-specific configuration is to use
``ARA_SETTINGS`` and keep your settings in different files such as ``dev.yaml``
or ``prod.yaml`` instead.
.. tip::
If it does not exist, ara-server will generate a default configuration
file at ``~/.ara/server/settings.yaml``.
This generated file sets up all the configuration keys in the **default**
environment.
This lets users override only the parameters they are interested in for
specific environments.
ARA_READ_LOGIN_REQUIRED
~~~~~~~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_READ_LOGIN_REQUIRED``
- **Configuration file variable**: ``READ_LOGIN_REQUIRED``
- **Type**: ``bool``
- **Default**: ``False``
- **Provided by**: `django-rest-framework permissions <https://www.django-rest-framework.org/api-guide/permissions>`_
Determines if authentication is required before being authorized to query all
API endpoints exposed by the server.
There is no concept of granularity: users either have access to query
everything or they don't.
Enabling this feature first requires setting up :ref:`users <user management>`.
ARA_WRITE_LOGIN_REQUIRED
~~~~~~~~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_WRITE_LOGIN_REQUIRED``
- **Configuration file variable**: ``WRITE_LOGIN_REQUIRED``
- **Type**: ``bool``
- **Default**: ``False``
- **Provided by**: `django-rest-framework permissions <https://www.django-rest-framework.org/api-guide/permissions>`_
Determines if authentication is required before being authorized to post data to
all API endpoints exposed by the server.
There is no concept of granularity: users either have access to query
everything or they don't.
Enabling this feature first requires setting up :ref:`users <user management>`.
ARA_LOG_LEVEL
~~~~~~~~~~~~~
- **Environment variable**: ``ARA_LOG_LEVEL``
- **Configuration file variable**: ``LOG_LEVEL``
- **Type**: ``string``
- **Default**: ``INFO``
Log level of the different components from ``ara-server``.
``ARA_LOG_LEVEL`` changes the log level of the default logging configuration
provided by ARA_LOGGING_.
ARA_LOGGING
~~~~~~~~~~~
- **Environment variable**: *Not recommended, use configuration file*
- **Configuration file variable**: ``LOGGING``
- **Type**: ``dictionary``
- **Default**::
LOGGING:
disable_existing_loggers: false
formatters:
normal:
format: '%(asctime)s %(levelname)s %(name)s: %(message)s'
handlers:
console:
class: logging.StreamHandler
formatter: normal
level: INFO
stream: ext://sys.stdout
loggers:
ara:
handlers:
- console
level: INFO
propagate: 0
root:
handlers:
- console
level: INFO
version: 1
The python logging configuration for ``ara-server``.
ARA_CORS_ORIGIN_WHITELIST
~~~~~~~~~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_CORS_ORIGIN_WHITELIST``
- **Configuration file variable**: ``CORS_ORIGIN_WHITELIST``
- **Provided by**: `django-cors-headers <https://github.com/ottoyiu/django-cors-headers>`_
- **Type**: ``list``
- **Default**: ``["127.0.0.1:8000", "localhost:3000"]``
- **Examples**:
- ``export ARA_CORS_ORIGIN_WHITELIST="['api.ara.example.org', 'web.ara.example.org']"``
- In a YAML configuration file::
dev:
CORS_ORIGIN_WHITELIST:
- 127.0.0.1:8000
- localhost:3000
production:
CORS_ORIGIN_WHITELIST:
- api.ara.example.org
- web.ara.example.org
Hosts in the whitelist for `Cross-Origin Resource Sharing <https://en.wikipedia.org/wiki/Cross-origin_resource_sharing>`_.
This setting is typically used in order to allow the API and a web client
(such as `ara-web <https://github.com/openstack/ara-web>`_) to talk to each other.
ARA_ALLOWED_HOSTS
~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_ALLOWED_HOSTS``
- **Configuration file variable**: ``ALLOWED_HOSTS``
- **Type**: ``list``
- **Provided by**: Django's ALLOWED_HOSTS_
- **Default**: ``["127.0.0.1", "localhost", "::1"]``
A list of strings representing the host/domain names that this Django site can
serve.
If you are planning on hosting an instance of ``ara-server`` somewhere, you'll
need to add your domain name to this list.
ARA_DEBUG
~~~~~~~~~
- **Environment variable**: ``ARA_DEBUG``
- **Configuration file variable**: ``DEBUG``
- **Provided by**: Django's DEBUG_
- **Type**: ``string``
- **Default**: ``false``
Whether or not Django's debug mode should be enabled.
The Django project recommends turning this off for production use.
ARA_SECRET_KEY
~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_SECRET_KEY``
- **Configuration file variable**: ``SECRET_KEY``
- **Provided by**: Django's SECRET_KEY_
- **Type**: ``string``
- **Default**: Randomized with ``django.utils.crypto.get_random_string()``
A secret key for a particular Django installation. This is used to provide
cryptographic signing, and should be set to a unique, unpredictable value.
If it is not set, a random token will be generated and persisted in the
default configuration file.
ARA_STATIC_ROOT
~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_STATIC_ROOT``
- **Configuration file variable**: ``STATIC_ROOT``
- **Provided by**: Django's STATIC_ROOT_
- **Type**: ``string``
- **Default**: ``~/.ara/server/www/static``
The absolute path to the directory where Django's collectstatic command will
collect static files for deployment.
The static files are required for the built-in API browser by
django-rest-framework.
ARA_DATABASE_ENGINE
~~~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_DATABASE_ENGINE``
- **Configuration file variable**: ``DATABASES["default"]["ENGINE"]``
- **Provided by**: Django's ENGINE_ database setting
- **Type**: ``string``
- **Default**: ``django.db.backends.sqlite3``
- **Examples**:
- ``django.db.backends.postgresql``
- ``django.db.backends.mysql``
The Django database driver to use.
When using anything other than sqlite3 default driver, make sure to set the
other database settings to allow ara-server to connect to the database.
ARA_DATABASE_NAME
~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_DATABASE_NAME``
- **Configuration file variable**: ``DATABASES["default"]["NAME"]``
- **Provided by**: Django's NAME_ database setting
- **Type**: ``string``
- **Default**: ``~/.ara/server/ansible.sqlite``
The name of the database.
When using sqlite, this is the absolute path to the sqlite database file.
When using drivers such as MySQL or PostgreSQL, it's the name of the database.
ARA_DATABASE_USER
~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_DATABASE_USER``
- **Configuration file variable**: ``DATABASES["default"]["USER"]``
- **Provided by**: Django's USER_ database setting
- **Type**: ``string``
- **Default**: ``None``
The username to connect to the database.
Required when using something other than sqlite.
ARA_DATABASE_PASSWORD
~~~~~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_DATABASE_PASSWORD``
- **Configuration file variable**: ``DATABASES["default"]["PASSWORD"]``
- **Provided by**: Django's PASSWORD_ database setting
- **Type**: ``string``
- **Default**: ``None``
The password to connect to the database.
Required when using something other than sqlite.
ARA_DATABASE_HOST
~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_DATABASE_HOST``
- **Configuration file variable**: ``DATABASES["default"]["HOST"]``
- **Provided by**: Django's HOST_ database setting
- **Type**: ``string``
- **Default**: ``None``
The host for the database server.
Required when using something other than sqlite.
ARA_DATABASE_PORT
~~~~~~~~~~~~~~~~~
- **Environment variable**: ``ARA_DATABASE_PORT``
- **Configuration file variable**: ``DATABASES["default"]["PORT"]``
- **Provided by**: Django's PORT_ database setting
- **Type**: ``string``
- **Default**: ``None``
The port to use when connecting to the database server.
It is not required to set the port if you're using default ports for MySQL or
PostgreSQL.

View File

@ -1,15 +0,0 @@
Welcome to the ARA server documentation!
========================================
.. image:: _static/ara.png
Table of Contents
=================
.. toctree::
:maxdepth: 2
Installing ara-server <installing>
Configuration settings and preferences <configuring>
Authentication and security <security>
Using API clients with ara-server <using_api_clients>
Architecture and workflows <arch>

View File

@ -1,18 +0,0 @@
.. _installing:
Installing ara-server
=====================
``ara-server`` requires a Linux distribution with python 3 in order to work.
It is recommended to use a python `virtual environment <https://docs.python.org/3/tutorial/venv.html>`_
in order to avoid conflicts with your Linux distribution python packages::
# Create a virtual environment
python3 -m venv ~/.ara/venv
# Install ara-server from source
~/.ara/venv/bin/pip install git+https://git.openstack.org/openstack/ara-server
# or install it from PyPi
~/.ara/venv/bin/pip install ara-server

View File

@ -1,112 +0,0 @@
.. security:
Authentication and security
===========================
ara-server ships with a default configuration that emphasizes simplicity to
let users get started quickly.
By default:
- A random SECRET_KEY will be generated once if none are supplied
- No users are created
- API authentication and permissions are not enabled
- ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST are configured for use on localhost
These default settings can be configured according to the requirements of your
deployments.
Setting a custom secret key
---------------------------
By default, ara-server randomly generates a token for the :ref:`ARA_SECRET_KEY`
setting if none have been supplied by the user.
This value is persisted in the server configuration file in order to prevent
the key from changing on every instanciation of the server.
The default location for the server configuration file is
``~/.ara/server/settings.yaml``.
You can provide a custom secret key by supplying the ``ARA_SECRET_KEY``
environment variable or by specifying the ``SECRET_KEY`` setting in your server
configuration file.
User management
---------------
ara-server leverages Django's `user management <https://docs.djangoproject.com/en/2.1/topics/auth/default/>`_
but doesn't create any user by default.
.. note::
Creating users does not enable authentication on the API.
In order to make authentication required for using the API, see `Enabling authentication for read or write access`_.
In order to create users, you'll need to create a superuser account before
running the API server::
$ ara-manage createsuperuser --username=joe --email=joe@example.com
Password:
Password (again):
Superuser created successfully.
.. tip::
If you ever need to reset the password of a superuser account, this can be
done with the "changepassword" command::
$ ara-manage changepassword joe
Changing password for user 'joe'
Password:
Password (again):
Password changed successfully for user 'joe'
Once the superuser has been created, make sure the API server is started and
then login to the Django web administrative interface using the credentials
you just set up.
By default, you can start the API server with ``ara-manage runserver`` and
access the admin interface at ``http://127.0.0.1:8000/admin/``.
Log in to the admin interface:
.. image:: _static/admin_panel_login.png
Access the authentication and authorization configuration:
.. image:: _static/admin_panel_auth.png
And from here, you can manage existing users or create new ones:
.. image:: _static/admin_panel_users.png
Enabling authentication for read or write access
------------------------------------------------
Once you have created your users, you can enable authentication against the API
for read (ex: GET) and write (ex: DELETE, POST, PATCH) requests.
This is done with the two following configuration options:
- :ref:`ARA_READ_LOGIN_REQUIRED` for read access
- :ref:`ARA_WRITE_LOGIN_REQUIRED` for write access
These settings are global and are effective for all API endpoints.
Managing hosts allowed to serve the API
---------------------------------------
By default, :ref:`ARA_ALLOWED_HOSTS` authorizes ``localhost``, ``::1`` and
``127.0.0.1`` to serve requests for the API server.
In order to host an instance of ara-server on another domain, the domain must
be part of this list or the application server will deny any requests sent to
it.
Managing CORS (cross-origin resource sharing)
---------------------------------------------
The :ref:`ARA_CORS_ORIGIN_WHITELIST` default is designed to allow a local development
instance of an `ara-web <https://github.com/openstack/ara-web>`_ dashboard to
communicate with a local development instance of ara-server.
The whitelist must contain the domain names where you plan on hosting instances
of ara-web.

View File

@ -1,87 +0,0 @@
Using API clients with ara-server
=================================
Once you've :ref:`installed <installing>` ara-server, you need to know how
you're going to use it.
Typically, `ara-server <https://github.com/openstack/ara-server>`_ is consumed
by `ara-clients <https://github.com/openstack/ara-clients>`_ which currently
provides two python clients for the API.
ARA Offline REST API client
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The default client, ``AraOfflineClient``, is meant to be used to query the API
without requiring users to start or host an instance of ``ara-server``.
To use the offline client, first install ``ara-server`` and ``ara-clients``,
for example::
# Install ara-server and ara-clients
python3 -m venv ~/.ara/venv
~/.ara/venv/bin/pip install ara-server ara-clients
Then you can use it like this::
#!/usr/bin/env python3
# Import the client
from ara.clients.offline import AraOfflineClient
# Instanciate the offline client
client = AraOfflineClient()
ARA HTTP REST API client
~~~~~~~~~~~~~~~~~~~~~~~~
``AraHttpClient`` works with the same interface, methods and behavior as
``AraOfflineClient``.
The HTTP client does not require ``ara-server`` to be installed in order to be
used but expects a functional API endpoint at a specified location.
You can set your client to communicate with a remote ``ara-server`` API by
specifying an endpoint parameter::
#!/usr/bin/env python3
# Import the client
from ara.clients.http import AraHttpClient
# Instanciate the HTTP client with an endpoint where ara-server is listening
client = AraHttpClient(endpoint="https://api.demo.recordsansible.org")
Example API usage
~~~~~~~~~~~~~~~~~
.. note::
API documentation is a work in progress.
Once you've instanciated your client, you're ready to query the API.
Here's a code example to help you get started::
# Get a list of failed playbooks
# /api/v1/playbooks?status=failed
playbooks = client.get("/api/v1/playbooks", status="failed")
# If there are any failed playbooks, retrieve their failed results
# and provide some insight.
for playbook in playbooks["results"]:
# Retrieve results for this playbook
# /api/v1/results?playbook=<:id>&status=failed
results = client.get("/api/v1/results", playbook=playbook["id"], status="failed")
# Iterate over failed results to get meaningful data back
for result in results["results"]:
# Get the task that generated this result
# /api/v1/tasks/<:id>
task = client.get(f"/api/v1/tasks/{result['task']}")
# Get the file from which this task ran from
# /api/v1/files/<:id>
file = client.get(f"/api/v1/files/{task['file']}")
# Get the host on which this result happened
# /api/v1/hosts/<:id>
host = client.get(f"/api/v1/hosts/{result['host']}")
# Print something useful
print(f"Failure on {host['name']}: '{task['name']}' ({file['path']}:{task['lineno']})")

View File

@ -1,6 +0,0 @@
#!/usr/bin/env python
from ara.server.__main__ import main
if __name__ == "__main__":
main()

View File

@ -1,3 +0,0 @@
[tool.black]
line-length = 120
exclude = 'migrations'

View File

@ -1,7 +0,0 @@
pbr!=2.1.0,>=2.0.0 # Apache-2.0
Django>=2.1.5
djangorestframework>=3.9.1
django-cors-headers
django-filter
dynaconf[yaml]

View File

@ -1,84 +0,0 @@
[metadata]
name = ara-server
summary = ARA Records Ansible API and Server components
description-file =
README.rst
author = OpenStack Community
author-email = openstack-discuss@lists.openstack.org
home-page = https://github.com/openstack/ara-server
classifier =
Environment :: OpenStack
Intended Audience :: Information Technology
Intended Audience :: System Administrators
Intended Audience :: Developers
Topic :: Utilities
License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Operating System :: POSIX :: Linux
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.5
Development Status :: 4 - Beta
[global]
setup-hooks =
pbr.hooks.setup_hook
[files]
packages =
ara
[entry_points]
console_scripts =
ara-manage = ara.server.__main__:main
[build_sphinx]
source-dir = doc/source
build-dir = doc/build
all_files = 1
[upload_sphinx]
upload-dir = docs/html
[coverage:report]
ignore_errors = True
include =
ara/*
omit =
/usr*
setup.py
*egg*
.venv/*
[coverage:html]
directory = reports
[wheel]
universal = 1
[pbr]
skip_authors = True
skip_changelog = True
[flake8]
# E123, E125 skipped as they are invalid PEP-8.
# E741, short ambiguous variable names
# H106 Dont put vim configuration in source files
# H203 Use assertIs(Not)None to check for None
max-line-length = 120
ignore = E123,E125,E741
enable-extensions=H106,H203
show-source = True
exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build,ara/api/migrations
[isort]
known_first_party = ara
default_section = THIRDPARTY
skip = build,.git,.tox,.cache,.venv,ara/api/migrations
not_skip = __init__.py
multi_line_output=3
include_trailing_comma=True
force_grid_wrap=0
combine_as_imports=True
line_length=120

View File

@ -1,22 +0,0 @@
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA: Ansible Run Analysis.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
import setuptools
setuptools.setup(
setup_requires=['pbr'],
pbr=True)

View File

@ -1,8 +0,0 @@
factory-boy
bandit>=1.1.0 # Apache-2.0
coverage
flake8
sphinx>=1.4
sphinx-rtd-theme
black==18.9b0 ; python_version >= '3.6' # Exact version for prerelease
isort

View File

@ -1,65 +0,0 @@
#!/bin/bash
# Copyright (c) 2018 Red Hat, Inc.
#
# This file is part of ARA: Ansible Run Analysis.
#
# ARA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ARA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ARA. If not, see <http://www.gnu.org/licenses/>.
# The parent directory of this script
tests=$(dirname $0)
export PROJECT_ROOT=$(cd `dirname $tests` && pwd -P)
export PROJECT_LIB="${PROJECT_ROOT}/ara"
ret=0
function banner() {
echo
printf '#%.0s' {1..50}
echo
echo "# ${1}"
printf '#%.0s' {1..50}
echo
}
# Let this script work even though it might not be run by tox
if [ -z "${VIRTUAL_ENV}" ]; then
pushd "${PROJECT_ROOT}"
tox -e linters --notest
source .tox/linters/bin/activate
popd
fi
banner black
time black --diff --check "${PROJECT_LIB}"
ret+=$?
banner isort
time isort --recursive --check-only --diff "${PROJECT_LIB}"
ret+=$?
banner flake8
time flake8 "${PROJECT_LIB}"
ret+=$?
# B303 - Use of insecure MD2, MD4, or MD5 hash function.
# We're using sha1 to generate a hash of file contents.
banner bandit
time bandit -r "${PROJECT_LIB}" --skip B303
ret+=$?
if [ $ret -gt 0 ]
then
echo
echo "At least one linter detected errors!"
exit 1
fi

45
tox.ini
View File

@ -1,45 +0,0 @@
[tox]
minversion = 2.0
envlist = py3,pep8
skipdist = True
[testenv]
basepython = python3
sitepackages = False
usedevelop = True
install_command = pip install -U {opts} {packages} -c{env:CONSTRAINTS_FILE:/dev/null}
setenv = VIRTUAL_ENV={envdir}
deps = -r{toxinidir}/test-requirements.txt
[testenv:venv]
commands = {posargs}
[testenv:docs]
commands = sphinx-build -W -b html doc/source doc/build/html
[testenv:linters]
commands = {toxinidir}/tests/linters.sh
[testenv:py3]
commands = ara-manage test ara
setenv =
ARA_DEBUG=true
ARA_LOG_LEVEL=DEBUG
ARA_BASE_DIR={toxinidir}/.tox/py3/tmp/ara
[testenv:runserver]
commands =
ara-manage migrate
ara-manage collectstatic --clear --no-input
ara-manage runserver
setenv =
ARA_DEBUG=true
ARA_LOG_LEVEL=DEBUG
ARA_BASE_DIR={toxinidir}/.tox/runserver/tmp/ara
[testenv:cover]
commands =
coverage erase
coverage run {toxinidir}/ara/server/__main__.py test ara/server
coverage run -a {toxinidir}/ara/server/__main__.py test ara/api
coverage html

4
zuul.yaml Normal file
View File

@ -0,0 +1,4 @@
- project:
templates:
- noop-jobs