diff --git a/.flake8 b/.flake8 index 2534a45ee555bb5ebefd37210d19399634c7a4ee..0de55fba7ec878cb182f3a6efdb732db1e254cc0 100644 --- a/.flake8 +++ b/.flake8 @@ -1,3 +1,8 @@ +# SPDX-FileCopyrightText: Copyright © 2023 Idiap Research Institute <contact@idiap.ch> +# SPDX-FileContributor: Andre Anjos <andre.anjos@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + [flake8] max-line-length = 80 ignore = E501,W503,E302,E402,E203 diff --git a/.gitignore b/.gitignore index b8915d5c573033be90ab07e187de0be8d815fd07..cae6362cd0635be5da701825f5887b82e1f99d10 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,24 @@ -*.py? +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + *~ -*.egg-info *.swp -build -dist -.installed.cfg -.mr.developer.cfg -develop-eggs -eggs -bin -sphinx -.project -.pydevproject -.settings -submitted.sql3 -logs -src -record.txt +*.pyc +*.egg-info +.nfs* +.coverage +*.DS_Store +.envrc +coverage.xml +test_results.xml +junit-coverage.xml +.tox/ +html/ +build/ +doc/api/ +dist/ +.mypy_cache/ +.pytest_cache/ +cache/ +venv/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 845b719f2378d396a8b75296a68d1e32c840e7c7..b2f33577f12a27a272d6be26a125c5b2c72b34fe 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1 +1,8 @@ -include: 'https://gitlab.idiap.ch/bob/bob.devtools/raw/master/bob/devtools/data/gitlab-ci/single-package.yaml' +# SPDX-FileCopyrightText: Copyright © 2023 Idiap Research Institute <contact@idiap.ch> +# SPDX-FileContributor: Andre Anjos <andre.anjos@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +include: + - project: bob/dev-profile + file: /gitlab/python.yml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 833ff2341e4272ee8687a877a1a39ee360be8fb9..4441d5d062b6a618b142a41acf45e1625a5c74c5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,32 +1,56 @@ +# SPDX-FileCopyrightText: Copyright © 2023 Idiap Research Institute <contact@idiap.ch> +# SPDX-FileContributor: Andre Anjos <andre.anjos@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - - repo: https://github.com/timothycrosley/isort - rev: 5.10.1 - hooks: - - id: isort - args: [--settings-path, "pyproject.toml"] - repo: https://github.com/psf/black - rev: 22.3.0 + rev: 22.10.0 hooks: - id: black - - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.2 + - repo: https://github.com/pycqa/docformatter + rev: v1.5.0 + hooks: + - id: docformatter + - repo: https://github.com/pycqa/isort + rev: 5.10.1 + hooks: + - id: isort + - repo: https://github.com/pycqa/flake8 + rev: 5.0.4 hooks: - id: flake8 - exclude: | - (?x)^( - bob/devtools/templates/setup.py| - deps/bob-devel/run_test.py - )$ + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v0.991 + hooks: + - id: mypy + args: [ + --install-types, + --non-interactive, + --no-strict-optional, + --ignore-missing-imports, + ] + - repo: https://github.com/asottile/pyupgrade + rev: v3.2.2 + hooks: + - id: pyupgrade + args: [--py38-plus] - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.1.0 + rev: v4.3.0 hooks: - id: check-ast + - id: check-added-large-files + - id: check-toml + - id: check-yaml + exclude: conda/meta.yaml + - id: debug-statements - id: check-case-conflict - id: trailing-whitespace - id: end-of-file-fixer - id: debug-statements - - id: check-added-large-files - - id: check-yaml - exclude: .*/meta.yaml + - repo: https://github.com/fsfe/reuse-tool + rev: v1.0.0 + hooks: + - id: reuse diff --git a/.reuse/dep5 b/.reuse/dep5 new file mode 100644 index 0000000000000000000000000000000000000000..ecc7828aa4f4de8ebd9b89682883f9bdca18fec3 --- /dev/null +++ b/.reuse/dep5 @@ -0,0 +1,8 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: auto-intersphinx +Upstream-Contact: André Anjos <andre.anjos@idiap.ch> +Source: https://gitlab.idiap.ch/bob/gridtk/ + +Files: doc/catalog.json +Copyright: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +License: GPL-3.0-or-later diff --git a/COPYING b/COPYING deleted file mode 100644 index 94a9ed024d3859793618152ea559a168bbcbb5e2..0000000000000000000000000000000000000000 --- a/COPYING +++ /dev/null @@ -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: - - <program> Copyright (C) <year> <name of author> - 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>. diff --git a/LICENSES/GPL-3.0-or-later.txt b/LICENSES/GPL-3.0-or-later.txt new file mode 100644 index 0000000000000000000000000000000000000000..d41c0bd98feb776ef7d81efbc1b5447e0284a187 --- /dev/null +++ b/LICENSES/GPL-3.0-or-later.txt @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 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: + + <program> Copyright (C) <year> <name of author> + 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>. diff --git a/MANIFEST.in b/MANIFEST.in index 762ca7eef677fe1277af5ceb252435def36d25f4..0d6f1c498aa55da65d977ee86ac824e6cdb98e39 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,6 @@ -include README.rst buildout.cfg develop.cfg COPYING requirements.txt version.txt -recursive-include doc *.rst -recursive-include gridtk *.sh +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +recursive-include doc *.rst *.json *.txt *.py +recursive-include tests *.py *.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9d06b5bbd7f58e74fd56804939d25b9a09d630a9 --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +<!-- +SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> + +SPDX-License-Identifier: GPL-3.0-or-later +--> + +[](https://www.idiap.ch/software/bob/docs/bob/gridtk/stable/sphinx/index.html) +[](https://www.idiap.ch/software/bob/docs/bob/gridtk/main/sphinx/index.html) +[](https://gitlab.idiap.ch/bob/gridtk/commits/main) +[](https://www.idiap.ch/software/bob/docs/bob/gridtk/main/coverage/index.html) +[](https://gitlab.idiap.ch/bob/gridtk) + +# Grid-enabled job submitter and execution monitor for Idiap + +This package provides a set of python wrappers around SGE utilities like +`qsub`, `qstat` and `qdel`, and simplify job submission and management. It +interacts with these tools to submit and manage grid jobs. It is hardcoded to +work with the SGE grid at Idiap. + +For installation and usage instructions, check-out our documentation. diff --git a/README.rst b/README.rst deleted file mode 100644 index 6c553898d3705273c80779af49ef1ab5c9a46a9a..0000000000000000000000000000000000000000 --- a/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -.. vim: set fileencoding=utf-8 : -.. Tue 16 Aug 16:07:37 CEST 2016 - -.. image:: https://img.shields.io/badge/docs-latest-orange.svg - :target: https://www.idiap.ch/software/bob/docs/bob/gridtk/master/index.html -.. image:: https://gitlab.idiap.ch/bob/gridtk/badges/master/pipeline.svg - :target: https://gitlab.idiap.ch/bob/gridtk/commits/master -.. image:: https://gitlab.idiap.ch/bob/gridtk/badges/master/coverage.svg - :target: https://gitlab.idiap.ch/bob/gridtk/commits/master -.. image:: https://img.shields.io/badge/gitlab-project-0000c0.svg - :target: https://gitlab.idiap.ch/bob/gridtk - - -====================== - Parallel Job Manager -====================== - -This package is part of the signal-processing and machine learning toolbox -Bob_. It provides a set of python wrappers around SGE utilities like ``qsub``, -``qstat`` and ``qdel``. It interacts with these tools to submit and manage grid -jobs making up a complete workflow ecosystem. Currently, it is set up to work -with the SGE grid at Idiap, but it is also possible to modify it to be used in -other SGE grids. - -Since version 1.0.x there is also a local submission system introduced. Instead -of sending jobs to the SGE grid, it executes them in parallel processes on the -local machine, using a simple scheduling system. - - -Installation ------------- - -Complete Bob's `installation`_ instructions. Then, to install this package, -run:: - - $ conda install gridtk - - -Contact -------- - -For questions or reporting issues to this software package, contact our -development `mailing list`_. - - -.. Place your references here: -.. _bob: https://www.idiap.ch/software/bob -.. _installation: https://www.idiap.ch/software/bob/install -.. _mailing list: https://www.idiap.ch/software/bob/discuss diff --git a/buildout.cfg b/buildout.cfg deleted file mode 100644 index e3c77954fe75dd9e26b3e25e5652380ed5b3d3c6..0000000000000000000000000000000000000000 --- a/buildout.cfg +++ /dev/null @@ -1,14 +0,0 @@ -; vim: set fileencoding=utf-8 : -; Tue 16 Aug 16:07:37 CEST 2016 - -[buildout] -parts = scripts -develop = . -eggs = gridtk -extensions = bob.buildout -newest = false -verbose = true - -[scripts] -recipe = bob.buildout:scripts -dependent-scripts = true diff --git a/conda/meta.yaml b/conda/meta.yaml index 23c1f2167b72ff1504c6b5c5649662076a09f77d..6c102468fe6a0dddef3e9d118f54793b17c29cf8 100644 --- a/conda/meta.yaml +++ b/conda/meta.yaml @@ -1,65 +1,46 @@ -{% set name = 'gridtk' %} -{% set project_dir = environ.get('RECIPE_DIR') + '/..' %} +# SPDX-FileCopyrightText: 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +{% set data = load_file_data(RECIPE_DIR + '/../pyproject.toml') %} package: - name: {{ name }} - version: {{ environ.get('BOB_PACKAGE_VERSION', '0.0.1') }} + name: {{ data['project']['name'] }} + version: {{ data['project']['version'] }} + +source: + path: .. build: - entry_points: - - jman = gridtk.script.jman:main - - jgen = gridtk.script.jgen:main - - grid = gridtk.script.grid:main - - qstat.py = gridtk.script.grid:main - - qdel.py = gridtk.script.grid:main - - qsub.py = gridtk.script.grid:main - - man.py = gridtk.script.grid:main + noarch: python number: {{ environ.get('BOB_BUILD_NUMBER', 0) }} run_exports: - - {{ pin_subpackage(name) }} + - {{ pin_subpackage(data['project']['name']) }} script: - - cd {{ project_dir }} - {% if environ.get('BUILD_EGG') %} - - "{{ PYTHON }} setup.py sdist --formats=zip" - {% endif %} - - "{{ PYTHON }} -m pip install . -vv" + - "{{ PYTHON }} -m pip install {{ SRC_DIR }} -vv" requirements: host: - - python {{ python }} - - setuptools {{ setuptools }} + - python >=3.9 - pip {{ pip }} - - bob.extension - - jinja2 {{ jinja2 }} - - pyyaml {{ pyyaml }} - sqlalchemy {{ sqlalchemy }} run: - - python - - setuptools - - {{ pin_compatible('jinja2') }} - - {{ pin_compatible('pyyaml') }} + - python >=3.9 - {{ pin_compatible('sqlalchemy') }} + - exposed test: + source_files: + - tests imports: - - {{ name }} + - {{ data['project']['name'].replace('-','_') }} commands: - - jman --help - - jgen --help - - - nosetests --with-coverage --cover-package={{ name }} -sv {{ name }} - - sphinx-build -aEW {{ project_dir }}/doc {{ project_dir }}/sphinx - - sphinx-build -aEb doctest {{ project_dir }}/doc sphinx - - conda inspect linkages -p $PREFIX {{ name }} # [not win] - - conda inspect objects -p $PREFIX {{ name }} # [osx] + - pytest -sv tests requires: - - nose {{ nose }} - - coverage {{ coverage }} - - sphinx {{ sphinx }} - - sphinx_rtd_theme {{ sphinx_rtd_theme }} + - pytest {{ pytest }} about: - home: https://www.idiap.ch/software/bob/ - license: GNU General Public License v3 (GPLv3) - summary: Parallel Job Manager + home: {{ data['project']['urls']['homepage'] }} + summary: {{ data['project']['description'] }} + license: {{ data['project']['license']['text'] }} license_family: GPL diff --git a/doc/api.rst b/doc/api.rst new file mode 100644 index 0000000000000000000000000000000000000000..14eb4b20b4d331b0c9d94c6f40aa122539a6fe14 --- /dev/null +++ b/doc/api.rst @@ -0,0 +1,24 @@ +.. SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +.. +.. SPDX-License-Identifier: GPL-3.0-or-later + +.. _gridtk.api: + +============ + Python API +============ + +This section includes information for using the Python API of +``gridtk``. + +.. autosummary:: + :toctree: api + + gridtk.manager + gridtk.sge + gridtk.tools + gridtk.models + gridtk.setshell + + +.. include:: links.rst diff --git a/doc/catalog.json b/doc/catalog.json new file mode 100644 index 0000000000000000000000000000000000000000..3561c742e9c93e50e3d2c9b35354c3c0f315c87a --- /dev/null +++ b/doc/catalog.json @@ -0,0 +1,9 @@ +{ + "exposed": { + "versions": { + "stable": "https://www.idiap.ch/software/bob/docs/bob/exposed/stable/sphinx/", + "latest": "https://www.idiap.ch/software/bob/docs/bob/exposed/main/sphinx/" + }, + "sources": {} + } +} diff --git a/doc/conf.py b/doc/conf.py index 1db81a466e0524823f0301c71efd495bf53258eb..939c9ddc1ecb4cf043fe889f7462b609ec19a7b0 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -1,9 +1,11 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later import os +import time -import pkg_resources +from importlib.metadata import distribution # -- General configuration ----------------------------------------------------- @@ -14,16 +16,16 @@ needs_sphinx = "1.3" # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.todo", - "sphinx.ext.coverage", - "sphinx.ext.ifconfig", "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.doctest", - "sphinx.ext.graphviz", - "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.viewcode", - "sphinx.ext.mathjax", + "sphinx.ext.intersphinx", + "auto_intersphinx", + "sphinx_autodoc_typehints", + "sphinx_copybutton", + "sphinx_inline_tabs", ] # Be picky about warnings @@ -39,10 +41,6 @@ if os.path.exists("nitpick-exceptions.txt"): continue dtype, target = line.split(None, 1) target = target.strip() - try: # python 2.x - target = unicode(target) - except NameError: - pass nitpick_ignore.append((dtype, target)) # Always includes todos @@ -55,7 +53,7 @@ autosummary_generate = True numfig = True # If we are on OSX, the 'dvipng' path maybe different -dvipng_osx = "/opt/local/libexec/texlive/binaries/dvipng" +dvipng_osx = "/Library/TeX/texbin/dvipng" if os.path.exists(dvipng_osx): pngmath_dvipng = dvipng_osx @@ -65,165 +63,49 @@ templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = "index" +# The main toctree document. +main_doc = "index" # General information about the project. project = "gridtk" -import time +package = distribution(project) copyright = "%s, Idiap Research Institute" % time.strftime("%Y") -# Grab the setup entry -distribution = pkg_resources.require(project)[0] - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# # The short X.Y version. -version = distribution.version +version = package.version # The full version, including alpha/beta/rc tags. -release = distribution.version - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' +release = version # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["links.rst"] -# The reST default role (used for this markup: `text`) to use for all documents. -# default_role = None - -# 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 - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" +pygments_dark_style = "monokai" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # Some variables which are useful for generated material project_variable = project.replace(".", "_") -short_description = "Parallel Job Manager" +short_description = package.metadata["Summary"] owner = ["Idiap Research Institute"] - # -- Options for HTML output --------------------------------------------------- -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -import sphinx_rtd_theme - -html_theme = "sphinx_rtd_theme" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] - -# The name for this set of Sphinx documents. If None, it defaults to -# "<project> v<release> documentation". -# html_title = None +html_theme = "furo" -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = project_variable - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -html_logo = "img/logo.png" - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -html_favicon = "img/favicon.ico" - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -# html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a <link> tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = project_variable + "_doc" +html_theme_options = { + "source_edit_link": f"https://gitlab.idiap.ch/bob/{project}/-/edit/main/doc/{{filename}}", +} +html_title = f"{project} {release}" # -- Post configuration -------------------------------------------------------- -# Included after all input documents -rst_epilog = """ -.. |project| replace:: Bob -.. |version| replace:: %s -.. |current-year| date:: %%Y -""" % ( - version, -) - # Default processing flags for sphinx -autoclass_content = "class" autodoc_member_order = "bysource" autodoc_default_options = { "members": True, @@ -231,13 +113,5 @@ autodoc_default_options = { "show-inheritance": True, } -# For inter-documentation mapping: -from bob.extension.utils import link_documentation, load_requirements - -sphinx_requirements = "extra-intersphinx.txt" -if os.path.exists(sphinx_requirements): - intersphinx_mapping = link_documentation( - additional_packages=load_requirements(sphinx_requirements) - ) -else: - intersphinx_mapping = link_documentation() +auto_intersphinx_packages = [("python", "3"), ("exposed", "latest")] +auto_intersphinx_catalog = "catalog.json" diff --git a/doc/generate.rst b/doc/generate.rst deleted file mode 100644 index 6cd4facc664e9a093b8443b463dae13a512dbb9a..0000000000000000000000000000000000000000 --- a/doc/generate.rst +++ /dev/null @@ -1,204 +0,0 @@ -.. vim: set fileencoding=utf-8 : - - -.. _gridtk.generate: - -===================================== - Script Generation for Grid Searches -===================================== - -The thing with scientific discovery is that, sometimes, you need to do a lot -of experiments before a reasonable conclusion. These experiments require minor -variations in their configuration and submission, possibly to an SGE-enabled -facility for processing. - -This guide explains how to use the script ``jgen``, which helps you in -generating multiple experiment configurations for your grid searches. The -system supposes that a single experiment is defined in a single file while -multiple experiments can be run by somehow executing sequences of these -individual configuration files. - -The script ``jgen`` takes, in its simplistic form, 3 parameters that explain: - -* The "combinations" of variables that one needs to scan for a search in a - YAML_ file -* A Jinja2_ template file that explains the setup of each experiment -* An output template that explains how to mix the parameters in your YAML_ file - with the template and generate a bunch of experiment configurations to run - -Let's decrypt each of these inputs. - - -YAML Input ----------- - -The YAML_ input file describes all possible combinations of parameters you want -to scan. All root keys that represent lists will be combined in all possible -ways to produce, each combination, a "configuration set". - -A configuration set corresponds to settings for **all** variables in the input -template that needs replacing. For example, if your template mentions the -variables ``name`` and ``version``, then each configuration set should yield -values for both ``name`` and ``version``. - -For example: - -.. code-block:: yaml - - name: [john, lisa] - version: [v1, v2] - - -This should yield to the following configuration sets: - -.. code-block:: python - - [ - {'name': 'john', 'version': 'v1'}, - {'name': 'john', 'version': 'v2'}, - {'name': 'lisa', 'version': 'v1'}, - {'name': 'lisa', 'version': 'v2'}, - ] - - -Each key in the input file should correspond to either an object or a YAML -list. If the object is a list, then we'll iterate over it for every possible -combination of elements in the lists. If the element in question is not a list, -then it is considered unique and repeated for each generated configuration set. -Example - -.. code-block:: yaml - - name: [john, lisa] - version: [v1, v2] - text: > - hello, - world! - -Should yield to the following configuration sets: - -.. code-block:: python - - [ - {'name': 'john', 'version': 'v1', 'text': 'hello, world!'}, - {'name': 'john', 'version': 'v2', 'text': 'hello, world!'}, - {'name': 'lisa', 'version': 'v1', 'text': 'hello, world!'}, - {'name': 'lisa', 'version': 'v2', 'text': 'hello, world!'}, - ] - -Keys starting with one `_` (underscore) are treated as "unique" objects as -well. Example: - -.. code-block:: yaml - - name: [john, lisa] - version: [v1, v2] - _unique: [i1, i2] - -Should yield to the following configuration sets: - -.. code-block:: python - - [ - {'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']}, - {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']}, - {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']}, - {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']}, - ] - - -Jinja2 Template ---------------- - -This corresponds to a file that will have variables replaced for each of the -configuration sets generated by your YAML_ file. For example, if your template -is a python file that uses the variables this way: - -.. code-block:: text - - #/usr/bin/env python - - print('My name is {{ name }}') - print('This is {{ version }}') - - -Then, ``jgen`` will generate 4 output files each with combinations of ``name`` -and ``version`` as explained above. - - -Output filename template ------------------------- - -This is the same as the Jinja2_ template, in the sense it has the same build -rules, but it is just a string, describing the path in which the extrapolated -configurations, when combined with the template, will be saved. It may be -something like this, considering our example above: - -.. code-block:: text - - output-dir/{{ name }}-{{ version }}.py - - -With all those inputs, the ``jgen`` command will look like this: - -.. code-block:: sh - - $ jgen variables.yaml template.py 'output-dir/{{ name }}-{{ version }}.py' - - -Generating Aggregations ------------------------ - -When you generate as many files you need to run, it is sometimes practical to -also generate an "aggregation" script, that makes running all configurations -easy. For example, one could think of a bash script that runs all of the above -generated python scripts. We call those "aggregations". When aggregating, you -iterate over a specific variable called ``cfgset``, which contains the -dictionaries for each configuration set extrapolation. For example, an -aggregation would look like this: - -.. code-block:: sh - - #/usr/bin/env bash - - {% for k in cfgset %} - python output-dir/{{ k.name }}-{{ k.version }}.py - {% endfor %} - - -Which would then generate: - -.. code-block:: sh - - #/usr/bin/env bash - - python output-dir/john-v1.py - python output-dir/john-v2.py - python output-dir/lisa-v1.py - python output-dir/lisa-v2.py - - -With this generated bash script, you could run all configuration sets from a -single command line. - -The final command line for ``jgen``, including the generation of specific -configuration files and the aggregation would look like the following: - -.. code-block:: sh - - $ jgen variables.yaml template.py 'output-dir/{{ name }}-{{ version }}.py' run.sh 'output-dir/run.sh' - - -Automatic injection of variables --------------------------------- - -Sometimes you want to use variables that are user specific in your jinja templates; For -example, a temp directory that can be different for other users. To allow this, jgen -automatically injects ``bob.extension.rc`` (see :ref:`bob.extension.rc`) into your -variables. Then, you can access ``bob.extension.rc`` using something like: -``rc.variable_name`` to access variables from it in your jinja templates. - - -.. Place your references here: -.. _yaml: https://en.wikipedia.org/wiki/YAML -.. _jinja2: http://jinja.pocoo.org/docs/ diff --git a/doc/img/favicon.ico b/doc/img/favicon.ico deleted file mode 100644 index 4cc3264302627d40868261add69eb755856611b6..0000000000000000000000000000000000000000 Binary files a/doc/img/favicon.ico and /dev/null differ diff --git a/doc/img/logo.png b/doc/img/logo.png deleted file mode 100644 index b60858a7068bf45c1ed8e3da12fe244ccdcfe85d..0000000000000000000000000000000000000000 Binary files a/doc/img/logo.png and /dev/null differ diff --git a/doc/index.rst b/doc/index.rst index 1a32645f442aa57131bbc2324f37c8d3b4e2397d..440b929c61863124dd168663b16de2fc70c75484 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -1,34 +1,36 @@ -.. vim: set fileencoding=utf-8 : +.. SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +.. +.. SPDX-License-Identifier: GPL-3.0-or-later .. _gridtk: -====================== - Parallel Job Manager -====================== +============================================================ + Grid-enabled job submitter and execution monitor for Idiap +============================================================ -The GridTK serves as a tool to submit jobs and keep track of their dependencies -and their current statuses. These jobs can either be submitted to an SGE grid, -or to be run in parallel on the local machine. +``gridtk`` is a tool to submit jobs to SGE, keep track of their dependencies, +and current statuses. There are two main ways to interact with this package: +via a command-line interface or the Python API. -There are two main ways to interact with the GridTK. The easiest way is surely -to use the command line interface, for details please read the -:ref:`command_line` section. It is also possible to use the GridTK in a -program, the developer interface is described in the :ref:`developer` section. - -Contents: +Documentation +------------- .. toctree:: :maxdepth: 2 - manual - program - generate + install + usage-cli + usage-api + api Indices and tables -================== +------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` + + +.. include:: links.rst diff --git a/doc/install.rst b/doc/install.rst new file mode 100644 index 0000000000000000000000000000000000000000..5e65307c83692332bb614308c4b09f2d98a897dc --- /dev/null +++ b/doc/install.rst @@ -0,0 +1,75 @@ +.. SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +.. +.. SPDX-License-Identifier: GPL-3.0-or-later + +.. _gridtk.install: + +============== + Installation +============== + +We support two installation modes, through pip_, or mamba_ (conda). + + +.. tab:: pip + + Stable, from PyPI: + + .. code:: sh + + pip install gridtk + + Latest beta, from GitLab package registry: + + .. code:: sh + + pip install --pre --index-url https://gitlab.idiap.ch/api/v4/groups/bob/-/packages/pypi/simple --extra-index-url https://pypi.org/simple gridtk + + .. tip:: + + To avoid long command-lines you may configure pip to define the indexes and + package search priorities as you like. + + +.. tab:: mamba/conda + + Stable: + + .. code:: sh + + mamba install -c https://www.idiap.ch/software/bob/conda -c conda-forge gridtk + + Latest beta: + + .. code:: sh + + mamba install -c https://www.idiap.ch/software/bob/conda/label/beta -c conda-forge gridtk + + +Setup +----- + +A configuration file may be useful to setup global options that should be often +reused. The location of the configuration file depends on the value of the +environment variable ``$XDG_CONFIG_HOME``, but defaults to +``~/.config/gridtk.toml``. You may edit this file using your preferred editor. + +Here is an example configuration file that may be useful to many (replace +``<projectname>`` by the name of the project to charge): + +.. code:: toml + + # selects project to submit jobs + sge-extra-args-prepend = "-P <projectname>" + + +.. tip:: + + To get a list of valid project names, execute: + + .. code:: sh + + qconf -sprjl + + +.. include:: links.rst diff --git a/doc/links.rst b/doc/links.rst new file mode 100644 index 0000000000000000000000000000000000000000..125f594d6d0af638243b2b4b1cabee629dab15f6 --- /dev/null +++ b/doc/links.rst @@ -0,0 +1,13 @@ +.. SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +.. +.. SPDX-License-Identifier: GPL-3.0-or-later + +.. place re-used URLs here, then include this file +.. on your other RST sources. + +.. _sqlite: https://www.sqlite.org/ +.. _conda: https://conda.io +.. _idiap: http://www.idiap.ch +.. _python: http://www.python.org +.. _pip: https://pip.pypa.io/en/stable/ +.. _mamba: https://mamba.readthedocs.io/en/latest/index.html diff --git a/doc/nitpick-exceptions.txt b/doc/nitpick-exceptions.txt index 22ff9077c5c929ec65d02bea755413c0203c1129..111ab6472328f90e9141f114a76f189967716419 100644 --- a/doc/nitpick-exceptions.txt +++ b/doc/nitpick-exceptions.txt @@ -1,3 +1,5 @@ -# sqlalchemy -py:class sqlalchemy.ext.declarative.api.Base +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + py:class sqlalchemy.orm.decl_api.Base diff --git a/doc/program.rst b/doc/program.rst deleted file mode 100644 index 0d7d3369085976cfd47fbab51c92a813cf14bf85..0000000000000000000000000000000000000000 --- a/doc/program.rst +++ /dev/null @@ -1,61 +0,0 @@ -.. vim: set fileencoding=utf-8 : -.. Andre Anjos <andre.anjos@idiap.ch> -.. Thu 25 Aug 2011 15:58:21 CEST - -.. _developer: - -======================= - The GridTk User Guide -======================= - -The ``gridtk`` framework is a python library to help submitting, tracking and -querying SGE. Here is quick example on how to use the ``gridtk`` framework to -submit a python script: - -.. code-block:: python - - import sys - from gridtk.sge import JobManagerSGE - from gridtk.tools import make_shell - - manager = JobManagerSGE() - command = make_shell(sys.executable, ['myscript.py', '--help']) - job = manager.submit(command) - - -You can do, programatically, everything you can do with the job manager - just -browse the help messages and the ``jman`` script for more information. - - -API to the Job Managers -======================= - -.. automodule:: gridtk.manager - :members: - - -.. automodule:: gridtk.sge - :members: - -.. automodule:: gridtk.local - :members: - - -The Models of the SQL3 Databases -================================ - -.. automodule:: gridtk.models - :members: - - -Middleware -========== - -.. automodule:: gridtk.tools - :members: - -Low-level Utilities -=================== - -.. automodule:: gridtk.setshell - :members: diff --git a/doc/usage-api.rst b/doc/usage-api.rst new file mode 100644 index 0000000000000000000000000000000000000000..036c9797b316bc93e92315cbdcc8634ecc703dd5 --- /dev/null +++ b/doc/usage-api.rst @@ -0,0 +1,30 @@ +.. SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +.. +.. SPDX-License-Identifier: GPL-3.0-or-later + +.. _gridtk.usage_api: + +=============== + Using the API +=============== + +The ``gridtk`` framework is a python library to help submitting, tracking and +querying SGE. Here is quick example on how to use the ``gridtk`` framework to +submit a python script: + +.. code:: python + + import sys + from gridtk.sge import JobManagerSGE + from gridtk.tools import make_shell + + manager = JobManagerSGE() + command = make_shell(sys.executable, ['myscript.py', '--help']) + job = manager.submit(command) + + +You can do, programatically, everything you can do with the job manager - just +browse the help messages and the ``jman`` script for more information. + + +.. include:: links.rst diff --git a/doc/manual.rst b/doc/usage-cli.rst similarity index 59% rename from doc/manual.rst rename to doc/usage-cli.rst index b08a4938dc0dec89023089a2ae0a76de7435f953..4ff751288ec9e4e90c69c5b5bc205ce3f3f9fa7b 100644 --- a/doc/manual.rst +++ b/doc/usage-cli.rst @@ -1,28 +1,30 @@ -.. vim: set fileencoding=utf-8 : -.. author: Manuel Günther <manuel.guenther@idiap.ch> -.. date: Fri Aug 30 14:31:49 CEST 2013 +.. SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +.. +.. SPDX-License-Identifier: GPL-3.0-or-later -.. _command_line: +.. _gridtk.usage_cli: -============================ - The Command Line Interface -============================ +======================== + Command Line Interface +======================== + +This section explains the use of ``gridtk`` through its command-line interface +(CLI). The Job Manager =============== -The most important utility is the Job Manager ``jman``. This Job Manager -can be used to: +The central important CLI is ``jman``, the "job manager". This application can +be used to: -* submit jobs +* submit jobs (with support for parametric/array jobs) * probe for submitted jobs * identify problems with submitted jobs * cleanup logs from submitted jobs * easily re-submit jobs if problems occur -* support for parametric (array) jobs -The Job Manager has a common set of parameters, which will be explained in the +``jman`` has a common set of parameters, which will be explained in the next section. Additionally, several commands can be issued, each of which has its own set of options. These commands will be explained afterwards. @@ -33,63 +35,66 @@ Basic Job Manager Parameters There are two versions of Job Managers: One that submits jobs to the SGE grid, and one that submits jobs so that they are run in parallel on the local machine. By default, the SGE manager is engaged. If you don't have access to -the SGE grid, or you want to submit locally, please issue the ``jman ---local`` (or shortly ``jman -l``) command. +the SGE grid, or you want to submit locally, issue the ``jman --local`` (or +shortly ``jman -l``) command instead. -To keep track of the submitted jobs, an SQL3 database is written. This -database is by default called ``submitted.sql3`` and put in the current -directory, but this can be changed using the ``jman --database`` -(``jman -d``) flag. +To keep track of the submitted jobs, a SQLite_ database is written. This +database is by default called ``submitted.sql3``, and put in the current +directory. This can be changed using the ``jman --database`` (``jman -d``) +flag. -Normally, the Job Manager acts silently, and only error messages are reported. -To make the Job Manager more verbose, you can use the ``--verbose`` (``-v``) -option several times, to increase the verbosity level to 1) WARNING, 2) INFO, -3) DEBUG. +Normally, the Job Manager acts silently, and only errors are reported. To make +the application more verbose, you can use the ``--verbose`` (``-v``) option +several times, to increase the verbosity level to 1) WARNING, 2) INFO, 3) +DEBUG. Submitting Jobs --------------- -To submit a job, the ``jman submit`` command is used. -The simplest way to submit a job to be run in the SGE grid is: +To submit a job, the ``jman submit`` command is used. The simplest way to +submit a job to be run in the SGE grid is: -.. code-block:: sh +.. code:: sh - $ jman -vv submit myscript.py + jman -vv submit myscript.py -This command will create an SQL3 database, submit the job to the grid and register it in the database. -To be more easily separable from other jobs in the database, you can give your job a name: +This command will create a SQLite database, submit the job to the grid and +register it in the database. To be more easily separable from other jobs in the +database, you can give your job a name: -.. code-block:: sh +.. code:: sh - $ jman -vv submit -n [name] myscript.py + jman -vv submit -n [name] myscript.py -If the job requires certain machine specifications, you can add these (please see the SGE manual for possible specifications of [key] and [value] pairs). +If the job requires certain machine specifications, you can add these (please +see the SGE manual for possible specifications of [key] and [value] pairs). Please note the ``--`` option that separates specifications from the command: -.. code-block:: sh +.. code:: sh - $ jman -vv submit -q [queue-name] -m [memory] --io-big -s [key1]=[value1] [key2]=[value2] -- myscript.py + jman -vv submit -q [queue-name] -m [memory] --io-big -s [key1]=[value1] [key2]=[value2] -- myscript.py To have jobs run in parallel, you can submit a parametric job. Simply call: -.. code-block:: sh +.. code:: sh - $ jman -vv submit -t 10 myscript.py + jman -vv submit -t 10 myscript.py to run ``myscript.py`` 10 times in parallel. Each of the parallel jobs will have a different environment variable called ``SGE_TASK_ID``, which will range from 1 to 10 in this case. If your script can handle this environment -variable, it can actually execute 10 different tasks. +variable, it can actually execute 10 different tasks (switched by the value of +the variable itself). Also, jobs with dependencies can be submitted. When submitted to the grid, -each job has its own job id. These job ids can be used to create dependencies -between the jobs (i.e., one job needs to finish before the next one can be -started): +each job has its own job identifier. These job ids can be used to create +dependencies between the jobs (i.e., one job needs to finish before the next +one can be started): -.. code-block:: sh +.. code:: sh - $ jman -vv submit -x [job_id_1] [job_id_2] -- myscript.py + jman -vv submit -x [job_id_1] [job_id_2] -- myscript.py In case the first job fails, it can automatically stop the depending jobs from being executed. Just submit jobs with the ``--stop-on-failure`` option. @@ -104,17 +109,18 @@ depend on the last one. This is useful when for GPU training when your jobs gets killed because you run out of time but you want to submit the same job again. -.. code-block:: sh +.. code:: sh - $ jman submit --repeat 5 -- myscript.py + jman submit --repeat 5 -- myscript.py -While the jobs run, the output and error stream are captured in log files, which are written into a ``logs`` directory. -This directory can be changed by specifying: +While the jobs run, the output and error stream are captured in log files, +which are written into a ``logs`` directory. This directory can be changed by +specifying: -.. code-block:: sh +.. code:: sh - $ jman -vv submit -l [log_dir] + jman -vv submit -l [log_dir] .. note:: @@ -125,58 +131,62 @@ This directory can be changed by specifying: has finished. -If the SGE backend is used, ``--sge-extra-args`` or shortly ``-e`` allows you to send -extra arguments to ``qsub``. +If the SGE backend is used, ``--sge-extra-args`` or shortly ``-e`` allows you +to send extra arguments to ``qsub``. -.. code-block:: sh +.. code:: sh - $ jman -vv submit -e="<sge_extra_args>" + jman -vv submit -e="<sge_extra_args>" For example, ``jman submit .. -e="-P project_name -l pytorch" -- ...`` will be translated to ``qsub ... -P project_name -l pytorch -- ...``. .. note:: - Note that extra options for qsub must be wrapped in single or double quotes **and** - should attach to the ``-e`` option with an ``=`` sign, e.g. ``jman submit -e='-P - project_name -l pytorch'``. Examples like ``jman submit -e '-P project_name -l - pytorch'`` and ``jman submit -e -P project_name -l pytorch`` will not work. + Note that extra options for qsub must be wrapped in single or double quotes + **and** should attach to the ``-e`` option with an ``=`` sign, e.g. ``jman + submit -e='-P project_name -l pytorch'``. Examples like ``jman submit -e '-P + project_name -l pytorch'`` and ``jman submit -e -P project_name -l pytorch`` + will not work. -To avoid adding the same ``-e`` option each time you run ``jman submit``, you may also -change its default value using :ref:`bob.extension.rc`. For example, if you run: +To avoid adding the same ``-e`` option each time you run ``jman submit``, you +may also change its default value via the gridtk configuration file. For +example, if you run: -.. code-block:: sh +.. code:: sh - $ bob config set -- gridtk.sge.extra.args.default "-P myproject" + bob config set -- gridtk.sge.extra.args.default "-P myproject" -Then, if you do ``jman submit ...``, this will translate to ``qsub -P myproject ...``. -This configuration only changes the default value, you still can provide a new value by -providing the ``-e`` option. +Then, if you do ``jman submit ...``, this will translate to ``qsub -P myproject +...``. This configuration only changes the default value, you still can provide +a new value by providing the ``-e`` option on the command-line. -Another (**recommended**) option is to always a prepend a string to this option. For -example, if you run: +Another (**recommended**) option is to always a prepend a string to this +option. For example, if you run: -.. code-block:: sh +.. code:: sh - $ bob config set -- gridtk.sge.extra.args.prepend "-P myproject" + bob config set -- gridtk.sge.extra.args.prepend "-P myproject" Then, if you do ``jman submit -e="-l pytorch"``, this will translate to -``qsub -P myproject -l pytorch``. +``qsub -P myproject -l pytorch`` and will work as expected. Running Jobs Locally -------------------- -When jobs are submitted to the SGE grid, they are run immediately. However, -when jobs are submitted locally, (using the ``--local`` option, see above), a -local scheduler needs to be run. This is achieved by issuing the command: +When jobs are submitted to the SGE grid, ``jman`` typically returns +immediately, as nothing gets really executed, but only scheduled. However, when +jobs are submitted locally, (using the ``--local`` option, see above), a local +scheduler, mimicking the SGE scheduler, needs to be run. This is achieved by +issuing the command: -.. code-block:: sh +.. code:: sh - $ jman -vv run-scheduler -p [parallel_jobs] -s [sleep_time] + jman -vv run-scheduler -p [parallel_jobs] -s [sleep_time] This will start the scheduler in the daemon mode. This will constantly monitor -the SQL3 database and execute jobs after submission, starting every +the SQLite database and execute jobs after submission, starting every ``[sleep_time]`` second. Use ``Ctrl-C`` to stop the scheduler (if jobs are still running locally, they will automatically be stopped). @@ -197,27 +207,27 @@ updated when jobs finish, you can use the ``jman list`` again after some time. Normally, long command lines are cut so that each job is listed in a single line. To get the full command line, please use the ``-vv`` option: -.. code-block:: sh +.. code:: sh - $ jman -vv list + jman -vv list By default, array jobs are not listed, but the ``-a`` option changes this behavior. Usually, it is a good idea to combine the ``-a`` option with ``-j``, which will list only the jobs of the given job id(s): -.. code-block:: sh +.. code:: sh - $ jman -vv list -a -j [job_id_1] [job_id_2] + jman -vv list -a -j [job_id_1] [job_id_2] Note that the ``-j`` option is in general relatively smart. You can use it to -select a range of job ids, e.g., ``-j 1-4 6-8 10+2`` is the same as -``-j 1 2 3 4 6 7 8 10 11 12``. In this case, please assert that there are no -spaces between job ids and the ``-`` and ``+`` separators. You cannot use both -``-`` and ``+`` in one part, i.e., something like ``-j 1-4+2`` will not work. -If any job id is specified, which is not available in the database, it will -simply be ignored, including job ids that are in the ranges. - -Since version 1.3.0, GridTK also saves timing information about jobs, i.e., +select a range of job ids, e.g., ``-j 1-4 6-8 10+2`` is the same as ``-j 1 2 3 +4 6 7 8 10 11 12``. In this case, please assert that there are no spaces +between job ids and the ``-`` and ``+`` separators. You cannot use both ``-`` +and ``+`` in one part, i.e., something like ``-j 1-4+2`` will not work. If any +job id is specified, which is not available in the database, it will simply be +ignored, including job ids that are in the ranges. + +Since version 1.3.0, ``gridtk`` also saves timing information about jobs, i.e., time stamps when jobs were submitted, started and finished. You can use the ``-t`` option of ``jman ls`` to add the time stamps to the listing, which are both written for jobs and parametric jobs (i.e., when using the ``-a`` option). @@ -227,12 +237,12 @@ Submitting dependent jobs ------------------------- Sometimes, the execution of one job might depend on the execution of another -job. The JobManager can take care of this, simply by adding the id of the job -that we have to wait for: +job. ``jman`` can take care of this, simply by adding the id of the job that we +have to wait for: -.. code-block:: sh +.. code:: sh - $ jman -vv submit --dependencies 6151645 -- /usr/bin/python myscript.py --help + jman -vv submit --dependencies 6151645 -- /usr/bin/python myscript.py --help ... Added job '<Job: 3> : submitted -- /usr/bin/python myscript.py --help' to the database ... Submitted job '<Job: 6151647> : queued -- /usr/bin/python myscript.py --help' to the SGE grid. @@ -247,13 +257,13 @@ Inspecting log files -------------------- When a job fails, the status will be ``failure``. In this case, you might want -to know, what happened. As a first indicator, the exit code of the program is -reported as well. Also, the output and error streams of the job has been -recorded and can be seen using the utilities. E.g.: +to know what happened. As a first indicator, the exit code of the program is +reported as well. Also, the output and error streams of the job are recorded +and can be seen using ``jman``. E.g.: -.. code-block:: sh +.. code:: sh - $ jman -vv report -j [job_id] -a [array_id] + jman -vv report -j [job_id] -a [array_id] will print the contents of the output and error log file from the job with the desired ID (and only the array job with the given ID). @@ -269,9 +279,9 @@ After correcting your code you might want to submit the same command line again. For this purpose, the ``jman resubmit`` command exists. Simply specify the job id(s) that you want to resubmit: -.. code-block:: sh +.. code:: sh - $ jman -vv resubmit -j [job_id_1] [job_id_2] + jman -vv resubmit -j [job_id_1] [job_id_2] This will clean up the old log files (if you didn't specify the ``--keep-logs`` option) and re-submit the job. If the submission is done in the grid the job @@ -285,9 +295,9 @@ In case you found an error in the code of a grid job that is currently executing, you might want to kill the job in the grid. For this purpose, you can use the command: -.. code-block:: sh +.. code:: sh - $ jman stop + jman stop The job is removed from the grid, but all log files are still available. A common use case is to stop the grid job, fix the bugs, and re-submit it. @@ -318,18 +328,18 @@ Cleaning up ----------- After the job was successfully (or not) executed, you should clean up the -database using the ``jman delete`` command. If not specified otherwise -(i.e., using the ``--keep-logs`` option), this command will delete all jobs -from the database and delete the log files (including the log directory in case -it is empty), and remove the database as well. +database using the ``jman delete`` command. If not specified otherwise (i.e., +using the ``--keep-logs`` option), this command will delete all jobs from the +database and delete the log files (including the log directory in case it is +empty), and remove the database as well. Again, job ids and array ids can be specified to limit the deleted jobs with the ``-j`` and ``-a`` option, respectively. It is also possible to clean up only those jobs (and array jobs) with a certain status. E.g. use: -.. code-block:: sh +.. code:: sh - $ jman -vv delete -s success -j 10-20 + jman -vv delete -s success -j 10-20 to delete all jobs and the logs of all successfully finished jobs with job ids from 10 to 20 from the database. @@ -338,14 +348,17 @@ from 10 to 20 from the database. Other command line tools ======================== -For convenience, we also provide additional command line tools, which are -mainly useful at Idiap. These tools are: - -- ``qstat.py``: writes the statuses of the jobs that are currently running - in the SGE grid -- ``qsub.py``: submit job to the SGE grid without logging them into the - database -- ``qdel.py``: delete job from the SGE grid without logging them into the - database -- ``grid``: executes the command in an grid environment (i.e., as if a - ``SETSHELL grid`` command would have been issued before) +For convenience, we also provide additional command line tools, which +*transparently* wrap the equivalent SGE tools, and make the process of using +SGE at Idiap a bit easier (no need to execute ``SETSHELL grid``, if this +package is installed): + +- qsub +- qdel +- qrst +- qstat +- qhost + +Please refer to the relevant manual pages for operational details. + +.. include:: links.rst diff --git a/gridtk/__init__.py b/gridtk/__init__.py deleted file mode 100644 index 065638411c53a62ceab1afc4a543979eb6a2e924..0000000000000000000000000000000000000000 --- a/gridtk/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -from . import easy, local, manager, setshell, sge, tests, tools # noqa: F401 - - -def get_config(): - """Returns a string containing the configuration information.""" - import bob.extension - - return bob.extension.get_config(__name__) - - -# gets sphinx autodoc done right - don't remove it -__all__ = [_ for _ in dir() if not _.startswith("_")] diff --git a/gridtk/config.py b/gridtk/config.py deleted file mode 100644 index 0784ea51c0307aa9bf236507fc5e202f7b568daa..0000000000000000000000000000000000000000 --- a/gridtk/config.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : -# Andre Anjos <andre.anjos@idiap.ch> -# Fri 13 Jul 2012 08:49:43 CEST - -"""Returns the currently compiled version number""" - -__version__ = __import__("pkg_resources").get_distribution("gridtk").version diff --git a/gridtk/generator.py b/gridtk/generator.py deleted file mode 100644 index 864ed9d935c67ee2db52e8dd7edacfce89286811..0000000000000000000000000000000000000000 --- a/gridtk/generator.py +++ /dev/null @@ -1,214 +0,0 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : - -"""Utilities for generating configurations for running experiments in batch""" - -import collections -import itertools - -import jinja2 -import yaml - -from bob.extension import rc - - -class dict(collections.OrderedDict): - """An OrderedDict class that can be compared. - This is to avoid sort errors (in Python 3) that happen in jinja internally. - """ - - def __lt__(self, other): - return id(self) < id(other) - - -def _ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=dict): - """Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s - - See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts - - """ - - class OrderedLoader(Loader): - pass - - def construct_mapping(loader, node): - loader.flatten_mapping(node) - return object_pairs_hook(loader.construct_pairs(node)) - - OrderedLoader.add_constructor( - yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, construct_mapping - ) - - return yaml.load(stream, OrderedLoader) - - -def expand(data): - """Generates configuration sets based on the YAML input contents - - For an introduction to the YAML mark-up, just search the net. Here is one of - its references: https://en.wikipedia.org/wiki/YAML - - A configuration set corresponds to settings for **all** variables in the - input template that needs replacing. For example, if your template mentions - the variables ``name`` and ``version``, then each configuration set should - yield values for both ``name`` and ``version``. - - For example: - - .. code-block:: yaml - - name: [john, lisa] - version: [v1, v2] - - - This should yield to the following configuration sets: - - .. code-block:: python - - [ - {'name': 'john', 'version': 'v1'}, - {'name': 'john', 'version': 'v2'}, - {'name': 'lisa', 'version': 'v1'}, - {'name': 'lisa', 'version': 'v2'}, - ] - - - Each key in the input file should correspond to either an object or a YAML - array. If the object is a list, then we'll iterate over it for every possible - combination of elements in the lists. If the element in question is not a - list, then it is considered unique and repeated for each yielded - configuration set. Example - - .. code-block:: yaml - - name: [john, lisa] - version: [v1, v2] - text: > - hello, - world! - - Should yield to the following configuration sets: - - .. code-block:: python - - [ - {'name': 'john', 'version': 'v1', 'text': 'hello, world!'}, - {'name': 'john', 'version': 'v2', 'text': 'hello, world!'}, - {'name': 'lisa', 'version': 'v1', 'text': 'hello, world!'}, - {'name': 'lisa', 'version': 'v2', 'text': 'hello, world!'}, - ] - - Keys starting with one `_` (underscore) are treated as "unique" objects as - well. Example: - - .. code-block:: yaml - - name: [john, lisa] - version: [v1, v2] - _unique: [i1, i2] - - Should yield to the following configuration sets: - - .. code-block:: python - - [ - {'name': 'john', 'version': 'v1', '_unique': ['i1', 'i2']}, - {'name': 'john', 'version': 'v2', '_unique': ['i1', 'i2']}, - {'name': 'lisa', 'version': 'v1', '_unique': ['i1', 'i2']}, - {'name': 'lisa', 'version': 'v2', '_unique': ['i1', 'i2']}, - ] - - - Parameters: - - data (str): YAML data to be parsed - - - Yields: - - dict: A dictionary of key-value pairs for building the templates - - """ - - data = _ordered_load(data, yaml.SafeLoader) - - # separates "unique" objects from the ones we have to iterate - # pre-assemble return dictionary - iterables = dict() - unique = dict() - for key, value in data.items(): - if isinstance(value, list) and not key.startswith("_"): - iterables[key] = value - else: - unique[key] = value - - # generates all possible combinations of iterables - for values in itertools.product(*iterables.values()): - retval = dict(unique) - keys = list(iterables.keys()) - retval.update(dict(zip(keys, values))) - yield retval - - -def generate(variables, template): - """Yields a resolved "template" for each config set and dumps on output - - This function will extrapolate the ``template`` file using the contents of - ``variables`` and will output individual (extrapolated, expanded) files in - the output directory ``output``. - - - Parameters: - - variables (str): A string stream containing the variables to parse, in YAML - format as explained on :py:func:`expand`. - - template (str): A string stream containing the template to extrapolate - - - Yields: - - str: A generated template you can save - - - Raises: - - jinja2.UndefinedError: if a variable used in the template is undefined - - """ - - env = jinja2.Environment(undefined=jinja2.StrictUndefined) - for c in expand(variables): - c["rc"] = rc - yield env.from_string(template).render(c) - - -def aggregate(variables, template): - """Generates a resolved "template" for **all** config sets and returns - - This function will extrapolate the ``template`` file using the contents of - ``variables`` and will output a single (extrapolated, expanded) file. - - - Parameters: - - variables (str): A string stream containing the variables to parse, in YAML - format as explained on :py:func:`expand`. - - template (str): A string stream containing the template to extrapolate - - - Returns: - - str: A generated template you can save - - - Raises: - - jinja2.UndefinedError: if a variable used in the template is undefined - - """ - - env = jinja2.Environment(undefined=jinja2.StrictUndefined) - d = {"cfgset": list(expand(variables)), "rc": rc} - return env.from_string(template).render(d) diff --git a/gridtk/script/grid.py b/gridtk/script/grid.py deleted file mode 100644 index f54cec70920e90a392f81a7bee7454ce0cd570d0..0000000000000000000000000000000000000000 --- a/gridtk/script/grid.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : - -"""Executes a given command within the context of a shell script that has its -enviroment set like Idiap's 'SETSHELL grid' does.""" - -from __future__ import print_function - -import os -import sys - - -def main(): - - from ..setshell import replace - - # get the name of the script that we actually want to execute - # (as defined in the setup.py) - prog = os.path.basename(sys.argv[0]) - # remove the .py extension, if available - if prog[-3:] == ".py": - prog = prog[:-3] - - if prog == "grid": - # act as before - if len(sys.argv) < 2: - print(__doc__) - print( - "usage: %s <command> [arg [arg ...]]" - % os.path.basename(sys.argv[0]) - ) - return 1 - - replace("grid", sys.argv[1:]) - else: - # call that specific command on the grid environment - replace("grid", [prog] + sys.argv[1:]) diff --git a/gridtk/script/jgen.py b/gridtk/script/jgen.py deleted file mode 100644 index fa70f98a2ab30a5f26346fd30f96e13c241904de..0000000000000000000000000000000000000000 --- a/gridtk/script/jgen.py +++ /dev/null @@ -1,187 +0,0 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : - - -"""Script generator for grid jobs - -This script can generate multiple output files based on a template and a set of -variables explained in a YAML file. It can also, optionally, generate a single -aggregated file for all possible configuration sets in the YAML file. It can be -used to: - - 1. Generate a set of runnable experiment configurations from a single - template - 2. Generate a single script to launch all runnable experiments - -""" - -__epilog__ = """\ - -examples: - To generate a configuration for running experiments and an aggregation script, - do the following: - - $ %(prog)s vars.yaml config.py 'out/cfg-{{ name }}-.py' run.sh out/run.sh - - In this example, the user dumps all output in a directory called "out". The - name of each output file uses variable expansion from the file "vars.yaml" to - create a new file for each configuration set defined inside. In this example, - we assume it defines at least variable "name" within with multiple values for - each configuration set. The file "run.sh" represents a template for the - aggregation and the extrapolated template will be saved at 'out/run.sh'. For - more information about how to structure these files, read the GridTK manual. - - To only generate the configurations and not the aggregation, omit the last - two parameters: - - $ %(prog)s vars.yaml config.py 'out/cfg-{{ name }}-.py' - -""" - -import argparse -import logging -import os -import sys - -from .. import generator, tools - - -def _setup_logger(verbosity): - - if verbosity > 3: - verbosity = 3 - - # set up the verbosity level of the logging system - log_level = { - 0: logging.ERROR, - 1: logging.WARNING, - 2: logging.INFO, - 3: logging.DEBUG, - }[verbosity] - - handler = logging.StreamHandler() - handler.setFormatter( - logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s") - ) - logger = logging.getLogger("gridtk") - logger.addHandler(handler) - logger.setLevel(log_level) - - return logger - - -def main(command_line_options=None): - - from ..config import __version__ - - basename = os.path.basename(sys.argv[0]) - epilog = __epilog__ % dict(prog=basename) - - formatter = argparse.RawTextHelpFormatter - parser = argparse.ArgumentParser( - description=__doc__, epilog=epilog, formatter_class=formatter - ) - - parser.add_argument( - "variables", - type=str, - help="Text file containing the variables in YAML format", - ) - parser.add_argument( - "gentmpl", - type=str, - help="Text file containing the template for generating multiple outputs, one for each configuration set", - ) - parser.add_argument( - "genout", type=str, help="Template for generating the output filenames" - ) - parser.add_argument( - "aggtmpl", - type=str, - nargs="?", - help="Text file containing the template for generating one single output out of all configuration sets", - ) - parser.add_argument( - "aggout", - type=str, - nargs="?", - help="Name of the output aggregation file", - ) - parser.add_argument( - "-v", - "--verbose", - action="count", - default=0, - help="Increase the verbosity level from 0 (only error messages) to 1 (warnings), 2 (log messages), 3 (debug information) by adding the --verbose option as often as desired (e.g. '-vvv' for debug).", - ) - parser.add_argument( - "-V", - "--version", - action="version", - version="GridTk version %s" % __version__, - ) - parser.add_argument( - "-u", - "--unique-aggregate", - dest="unique", - action="store_true", - help="It will make sure the output lines in aggout are unique while ignoring the empty lines and comment lines.", - ) - - # parse - if command_line_options: - args = parser.parse_args(command_line_options[1:]) - args.wrapper_script = command_line_options[0] - else: - args = parser.parse_args() - args.wrapper_script = sys.argv[0] - - # setup logging first - logger = _setup_logger(args.verbose) - - # check - if args.aggtmpl and not args.aggout: - logger.error("Missing aggregate output name") - sys.exit(1) - - # do all configurations and store - with open(args.variables, "rt") as f: - args.variables = f.read() - - with open(args.gentmpl, "rt") as f: - args.gentmpl = f.read() - - gdata = generator.generate(args.variables, args.gentmpl) - gname = generator.generate(args.variables, args.genout) - for fname, data in zip(gname, gdata): - dirname = os.path.dirname(fname) - if dirname: - tools.makedirs_safe(dirname) - with open(fname, "wt") as f: - f.write(data) - logger.info("Wrote `%s'", fname) - - # if user passed aggregator, do it as well - if args.aggtmpl and args.aggout: - with open(args.aggtmpl, "rt") as f: - args.aggtmpl = f.read() - data = generator.aggregate(args.variables, args.aggtmpl) - dirname = os.path.dirname(args.aggout) - if dirname: - tools.makedirs_safe(dirname) - with open(args.aggout, "wt") as f: - if args.unique: - unique_lines = [] - for line in data.split("\n"): - if not line.strip(): - f.write(line + "\n") - elif line.strip()[0] == "#": - f.write(line + "\n") - elif line not in unique_lines: - unique_lines.append(line) - f.write(line + "\n") - else: - f.write(data) - logger.info("Wrote `%s'", args.aggout) - - return 0 diff --git a/gridtk/tests/__init__.py b/gridtk/tests/__init__.py deleted file mode 100644 index 608a567c659e4287c81fa61e364bb9e9ad20f8d7..0000000000000000000000000000000000000000 --- a/gridtk/tests/__init__.py +++ /dev/null @@ -1,596 +0,0 @@ -from __future__ import print_function - -import os -import subprocess -import time -import unittest - -import pkg_resources - -import gridtk - -from ..models import Job - - -class GridTKTest(unittest.TestCase): - # This class defines tests for the gridtk - - def setUp(self): - # Create a temporary directory that will contain all outputs - import tempfile - - self.temp_dir = tempfile.mkdtemp(prefix="gridtk_test") - self.log_dir = os.path.join(self.temp_dir, "logs") - self.database = os.path.join(self.temp_dir, "database.sql3") - self.scheduler_job = None - - from ..manager import which - - bindir = os.path.join(os.path.realpath(os.curdir), "bin") - self.jman = which( - "jman", path=os.pathsep.join((bindir, os.environ["PATH"])) - ) - - def tearDown(self): - # make sure that all scheduler jobs are stopped after exiting - if self.scheduler_job: - self.scheduler_job.kill() - # Clean up the mess that we created - import shutil - - shutil.rmtree(self.temp_dir) - - def test01_local(self): - # This test executes all commands of the local grid manager and asserts that everything is fine - - # first test, if the '/bin/bash' exists - bash = "/bin/bash" - if not os.path.exists(bash): - raise unittest.SkipTest( - "Could not find '%s' which is required to run the test scripts" - % bash - ) - - try: - - import nose - - # first, add some commands to the database - script_1 = pkg_resources.resource_filename( - __name__, "test_script.sh" - ) - script_2 = pkg_resources.resource_filename( - __name__, "test_array.sh" - ) - rdir = pkg_resources.resource_filename("gridtk", "tests") - from gridtk.script import jman - - # add a simple script that will write some information to the - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_1", - bash, - script_1, - ] - ) - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_2", - "--dependencies", - "1", - "--parametric", - "1-7:2", - bash, - script_2, - ] - ) - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_3", - "--dependencies", - "1", - "2", - "--exec-dir", - rdir, - bash, - "test_array.sh", - ] - ) - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_1", - "--repeat", - "2", - bash, - script_1, - ] - ) - - # check that the database was created successfully - self.assertTrue(os.path.exists(self.database)) - - print() - # test that the list command works (should also work with the "default" grid manager - jman.main( - [ - self.jman, - "--database", - self.database, - "list", - "--job-ids", - "1", - ] - ) - jman.main( - [ - self.jman, - "--database", - self.database, - "list", - "--job-ids", - "2", - "--print-array-jobs", - "--print-dependencies", - "--print-times", - ] - ) - jman.main( - [ - self.jman, - "--database", - self.database, - "list", - "--job-ids", - "4-5", - "--print-array-jobs", - "--print-dependencies", - "--print-times", - ] - ) - - # get insight into the database - job_manager = gridtk.local.JobManagerLocal(database=self.database) - session = job_manager.lock() - jobs = list(session.query(Job)) - self.assertEqual(len(jobs), 5) - self.assertEqual(jobs[0].id, 1) - self.assertEqual(jobs[1].id, 2) - self.assertEqual(jobs[2].id, 3) - self.assertEqual(jobs[3].id, 4) - self.assertEqual(jobs[4].id, 5) - self.assertEqual(len(jobs[1].array), 4) - self.assertEqual(jobs[0].status, "submitted") - self.assertEqual(jobs[1].status, "submitted") - self.assertEqual(jobs[2].status, "submitted") - self.assertEqual(jobs[3].status, "submitted") - self.assertEqual(jobs[4].status, "submitted") - self.assertTrue(all(j.submit_time is not None for j in jobs)) - self.assertTrue(all(j.start_time is None for j in jobs)) - self.assertTrue(all(j.finish_time is None for j in jobs)) - self.assertTrue( - all(j.submit_time is not None for j in jobs[1].array) - ) - self.assertTrue(all(j.start_time is None for j in jobs[1].array)) - self.assertTrue(all(j.finish_time is None for j in jobs[1].array)) - - # check that the job dependencies are correct - waiting = jobs[0].get_jobs_waiting_for_us() - self.assertEqual(len(waiting), 2) - self.assertEqual(waiting[0].id, 2) - self.assertEqual(waiting[1].id, 3) - waited = jobs[2].get_jobs_we_wait_for() - self.assertEqual(len(waited), 2) - self.assertEqual(waited[0].id, 1) - self.assertEqual(waited[1].id, 2) - - # check dependencies for --repeat - waiting = jobs[3].get_jobs_waiting_for_us() - self.assertEqual(len(waiting), 1) - self.assertEqual(waiting[0].id, 5) - waited = jobs[4].get_jobs_we_wait_for() - self.assertEqual(len(waited), 1) - self.assertEqual(waited[0].id, 4) - - job_manager.unlock() - - # now, start the local execution of the job in a parallel job - self.scheduler_job = subprocess.Popen( - [ - self.jman, - "--local", - "--database", - self.database, - "run-scheduler", - "--sleep-time", - "5", - "--parallel", - "2", - ] - ) - - # sleep some time to assure that the scheduler was able to start the first job - time.sleep(5) - # ... and kill the scheduler - self.scheduler_job.kill() - self.scheduler_job = None - - # now, the first job needs to have status failure, and the second needs to be queued - session = job_manager.lock() - jobs = list(session.query(Job)) - self.assertEqual(len(jobs), 5) - if jobs[0].status in ("submitted", "queued", "executing"): - # on slow machines, we don0t want the tests to fail, so we just skip - job_manager.unlock() - raise nose.plugins.skip.SkipTest( - "This machine seems to be quite slow in processing parallel jobs." - ) - self.assertEqual(jobs[0].status, "failure") - self.assertEqual(jobs[1].status, "queued") - self.assertEqual(jobs[2].status, "waiting") - self.assertTrue(jobs[0].start_time is not None) - self.assertTrue(jobs[0].finish_time is not None) - self.assertTrue(jobs[1].start_time is None) - self.assertTrue(jobs[1].finish_time is None) - self.assertTrue(jobs[2].start_time is None) - self.assertTrue(jobs[2].finish_time is None) - - # the result files should already be there - self.assertTrue(os.path.exists(jobs[0].std_out_file())) - self.assertTrue(os.path.exists(jobs[0].std_err_file())) - job_manager.unlock() - - # reset the job 1 - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "resubmit", - "--job-id", - "1", - "--running-jobs", - "--overwrite-command", - bash, - script_1, - ] - ) - - # now, start the local execution of the job in a parallel job - self.scheduler_job = subprocess.Popen( - [ - self.jman, - "--local", - "--database", - self.database, - "run-scheduler", - "--sleep-time", - "5", - "--parallel", - "2", - ] - ) - - # sleep some time to assure that the scheduler was able to finish the first and start the second job - time.sleep(10) - # ... and kill the scheduler - self.scheduler_job.kill() - self.scheduler_job = None - - # Job 1 and two array jobs of job two should be finished now, the other two still need to be queued - session = job_manager.lock() - jobs = list(session.query(Job)) - self.assertEqual(len(jobs), 5) - if ( - jobs[0].status in ("queued", "executing") - or jobs[1].status == "queued" - ): - # on slow machines, we don0t want the tests to fail, so we just skip - job_manager.unlock() - raise nose.plugins.skip.SkipTest( - "This machine seems to be quite slow in processing parallel jobs." - ) - self.assertEqual(jobs[0].status, "failure") - self.assertEqual(jobs[1].status, "executing") - if ( - jobs[1].array[0].status == "executing" - or jobs[1].array[1].status == "executing" - ): - # on slow machines, we don0t want the tests to fail, so we just skip - job_manager.unlock() - raise nose.plugins.skip.SkipTest( - "This machine seems to be quite slow in processing parallel jobs." - ) - self.assertEqual(jobs[1].array[0].status, "failure") - self.assertEqual(jobs[1].array[0].result, 1) - self.assertEqual(jobs[1].array[1].status, "success") - self.assertEqual(jobs[1].array[1].result, 0) - self.assertEqual( - len([a for a in jobs[1].array if a.status == "queued"]), 2 - ) - out_file = jobs[0].std_out_file() - err_file = jobs[0].std_err_file() - job_manager.unlock() - - # the result files of the first job should now be there - self.assertTrue(os.path.isfile(out_file)) - self.assertTrue(os.path.isfile(err_file)) - self.assertEqual( - open(out_file).read().rstrip(), - "This is a text message to std-out", - ) - self.assertTrue( - "This is a text message to std-err" - in open(err_file).read().split("\n") - ) - - # resubmit all jobs - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "resubmit", - "--running-jobs", - ] - ) - # check that the log files have been cleaned - self.assertFalse(os.path.exists(out_file)) - self.assertFalse(os.path.exists(err_file)) - # ... but the log dir still exists - self.assertTrue(os.path.exists(self.log_dir)) - - # now, let the scheduler run all jobs, but this time in verbose mode - self.scheduler_job = subprocess.Popen( - [ - self.jman, - "--local", - "-vv", - "--database", - self.database, - "run-scheduler", - "--sleep-time", - "1", - "--parallel", - "2", - "--die-when-finished", - ] - ) - # and wait for the job to finish (the timeout argument to Popen only exists from python 3.3 onwards) - self.scheduler_job.wait() - self.scheduler_job = None - - # check that all output files are generated again - self.assertTrue(os.path.isfile(out_file)) - self.assertTrue(os.path.isfile(err_file)) - self.assertEqual( - open(out_file).read().rstrip(), - "This is a text message to std-out", - ) - self.assertTrue( - "This is a text message to std-err" - in open(err_file).read().split("\n") - ) - - # check that exactly four output and four error files have been created - files = os.listdir(self.log_dir) - self.assertEqual(len(files), 16) - for i in range(1, 8, 2): - self.assertTrue("test_2.o2.%d" % i in files) - self.assertTrue("test_2.e2.%d" % i in files) - - # check that all array jobs are finished now - session = job_manager.lock() - jobs = list(session.query(Job)) - self.assertEqual(len(jobs), 5) - self.assertEqual(jobs[1].status, "failure") - self.assertEqual(jobs[1].array[0].status, "failure") - self.assertEqual(jobs[1].array[0].result, 1) - for i in range(1, 4): - self.assertEqual(jobs[1].array[i].status, "success") - self.assertEqual(jobs[1].array[i].result, 0) - self.assertEqual(jobs[2].status, "success") - self.assertEqual(jobs[2].result, 0) - - self.assertTrue(all(j.submit_time is not None for j in jobs)) - self.assertTrue(all(j.start_time is not None for j in jobs)) - self.assertTrue(all(j.finish_time is not None for j in jobs)) - self.assertTrue( - all(j.submit_time is not None for j in jobs[1].array) - ) - self.assertTrue( - all(j.start_time is not None for j in jobs[1].array) - ) - self.assertTrue( - all(j.finish_time is not None for j in jobs[1].array) - ) - - job_manager.unlock() - - print() - # test that the list command still works - jman.main( - [ - self.jman, - "--database", - self.database, - "list", - "--print-array-jobs", - ] - ) - jman.main( - [ - self.jman, - "--database", - self.database, - "list", - "--long", - "--print-array-jobs", - ] - ) - - print() - # test that the report command works - jman.main([self.jman, "--database", self.database, "report"]) - - # clean-up - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "delete", - "--job-ids", - "1+4", - ] - ) - - # check that the database and the log files are gone - self.assertEqual(len(os.listdir(self.temp_dir)), 0) - - # add the scripts again, but this time with the --stop-on-failure option - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_1", - "--stop-on-failure", - bash, - script_1, - ] - ) - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_2", - "--dependencies", - "1", - "--parametric", - "1-7:2", - "--stop-on-failure", - bash, - script_2, - ] - ) - jman.main( - [ - self.jman, - "--local", - "--database", - self.database, - "submit", - "--log-dir", - self.log_dir, - "--name", - "test_3", - "--dependencies", - "1", - "2", - "--exec-dir", - rdir, - "--stop-on-failure", - bash, - "test_array.sh", - ] - ) - - # and execute them, but without writing the log files - self.scheduler_job = subprocess.Popen( - [ - self.jman, - "--local", - "--database", - self.database, - "run-scheduler", - "--sleep-time", - "0.1", - "--parallel", - "2", - "--die-when-finished", - "--no-log-files", - ] - ) - # and wait for the job to finish (the timeout argument to Popen only exists from python 3.3 onwards) - self.scheduler_job.wait() - self.scheduler_job = None - - # assert that the log files are not there - self.assertFalse(os.path.isfile(out_file)) - self.assertFalse(os.path.isfile(err_file)) - - # check that all array jobs are finished now - session = job_manager.lock() - jobs = list(session.query(Job)) - self.assertEqual(len(jobs), 3) - self.assertEqual(jobs[0].status, "failure") - self.assertEqual(jobs[0].result, 255) - self.assertEqual(jobs[1].status, "failure") - self.assertTrue(jobs[1].result is None) - self.assertEqual(jobs[2].status, "failure") - self.assertTrue(jobs[2].result is None) - job_manager.unlock() - - # and clean up again - jman.main( - [self.jman, "--local", "--database", self.database, "delete"] - ) - self.assertEqual(len(os.listdir(self.temp_dir)), 0) - - except KeyboardInterrupt: - # make sure that the keyboard interrupt is captured and the mess is cleaned up (i.e. by calling tearDown) - pass - - def notest02_grid(self): - # Tests the functionality of the grid toolkit in the grid - import nose - - raise nose.plugins.skip.SkipTest( - "This test is not yet implemented. If you find a proper ways to test the grid functionality, please go ahead and implement the test." - ) diff --git a/gridtk/tests/test_array.sh b/gridtk/tests/test_array.sh deleted file mode 100644 index 06e391bc1ca224fac8c0429c5aa49bb32b309916..0000000000000000000000000000000000000000 --- a/gridtk/tests/test_array.sh +++ /dev/null @@ -1,7 +0,0 @@ -echo "The job id is '$JOB_ID' and the task id is '$SGE_TASK_ID'" - -if [[ $SGE_TASK_ID == '1' ]]; then - exit 1 -else - exit 0 -fi diff --git a/gridtk/tests/test_generator.py b/gridtk/tests/test_generator.py deleted file mode 100644 index 1ddfff33241e3054534e84d242dc7f8bc14734e0..0000000000000000000000000000000000000000 --- a/gridtk/tests/test_generator.py +++ /dev/null @@ -1,373 +0,0 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : - -"""Test for the grid-search generator""" - - -import os -import shutil -import tempfile - -import nose.tools - -from ..generator import aggregate, expand, generate -from ..script import jgen - - -def test_simple(): - - data = "name: [john, lisa]\n" "version: [v1, v2]" - - result = list(expand(data)) - expected = [ - {"name": "john", "version": "v1"}, - {"name": "john", "version": "v2"}, - {"name": "lisa", "version": "v1"}, - {"name": "lisa", "version": "v2"}, - ] - - nose.tools.eq_(result, expected) - - -def test_unique(): - - data = ( - "name: [john, lisa]\n" - "version: [v1, v2]\n" - "text: >\n" - " hello,\n" - " world!" - ) - - result = list(expand(data)) - expected = [ - {"name": "john", "version": "v1", "text": "hello, world!"}, - {"name": "john", "version": "v2", "text": "hello, world!"}, - {"name": "lisa", "version": "v1", "text": "hello, world!"}, - {"name": "lisa", "version": "v2", "text": "hello, world!"}, - ] - - nose.tools.eq_(result, expected) - - -def test_ignore(): - - data = "name: [john, lisa]\n" "version: [v1, v2]\n" "_unique: [i1, i2]" - - result = list(expand(data)) - expected = [ - {"name": "john", "version": "v1", "_unique": ["i1", "i2"]}, - {"name": "john", "version": "v2", "_unique": ["i1", "i2"]}, - {"name": "lisa", "version": "v1", "_unique": ["i1", "i2"]}, - {"name": "lisa", "version": "v2", "_unique": ["i1", "i2"]}, - ] - - nose.tools.eq_(result, expected) - - -def test_generation(): - - data = "name: [john, lisa]\n" "version: [v1, v2]" - - template = "{{ name }} - {{ version }}" - - expected = [ - "john - v1", - "john - v2", - "lisa - v1", - "lisa - v2", - ] - - result = list(generate(data, template)) - nose.tools.eq_(result, expected) - - -def test_aggregation(): - - data = "name: [john, lisa]\n" "version: [v1, v2]" - - template = ( - "{% for k in cfgset %}{{ k.name }} - {{ k.version }}\n{% endfor %}" - ) - - expected = "\n".join( - [ - "john - v1", - "john - v2", - "lisa - v1", - "lisa - v2\n", - ] - ) - - result = aggregate(data, template) - nose.tools.eq_(result, expected) - - -def test_cmdline_generation(): - - data = "name: [john, lisa]\n" "version: [v1, v2]" - - template = "{{ name }}-{{ version }}" - - expected = [ - "john-v1", - "john-v2", - "lisa-v1", - "lisa-v2", - ] - - tmpdir = tempfile.mkdtemp() - - try: - variables = os.path.join(tmpdir, "variables.yaml") - with open(variables, "wt") as f: - f.write(data) - gentmpl = os.path.join(tmpdir, "gentmpl.txt") - with open(gentmpl, "wt") as f: - f.write(template) - genout = os.path.join(tmpdir, "out", "{{ name }}-{{ version }}.txt") - nose.tools.eq_(jgen.main(["-vv", variables, gentmpl, genout]), 0) - - # check all files are there and correspond to the expected output - outdir = os.path.dirname(genout) - for k in expected: - ofile = os.path.join(outdir, k + ".txt") - assert os.path.exists(ofile) - with open(ofile, "rt") as f: - contents = f.read() - nose.tools.eq_(contents, k) - - finally: - shutil.rmtree(tmpdir) - - -def test_cmdline_aggregation(): - - data = "name: [john, lisa]\n" "version: [v1, v2]" - - template = "{{ name }}-{{ version }}" - - aggtmpl = "{% for k in cfgset %}{{ k.name }}-{{ k.version }}\n{% endfor %}" - - gen_expected = [ - "john-v1", - "john-v2", - "lisa-v1", - "lisa-v2", - ] - - agg_expected = "\n".join( - [ - "john-v1", - "john-v2", - "lisa-v1", - "lisa-v2\n", - ] - ) - - tmpdir = tempfile.mkdtemp() - - try: - variables = os.path.join(tmpdir, "variables.yaml") - with open(variables, "wt") as f: - f.write(data) - gentmpl = os.path.join(tmpdir, "gentmpl.txt") - with open(gentmpl, "wt") as f: - f.write(template) - genout = os.path.join(tmpdir, "out", "{{ name }}-{{ version }}.txt") - - aggtmpl_file = os.path.join(tmpdir, "agg.txt") - with open(aggtmpl_file, "wt") as f: - f.write(aggtmpl) - aggout = os.path.join(tmpdir, "out", "agg.txt") - - nose.tools.eq_( - jgen.main( - ["-vv", variables, gentmpl, genout, aggtmpl_file, aggout] - ), - 0, - ) - - # check all files are there and correspond to the expected output - outdir = os.path.dirname(genout) - for k in gen_expected: - ofile = os.path.join(outdir, k + ".txt") - assert os.path.exists(ofile) - with open(ofile, "rt") as f: - contents = f.read() - nose.tools.eq_(contents, k) - assert os.path.exists(aggout) - with open(aggout, "rt") as f: - contents = f.read() - nose.tools.eq_(contents, agg_expected) - - finally: - shutil.rmtree(tmpdir) - - -def test_cmdline_unique_aggregation(): - - data = "name: [john, lisa]\n" "version: [v1, v2]" - - template = "{{ name }}-{{ version }}" - - aggtmpl = """{% for k in cfgset %} -# comment lines and empty lines should repeat -# k.name -{{ k.name }} -# k.version -{{ k.version }} -{% endfor %} -""" - - gen_expected = [ - "john-v1", - "john-v2", - "lisa-v1", - "lisa-v2", - ] - - agg_expected = "\n".join( - [ - "", - "# comment lines and empty lines should repeat", - "# k.name", - "john", - "# k.version", - "v1", - "", - "# comment lines and empty lines should repeat", - "# k.name", - "# k.version", - "v2", - "", - "# comment lines and empty lines should repeat", - "# k.name", - "lisa", - "# k.version", - "", - "# comment lines and empty lines should repeat", - "# k.name", - "# k.version", - "", - "", - ] - ) - - tmpdir = tempfile.mkdtemp() - - try: - variables = os.path.join(tmpdir, "variables.yaml") - with open(variables, "wt") as f: - f.write(data) - gentmpl = os.path.join(tmpdir, "gentmpl.txt") - with open(gentmpl, "wt") as f: - f.write(template) - genout = os.path.join(tmpdir, "out", "{{ name }}-{{ version }}.txt") - - aggtmpl_file = os.path.join(tmpdir, "agg.txt") - with open(aggtmpl_file, "wt") as f: - f.write(aggtmpl) - aggout = os.path.join(tmpdir, "out", "agg.txt") - - nose.tools.eq_( - jgen.main( - ["-vv", "-u", variables, gentmpl, genout, aggtmpl_file, aggout] - ), - 0, - ) - - # check all files are there and correspond to the expected output - outdir = os.path.dirname(genout) - for k in gen_expected: - ofile = os.path.join(outdir, k + ".txt") - assert os.path.exists(ofile) - with open(ofile, "rt") as f: - contents = f.read() - nose.tools.eq_(contents, k) - assert os.path.exists(aggout) - with open(aggout, "rt") as f: - contents = f.read() - nose.tools.eq_(contents, agg_expected) - - finally: - shutil.rmtree(tmpdir) - - -def test_cmdline_aggregation_dict_groupby(): - - data = """ -model: - - {name: patch_1, patch_size: 28} - -train: - - {database: replaymobile, protocol: grandtest} - - {database: replay, protocol: grandtest} - -eval: - - {database: replaymobile, protocol: grandtest, groups: ['dev', 'eval']} - - {database: replay, protocol: grandtest, groups: ['dev', 'eval']} -""" - - template = "{{ model.name }}-{{ train.database }}-{{ eval.database }}" - - aggtmpl = """ -{% set cfg2 = cfgset|groupby('train')|map(attribute='list') -%} -{% for cfg3 in cfg2 %} -{% set k = cfg3[0] -%} -test-{{ k.model.name }}-{{ k.train.database }}-{{ k.eval.database }} -{%- endfor %} -""" - - gen_expected = [ - "patch_1-replay-replay", - "patch_1-replay-replaymobile", - "patch_1-replaymobile-replay", - "patch_1-replaymobile-replaymobile", - ] - - agg_expected = [ - "", - "", - "test-patch_1-replaymobile-replaymobile", - "test-patch_1-replay-replaymobile", - ] - tmpdir = tempfile.mkdtemp() - - try: - variables = os.path.join(tmpdir, "variables.yaml") - with open(variables, "wt") as f: - f.write(data) - gentmpl = os.path.join(tmpdir, "gentmpl.txt") - with open(gentmpl, "wt") as f: - f.write(template) - genout = os.path.join(tmpdir, "out", template + ".txt") - - aggtmpl_file = os.path.join(tmpdir, "agg.txt") - with open(aggtmpl_file, "wt") as f: - f.write(aggtmpl) - aggout = os.path.join(tmpdir, "out", "agg.txt") - - nose.tools.eq_( - jgen.main( - ["-vv", variables, gentmpl, genout, aggtmpl_file, aggout] - ), - 0, - ) - - # check all files are there and correspond to the expected output - outdir = os.path.dirname(genout) - for k in gen_expected: - ofile = os.path.join(outdir, k + ".txt") - assert os.path.exists(ofile) - with open(ofile, "rt") as f: - contents = f.read() - nose.tools.eq_(contents, k) - assert os.path.exists(aggout) - with open(aggout, "rt") as f: - contents = f.read() - for line in agg_expected: - assert line in contents, contents - - finally: - shutil.rmtree(tmpdir) diff --git a/pyproject.toml b/pyproject.toml index b738dc847ff9705c5769673db7415f2eb9a75f4d..e2b2d4633ecadbeaaf0e73aa8c5064979aeb8406 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,92 @@ +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + [build-system] - requires = ["setuptools", "wheel", "bob.extension"] + requires = ["setuptools>=61.0.0", "wheel"] build-backend = "setuptools.build_meta" +[project] +name = "gridtk" +version = "1.8.6b0" +requires-python = ">=3.9" +description = "Grid-enabled job submitter and execution monitor for Idiap" +dynamic = ["readme"] +license = {text = "GNU General Public License v3 (GPLv3)"} +authors = [ + {name = "Andre Anjos", email = "andre.anjos@idiap.ch"}, + {name = "Manuel Guenther", email = "manuel.guenther@idiap.ch"}, +] +classifiers = [ + "Development Status :: 5 - Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Natural Language :: English", + "Programming Language :: Python :: 3", + "Topic :: Software Development :: Libraries :: Python Modules", +] +dependencies = [ + "exposed", + "sqlalchemy", +] + +[project.urls] +documentation = "https://www.idiap.ch/software/bob/docs/bob/gridtk/main/sphinx" +homepage = "https://pypi.org/project/gridtk" +repository = "https://gitlab.idiap.ch/bob/gridtk" +changelog = "https://gitlab.idiap.ch/bob/gridtk/-/releases" + +[project.optional-dependencies] +qa = ["pre-commit"] +doc = [ + "sphinx", + "furo", + "sphinx-autodoc-typehints", + "sphinx-copybutton", + "sphinx-inline-tabs", + "auto-intersphinx", + ] +test = [ + "pytest", + "pytest-cov", + "coverage", + ] + +[project.scripts] +jman = "gridtk.script.jman:main" + +# access to SGE utilities from package installation +qconf = "gridtk.script.grid:main" +qsub = "gridtk.script.grid:main" +qdel = "gridtk.script.grid:main" +qstat = "gridtk.script.grid:main" +qrsh = "gridtk.script.grid:main" +qhost = "gridtk.script.grid:main" + +[tool.setuptools] +zip-safe = true +package-dir = {"" = "src"} + +[tool.setuptools.dynamic] +readme = {file = "README.md"} + +[tool.distutils.bdist_wheel] +universal = true + [tool.isort] - profile = "black" - line_length = 80 - order_by_type = true - lines_between_types = 1 +profile = "black" +line_length = 80 +order_by_type = true +lines_between_types = 1 [tool.black] - line-length = 80 +line-length = 80 + +[tool.pytest.ini_options] +addopts = [ + "--cov=gridtk", + "--cov-report=term-missing", + "--import-mode=append", +] +junit_logging = "all" +junit_log_passing_tests = false diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 4ea554e971d9040e23d91529e6ceb91d6095d739..0000000000000000000000000000000000000000 --- a/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -jinja2 -pyyaml -sqlalchemy -bob.extension diff --git a/setup.py b/setup.py index f9142842325a96759536e1afc5a930c3fbf7c969..9fef855da8905a9f8aaa9d6844a4fac5e66cdbcc 100644 --- a/setup.py +++ b/setup.py @@ -1,39 +1,7 @@ -from setuptools import find_packages, setup +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -version = open("version.txt").read().rstrip() -requirements = [k.strip() for k in open("requirements.txt").read().split()] +from setuptools import setup -setup( - name="gridtk", - version=version, - description="Parallel Job Manager", - long_description=open("README.rst").read(), - url="https://gitlab.idiap.ch/bob/gridtk", - license="GPLv3", - author="Manuel Guenther,Andre Anjos", - author_email="manuel.guenther@idiap.ch,andre.anjos@idiap.ch", - packages=find_packages(), - include_package_data=True, - install_requires=requirements, - entry_points={ - "console_scripts": [ - "jman = gridtk.script.jman:main", - "jgen = gridtk.script.jgen:main", - "grid = gridtk.script.grid:main", - # program replacements - "qstat.py = gridtk.script.grid:main", - "qdel.py = gridtk.script.grid:main", - "qsub.py = gridtk.script.grid:main", - "man.py = gridtk.script.grid:main", - ], - }, - classifiers=[ - "Development Status :: 4 - Beta", - "Intended Audience :: Developers", - "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", - "Natural Language :: English", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Topic :: System :: Clustering", - ], -) +setup() diff --git a/gridtk/script/__init__.py b/src/gridtk/__init__.py similarity index 100% rename from gridtk/script/__init__.py rename to src/gridtk/__init__.py diff --git a/gridtk/easy.py b/src/gridtk/easy.py similarity index 93% rename from gridtk/easy.py rename to src/gridtk/easy.py index ff81b30d4f3258b90daded6b98f8e17ae14c0312..f2f33b13ad357c0e45a834a16aa56b3e04ec47b8 100644 --- a/gridtk/easy.py +++ b/src/gridtk/easy.py @@ -1,10 +1,8 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : -# Andre Anjos <andre.anjos@idiap.ch> -# Fri 24 Feb 2012 12:46:51 CET +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -"""Common arguments to grid jobs -""" +"""Common arguments to grid jobs.""" import os import sys @@ -121,7 +119,8 @@ def add_arguments(parser): def create_manager(arguments): - """A simple wrapper to JobManager() that places the statefile on the correct path by default""" + """A simple wrapper to JobManager() that places the statefile on the + correct path by default.""" if arguments.statefile is None: arguments.statefile = os.path.join( @@ -133,8 +132,8 @@ def create_manager(arguments): return manager.JobManager(statefile=arguments.statefile) -class DryRunJob(object): - """A simple wrapper for dry-run jobs that behaves like a normal job""" +class DryRunJob: + """A simple wrapper for dry-run jobs that behaves like a normal job.""" # distributed as jobs are "submitted" current_id = 0 @@ -211,9 +210,11 @@ class DryRunJob(object): def submit(jman, command, arguments, deps=[], array=None): - """An easy submission option for grid-enabled scripts. Create the log - directories using random hash codes. Use the arguments as parsed by the main - script.""" + """An easy submission option for grid-enabled scripts. + + Create the log directories using random hash codes. Use the + arguments as parsed by the main script. + """ logdir = os.path.join( os.path.realpath(arguments.logdir), tools.random_logdir() diff --git a/gridtk/local.py b/src/gridtk/local.py similarity index 97% rename from gridtk/local.py rename to src/gridtk/local.py index 833a81074a75d84a71352cde0204c8bce24f7260..5d2fc50413b34f3d764c3d6bcd204055ae533e62 100644 --- a/gridtk/local.py +++ b/src/gridtk/local.py @@ -1,14 +1,12 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : -# Andre Anjos <andre.anjos@idiap.ch> -# Wed 24 Aug 2011 13:06:25 CEST +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -"""Defines the job manager which can help you managing submitted grid jobs. -""" -from __future__ import print_function +"""Defines the job manager which can help you managing submitted grid jobs.""" import copy +import logging import os import subprocess import sys @@ -16,21 +14,22 @@ import time from .manager import JobManager from .models import add_job -from .tools import logger, makedirs_safe + +logger = logging.getLogger(__name__) class JobManagerLocal(JobManager): """Manages jobs run in parallel on the local machine.""" def __init__(self, **kwargs): - """Initializes this object with a state file and a method for qsub'bing. + """Initializes this object with a state file and a method for + qsub'bing. Keyword parameters: statefile The file containing a valid status database for the manager. If the file does not exist it is initialized. If it exists, it is loaded. - """ JobManager.__init__(self, **kwargs) @@ -46,8 +45,11 @@ class JobManagerLocal(JobManager): stop_on_failure=False, **kwargs ): - """Submits a job that will be executed on the local machine during a call to "run". - All kwargs will simply be ignored.""" + """Submits a job that will be executed on the local machine during a + call to "run". + + All kwargs will simply be ignored. + """ # remove duplicate dependencies dependencies = sorted(list(set(dependencies))) @@ -92,7 +94,7 @@ class JobManagerLocal(JobManager): keep_logs=False, **kwargs ): - """Re-submit jobs automatically""" + """Re-submit jobs automatically.""" self.lock() # iterate over all jobs jobs = self.get_jobs(job_ids) @@ -130,7 +132,8 @@ class JobManagerLocal(JobManager): self.unlock() def stop_jobs(self, job_ids=None): - """Resets the status of the job to 'submitted' when they are labeled as 'executing'.""" + """Resets the status of the job to 'submitted' when they are labeled as + 'executing'.""" self.lock() jobs = self.get_jobs(job_ids) @@ -150,7 +153,8 @@ class JobManagerLocal(JobManager): self.unlock() def stop_job(self, job_id, array_id=None): - """Resets the status of the given to 'submitted' when they are labeled as 'executing'.""" + """Resets the status of the given to 'submitted' when they are labeled + as 'executing'.""" self.lock() job, array_job = self._job_and_array(job_id, array_id) @@ -221,7 +225,7 @@ class JobManagerLocal(JobManager): if no_log or job.log_dir is None: out, err = sys.stdout, sys.stderr else: - makedirs_safe(job.log_dir) + os.makedirs(job.log_dir, exist_ok=True) # create line-buffered files for writing output and error status if array_job is not None: out, err = open(array_job.std_out_file(), "w", 1), open( @@ -269,7 +273,8 @@ class JobManagerLocal(JobManager): nice=None, verbosity=0, ): - """Starts the scheduler, which is constantly checking for jobs that should be ran.""" + """Starts the scheduler, which is constantly checking for jobs that + should be ran.""" running_tasks = [] finished_tasks = set() try: diff --git a/gridtk/manager.py b/src/gridtk/manager.py similarity index 95% rename from gridtk/manager.py rename to src/gridtk/manager.py index 603be886424f504b4b7b8da35c67ca60028d6e67..9b44cdc0e807e91716926c4baa3060597b03c750 100644 --- a/gridtk/manager.py +++ b/src/gridtk/manager.py @@ -1,20 +1,24 @@ -from __future__ import print_function +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later +import logging import os import socket # to get the host name import subprocess -from distutils.version import LooseVersion from shutil import which import sqlalchemy from .models import ArrayJob, Base, Job, Status, times -from .tools import logger + +logger = logging.getLogger(__name__) class JobManager: - """This job manager defines the basic interface for handling jobs in the SQL database.""" + """This job manager defines the basic interface for handling jobs in the + SQL database.""" def __init__( self, database="submitted.sql3", wrapper_script=None, debug=False @@ -38,11 +42,11 @@ class JobManager: ) if wrapper_script is None: - raise IOError( + raise OSError( "Could not find the installation path of gridtk. Please specify it in the wrapper_script parameter of the JobManager." ) if not os.path.exists(wrapper_script): - raise IOError( + raise OSError( "Your wrapper_script cannot be found. Jobs will not be executable." ) self.wrapper_script = wrapper_script @@ -63,19 +67,13 @@ class JobManager: os.remove(self._database) def lock(self): - """Generates (and returns) a blocking session object to the database.""" + """Generates (and returns) a blocking session object to the + database.""" if hasattr(self, "session"): raise RuntimeError( "Dead lock detected. Please do not try to lock the session when it is already locked!" ) - if LooseVersion(sqlalchemy.__version__) < LooseVersion("0.7.8"): - # for old sqlalchemy versions, in some cases it is required to re-generate the engine for each session - self._engine = sqlalchemy.create_engine( - "sqlite:///" + self._database - ) - self._session_maker = sqlalchemy.orm.sessionmaker(bind=self._engine) - # create the database if it does not exist yet if not os.path.exists(self._database): self._create() @@ -97,10 +95,9 @@ class JobManager: def _create(self): """Creates a new and empty database.""" - from .tools import makedirs_safe # create directory for sql database - makedirs_safe(os.path.dirname(self._database)) + os.makedirs(os.path.dirname(self._database), exist_ok=True) # create all the tables Base.metadata.create_all(self._engine) @@ -144,7 +141,8 @@ class JobManager: return (job, None) def run_job(self, job_id, array_id=None): - """This function is called to run a job (e.g. in the grid) with the given id and the given array index if applicable.""" + """This function is called to run a job (e.g. in the grid) with the + given id and the given array index if applicable.""" # set the job's status in the database try: # get the job from the database @@ -311,7 +309,8 @@ class JobManager: status=Status, name=None, ): - """Iterates through the output and error files and write the results to command line.""" + """Iterates through the output and error files and write the results to + command line.""" def _write_contents(job): # Writes the contents of the output and error files to command line diff --git a/gridtk/models.py b/src/gridtk/models.py similarity index 94% rename from gridtk/models.py rename to src/gridtk/models.py index a1ceb097bac10ba6f4e1f302f20f4324021766b4..dd945a629e381052f265731ed7889c7639717629 100644 --- a/gridtk/models.py +++ b/src/gridtk/models.py @@ -1,3 +1,8 @@ +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +import logging import os from datetime import datetime @@ -12,12 +17,16 @@ from sqlalchemy import ( Integer, String, ) -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import relationship +from sqlalchemy.orm import declarative_base, relationship + +logger = logging.getLogger(__name__) + -from .tools import logger +class Base: + __allow_unmapped__ = True -Base = declarative_base() + +Base = declarative_base(cls=Base) # type: ignore Status = ("submitted", "queued", "waiting", "executing", "success", "failure") @@ -71,7 +80,7 @@ class ArrayJob(Base): r = "%s (%d)" % (self.status, self.result) else: r = "%s" % self.status - return "%s : %s" % (n, r) + return f"{n} : {r}" def format(self, format): """Formats the current job into a nicer string to fit into a table.""" @@ -139,7 +148,7 @@ class Job(Base): queue_name="local", machine_name=None, stop_on_failure=False, - **kwargs + **kwargs, ): """Constructs a Job object without an ID (needs to be set later).""" self.command_line = dumps(command_line) @@ -300,7 +309,8 @@ class Job(Base): ) def get_arguments(self): - """Returns the additional options for the grid (such as the queue, memory requirements, ...).""" + """Returns the additional options for the grid (such as the queue, + memory requirements, ...).""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly args = ( @@ -381,7 +391,7 @@ class Job(Base): def __str__(self): id = "%d (%d)" % (self.unique, self.id) if self.machine_name: - m = "%s - %s" % (self.queue_name, self.machine_name) + m = f"{self.queue_name} - {self.machine_name}" else: m = self.queue_name if self.array: @@ -389,14 +399,14 @@ class Job(Base): else: a = "" if self.name is not None: - n = "<Job: %s %s - '%s'>" % (id, a, self.name) + n = f"<Job: {id} {a} - '{self.name}'>" else: n = "<Job: %s>" % id if self.result is not None: r = "%s (%d)" % (self.status, self.result) else: r = "%s" % self.status - return "%s | %s : %s -- %s" % (n, m, r, self._cmdline()) + return f"{n} | {m} : {r} -- {self._cmdline()}" def format(self, format, dependencies=0, limit_command_line=None): """Formats the current job into a nicer string to fit into a table.""" @@ -423,10 +433,7 @@ class Job(Base): command_line = ( "<" + ",".join( - [ - "%s=%s" % (key, value) - for key, value in grid_opt.items() - ] + [f"{key}={value}" for key, value in grid_opt.items()] ) + ">: " + command_line @@ -439,9 +446,7 @@ class Job(Base): if dependencies: deps = str( sorted( - list( - set([dep.unique for dep in self.get_jobs_we_wait_for()]) - ) + list({dep.unique for dep in self.get_jobs_we_wait_for()}) ) ) if dependencies < len(deps): @@ -507,9 +512,10 @@ def add_job( exec_dir=None, log_dir=None, stop_on_failure=False, - **kwargs + **kwargs, ): - """Helper function to create a job, add the dependencies and the array jobs.""" + """Helper function to create a job, add the dependencies and the array + jobs.""" job = Job( command_line=command_line, name=name, @@ -551,15 +557,16 @@ def add_job( def times(job): - """Returns a string containing timing information for teh given job, which might be a :py:class:`Job` or an :py:class:`ArrayJob`.""" + """Returns a string containing timing information for teh given job, which + might be a :py:class:`Job` or an :py:class:`ArrayJob`.""" timing = "Submitted: %s" % job.submit_time.ctime() if job.start_time is not None: - timing += "\nStarted : %s \t Job waited : %s" % ( + timing += "\nStarted : {} \t Job waited : {}".format( job.start_time.ctime(), job.start_time - job.submit_time, ) if job.finish_time is not None: - timing += "\nFinished : %s \t Job executed: %s" % ( + timing += "\nFinished : {} \t Job executed: {}".format( job.finish_time.ctime(), job.finish_time - job.start_time, ) diff --git a/src/gridtk/script/__init__.py b/src/gridtk/script/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/gridtk/script/grid.py b/src/gridtk/script/grid.py new file mode 100644 index 0000000000000000000000000000000000000000..88114ec9b8aebbc51cc05a9cd59d4a91ec185874 --- /dev/null +++ b/src/gridtk/script/grid.py @@ -0,0 +1,43 @@ +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +"""Executes a given command within the context of a shell script that has its +enviroment set like Idiap's 'SETSHELL grid' does.""" + +from __future__ import annotations + +import os +import shutil +import sys + + +def main() -> None: + from ..setshell import environ + + # get the name of the script that we actually want to execute + # (as defined in the setup.py) + prog = os.path.basename(sys.argv[0]) + + # get the base environment for searching for the command + env = environ("grid") + + # removes the location from the current program from the list of paths to + # search + install_dir = os.path.realpath(os.path.dirname(sys.argv[0])) + paths = env.get("PATH", os.defpath).split(os.pathsep) + paths = [k for k in paths if os.path.realpath(k) != install_dir] + env["PATH"] = os.pathsep.join(paths) + + # check that this program is avalid on that environment + app = shutil.which(prog, path=env["PATH"]) + + if app is None: + + raise RuntimeError( + f"The CLI {prog} is not available when SETSHELL " + f"grid is executed. Are you at an Idiap computer?" + ) + + # call that specific command on the grid environment + os.execvpe(prog, sys.argv, env) diff --git a/gridtk/script/jman.py b/src/gridtk/script/jman.py similarity index 96% rename from gridtk/script/jman.py rename to src/gridtk/script/jman.py index dd962d297225f5b065e4fb7950eb4ee821c332e6..68177283f8510b5c818faa9d246c391bc2a58fff 100644 --- a/gridtk/script/jman.py +++ b/src/gridtk/script/jman.py @@ -1,10 +1,11 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -from __future__ import print_function -"""A logging Idiap/SGE job manager -""" +"""A logging Idiap/SGE job manager.""" + +from __future__ import annotations __epilog__ = """ For a list of available commands: >>> %(prog)s --help @@ -21,7 +22,8 @@ import sys from .. import local, sge from ..models import Status -from ..tools import logger + +logger = logging.getLogger("gridtk") GPU_QUEUES = ["gpu", "lgpu", "sgpu", "gpum", "vsgpu"] QUEUES = ["all.q", "q1d", "q1w", "q1m", "q1dm", "q1wm"] + GPU_QUEUES @@ -45,13 +47,14 @@ def appropriate_for_gpu(args, kwargs): def setup(args): - """Returns the JobManager and sets up the basic infrastructure""" + """Returns the JobManager and sets up the basic infrastructure.""" kwargs = { "wrapper_script": args.wrapper_script, "debug": args.verbose == 3, "database": args.database, } + if args.local: jm = local.JobManagerLocal(**kwargs) else: @@ -133,7 +136,7 @@ def get_memfree(memory, parallel): def submit(args): - """Submission command""" + """Submission command.""" # set full path to command if args.job[0] == "--": @@ -215,7 +218,11 @@ def resubmit(args): def run_scheduler(args): - """Runs the scheduler on the local machine. To stop it, please use Ctrl-C.""" + """Runs the scheduler on the local machine. + + To stop it, please use Ctrl-C. + """ + if not args.local: raise ValueError( "The execute command can only be used with the '--local' command line option" @@ -234,10 +241,13 @@ def run_scheduler(args): def list(args): """Lists the jobs in the given database.""" + jm = setup(args) + if not args.local: # update the status of jobs from SGE before listing them. jm.communicate(job_ids=get_ids(args.job_ids)) + jm.list( job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, @@ -252,6 +262,7 @@ def list(args): def communicate(args): """Uses qstat to get the status of the requested jobs.""" + if args.local: raise ValueError( "The communicate command can only be used without the '--local' command line option" @@ -262,6 +273,7 @@ def communicate(args): def report(args): """Reports the results of the finished (and unfinished) jobs.""" + jm = setup(args) jm.report( job_ids=get_ids(args.job_ids), @@ -275,6 +287,7 @@ def report(args): def stop(args): """Stops (qdel's) the jobs with the given ids.""" + if args.local: raise ValueError( "Stopping commands locally is not supported (please kill them yourself)" @@ -284,11 +297,17 @@ def stop(args): def delete(args): - """Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped.""" + """Deletes the jobs from the job manager. + + If the jobs are still running in the grid, they are stopped. + """ + jm = setup(args) + # first, stop the jobs if they are running in the grid if not args.local and "executing" in args.status: stop(args) + # then, delete them from the database jm.delete( job_ids=get_ids(args.job_ids), @@ -300,7 +319,8 @@ def delete(args): def run_job(args): - """Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us.""" + """Starts the wrapper script to execute a job, interpreting the JOB_ID and + SGE_TASK_ID keywords that are set by the grid or by us.""" jm = setup(args) job_id = int(os.environ["JOB_ID"]) array_id = ( @@ -313,15 +333,14 @@ def run_job(args): class AliasedSubParsersAction(argparse._SubParsersAction): """Hack taken from https://gist.github.com/471779 to allow aliases in - argparse for python 2.x (this has been implemented on python 3.2) - """ + argparse for python 2.x (this has been implemented on python 3.2)""" class _AliasedPseudoAction(argparse.Action): def __init__(self, name, aliases, help): dest = name if aliases: dest += " (%s)" % ",".join(aliases) - sup = super(AliasedSubParsersAction._AliasedPseudoAction, self) + sup = super() sup.__init__(option_strings=[], dest=dest, help=help) def add_parser(self, name, **kwargs): @@ -331,7 +350,7 @@ class AliasedSubParsersAction(argparse._SubParsersAction): else: aliases = [] - parser = super(AliasedSubParsersAction, self).add_parser(name, **kwargs) + parser = super().add_parser(name, **kwargs) # Make the aliases work. for alias in aliases: @@ -347,10 +366,11 @@ class AliasedSubParsersAction(argparse._SubParsersAction): def main(command_line_options=None): + from importlib.metadata import version - from bob.extension import rc + from ..tools import load_defaults - from ..config import __version__ + defaults = load_defaults() formatter = argparse.ArgumentDefaultsHelpFormatter parser = argparse.ArgumentParser( @@ -371,7 +391,7 @@ def main(command_line_options=None): "-V", "--version", action="version", - version="GridTk version %s" % __version__, + version="gridtk version %s" % version(__name__.split(".", 1)[0]), ) parser.add_argument( "-d", @@ -397,7 +417,7 @@ def main(command_line_options=None): "submit", aliases=["sub"], formatter_class=formatter, - help="Submits jobs to the SGE queue or to the local job scheduler and logs them in a database.", + help="Submits jobs to the SGE/Local job scheduler and logs them in a database.", ) submit_parser.add_argument( "-q", @@ -411,7 +431,7 @@ def main(command_line_options=None): submit_parser.add_argument( "-e", "--sge-extra-args", - default=rc.get("gridtk.sge.extra.args.default", ""), + default=defaults.get("sge-extra-args-default", ""), type=str, help="Passes extra arguments to qsub. See the documentation of the package for usage and ways of overriding default behavior.", ) diff --git a/gridtk/setshell.py b/src/gridtk/setshell.py similarity index 82% rename from gridtk/setshell.py rename to src/gridtk/setshell.py index 11cfe7210a933efdcad13e89c3636cc08afd8810..97146d092dae2e7b43e7f569bdc169f4b294695f 100644 --- a/gridtk/setshell.py +++ b/src/gridtk/setshell.py @@ -1,21 +1,25 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : -# Andre Anjos <andre.anjos@idiap.ch> -# Wed 24 Aug 2011 09:20:40 CEST +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -"""Wrappers for Idiap's SETSHELL functionality -""" +"""Wrappers for Idiap's SETSHELL functionality.""" +from __future__ import annotations + +import logging import os import signal import subprocess import sys -from .tools import logger, str_ +from .tools import str_ + +logger = logging.getLogger(__name__) -def environ(context): - """Retrieves the environment for a particular SETSHELL context""" +def environ(context: str) -> dict[str, str]: + """Retrieves the environment for a particular SETSHELL context.""" + if "BASEDIRSETSHELL" not in os.environ: # It seems that we are in a hostile environment # try to source the Idiap-wide shell @@ -27,16 +31,15 @@ def environ(context): pi = subprocess.Popen(command, stdout=subprocess.PIPE) # overwrite the default environment for line in pi.stdout: - line = str_(line) - (key, _, value) = line.partition("=") + sline = str_(line) + (key, _, value) = sline.partition("=") os.environ[key.strip()] = value.strip() except OSError: # occurs when the file is not executable or not found pass - # in case the BASEDIRSETSHELL environment variable is not set, - # we are not at Idiap, - # and so we don't have to set any additional variables. + # in case the BASEDIRSETSHELL environment variable is not set, we are not + # at Idiap, and so we don't have to set any additional variables. if "BASEDIRSETSHELL" not in os.environ: return dict(os.environ) @@ -77,8 +80,8 @@ def environ(context): new_environ = dict(os.environ) for line in p2.stdout: - line = str_(line) - (key, _, value) = line.partition("=") + sline = str_(line) + (key, _, value) = sline.partition("=") new_environ[key.strip()] = value.strip() try: @@ -97,12 +100,12 @@ def environ(context): return new_environ -def sexec(context, command, error_on_nonzero=True): - """Executes a command within a particular Idiap SETSHELL context""" - - import six +def sexec( + context: str, command: list[str], error_on_nonzero: bool = True +) -> bytes: + """Executes a command within a particular Idiap SETSHELL context.""" - if isinstance(context, six.string_types): + if isinstance(context, (str, bytes)): E = environ(context) else: E = context @@ -112,7 +115,7 @@ def sexec(context, command, error_on_nonzero=True): p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=E ) - (stdout, stderr) = p.communicate() # note: stderr will be 'None' + (stdout, _) = p.communicate() # note: stderr will be 'None' if p.returncode != 0: if error_on_nonzero: raise RuntimeError( diff --git a/gridtk/sge.py b/src/gridtk/sge.py similarity index 92% rename from gridtk/sge.py rename to src/gridtk/sge.py index f56480dc93d099fa1cb53f30c1e2023888818e2f..f3c5c264fbc1e93336627bc8c49f1a3c26993e81 100644 --- a/gridtk/sge.py +++ b/src/gridtk/sge.py @@ -1,13 +1,12 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : -# Andre Anjos <andre.anjos@idiap.ch> -# Wed 24 Aug 2011 13:06:25 CEST +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -"""Defines the job manager which can help you managing submitted grid jobs. -""" +"""Defines the job manager which can help you managing submitted grid jobs.""" -from __future__ import print_function +from __future__ import annotations +import logging import os import re import sys @@ -15,14 +14,17 @@ import sys from .manager import JobManager from .models import Job, add_job from .setshell import environ -from .tools import logger, make_shell, makedirs_safe, qdel, qstat, qsub +from .tools import make_shell, qdel, qstat, qsub + +logger = logging.getLogger(__name__) class JobManagerSGE(JobManager): - """The JobManager will submit and control the status of submitted jobs""" + """The JobManager will submit and control the status of submitted jobs.""" def __init__(self, context="grid", **kwargs): - """Initializes this object with a state file and a method for qsub'bing. + """Initializes this object with a state file and a method for + qsub'bing. Keyword parameters: @@ -40,9 +42,11 @@ class JobManagerSGE(JobManager): JobManager.__init__(self, **kwargs) def _queue(self, kwargs): - """The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. To - process it we have to split it twice (',' and then on '='), create a - dictionary and extract just the qname""" + """The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. + + To process it we have to split it twice (',' and then on '='), + create a dictionary and extract just the qname + """ if "hard resource_list" not in kwargs: return "all.q" d = dict( @@ -63,10 +67,10 @@ class JobManagerSGE(JobManager): # get the grid id's for the dependencies and remove duplicates dependent_jobs = self.get_jobs(dependencies) - deps = sorted(list(set([j.id for j in dependent_jobs]))) + deps = sorted(list({j.id for j in dependent_jobs})) # make sure log directory is created and is a directory - makedirs_safe(job.log_dir) + os.makedirs(job.log_dir, exist_ok=True) assert os.path.isdir( job.log_dir ), "Please make sure --log-dir `{}' either does not exist or is a directory.".format( @@ -87,7 +91,7 @@ class JobManagerSGE(JobManager): array=q_array, stdout=log_dir, stderr=log_dir, - **kwargs + **kwargs, ) # get the result of qstat @@ -149,7 +153,7 @@ class JobManagerSGE(JobManager): dry_run=False, verbosity=0, stop_on_failure=False, - **kwargs + **kwargs, ): """Submits a job that will be executed in the grid.""" # add job to database @@ -164,7 +168,7 @@ class JobManagerSGE(JobManager): log_dir=log_dir, stop_on_failure=stop_on_failure, context=self.context, - **kwargs + **kwargs, ) logger.info("Added job '%s' to the database." % job) if dry_run: @@ -191,7 +195,8 @@ class JobManagerSGE(JobManager): return job_id def communicate(self, job_ids=None): - """Communicates with the SGE grid (using qstat) to see if jobs are still running.""" + """Communicates with the SGE grid (using qstat) to see if jobs are + still running.""" self.lock() # iterate over all jobs jobs = self.get_jobs(job_ids) @@ -225,9 +230,9 @@ class JobManagerSGE(JobManager): new_command=None, verbosity=0, keep_logs=False, - **kwargs + **kwargs, ): - """Re-submit jobs automatically""" + """Re-submit jobs automatically.""" self.lock() # iterate over all jobs jobs = self.get_jobs(job_ids) @@ -286,7 +291,7 @@ class JobManagerSGE(JobManager): deps, job.log_dir, verbosity, - **arguments + **arguments, ) # commit after each job to avoid failures of not finding the job during execution in the grid @@ -294,7 +299,8 @@ class JobManagerSGE(JobManager): self.unlock() def run_job(self, job_id, array_id=None): - """Overwrites the run-job command from the manager to extract the correct job id before calling base class implementation.""" + """Overwrites the run-job command from the manager to extract the + correct job id before calling base class implementation.""" # get the unique job id from the given grid id self.lock() jobs = list(self.session.query(Job).filter(Job.id == job_id)) diff --git a/gridtk/tools.py b/src/gridtk/tools.py similarity index 77% rename from gridtk/tools.py rename to src/gridtk/tools.py index 906c96192af3ddacce800c39eb8473a4c45bd869..792a6491a00d1b8e2d35734495e2c94999cf5264 100644 --- a/gridtk/tools.py +++ b/src/gridtk/tools.py @@ -1,40 +1,61 @@ -#!/usr/bin/env python -# vim: set fileencoding=utf-8 : -# Andre Anjos <andre.anjos@idiap.ch> -# Wed 24 Aug 2011 09:26:46 CEST +# Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later -"""Functions that replace the shell based utilities for the grid submission and -probing. -""" +"""Functions that replace shell-based utilities for grid submission and +probing.""" + +from __future__ import annotations -# initialize the logging system import logging import math import os +import pathlib import re import shlex -logger = logging.getLogger("gridtk") +import exposed.rc + +logger = logging.getLogger(__name__) # Constant regular expressions QSTAT_FIELD_SEPARATOR = re.compile(":\\s+") -def makedirs_safe(fulldir): - """Creates a directory if it does not exists. Takes into consideration - concurrent access support. Works like the shell's 'mkdir -p'. - """ - os.makedirs(fulldir, exist_ok=True) +def load_defaults() -> exposed.rc.UserDefaults: + """Loads user defaults from the stock location.""" + from exposed import rc -def str_(name): - """Return the string representation of the given 'name'. - If it is a bytes object, it will be converted into str. - If it is a str object, it will simply be resurned.""" - if isinstance(name, bytes) and not isinstance(name, str): - return name.decode("utf8") + config_dir = os.environ.get("XDG_CONFIG_HOME") + + if config_dir is None: + config_path = pathlib.Path.home() / ".config" else: - return name + config_path = pathlib.Path(config_dir) + + return rc.UserDefaults(config_path / "gridtk.toml") + + +def str_(v: str | bytes) -> str: + """Always returns the string representation of the given ``name``. + + If it is a bytes object, it will be converted into str. + + If it is a str object, it will simply be resurned. + + + Parameters: + + v: a bytes or str object + + + Returns: + + A str object + """ + + return v if not isinstance(v, bytes) else v.decode() def qsub( @@ -56,7 +77,7 @@ def qsub( io_big=False, sge_extra_args="", ): - """Submits a shell job to a given grid queue + """Submits a shell job to a given grid queue. Keyword parameters: @@ -148,17 +169,16 @@ def qsub( Returns the job id assigned to this job (integer) """ - import six - - from bob.extension import rc scmd = ["qsub"] - prepend = rc.get("gridtk.sge.extra.args.prepend") or "" + defaults = load_defaults() + + prepend = defaults.get("sge-extra-args-prepend", "") sge_extra_args = f"{prepend} {sge_extra_args or ''}" scmd += shlex.split(sge_extra_args) - if isinstance(queue, six.string_types) and queue not in ( + if isinstance(queue, (str, bytes)) and queue not in ( "all.q", "default", ): @@ -198,7 +218,7 @@ def qsub( os.chdir(os.environ["HOME"]) if not os.path.exists(stdout): - makedirs_safe(stdout) + os.makedirs(stdout, exist_ok=True) if not cwd: # go back @@ -207,8 +227,7 @@ def qsub( scmd += ["-o", stdout] if stderr: - if not os.path.exists(stderr): - makedirs_safe(stderr) + os.makedirs(stderr, exist_ok=True) scmd += ["-e", stderr] elif stdout: # just re-use the stdout settings scmd += ["-e", stdout] @@ -222,14 +241,14 @@ def qsub( if array is not None: scmd.append("-t") - if isinstance(array, six.string_types): + if isinstance(array, (str, bytes)): try: i = int(array) scmd.append("1-%d:1" % i) except ValueError: # must be complete... scmd.append("%s" % array) - if isinstance(array, six.integer_types): + if isinstance(array, (str, bytes)): scmd.append("1-%d:1" % array) if isinstance(array, (tuple, list)): if len(array) < 1 or len(array) > 3: @@ -239,9 +258,9 @@ def qsub( elif len(array) == 1: scmd.append("%s" % array[0]) elif len(array) == 2: - scmd.append("%s-%s" % (array[0], array[1])) + scmd.append(f"{array[0]}-{array[1]}") elif len(array) == 3: - scmd.append("%s-%s:%s" % (array[0], array[1], array[2])) + scmd.append(f"{array[0]}-{array[1]}:{array[2]}") if not isinstance(command, (list, tuple)): command = [command] @@ -256,7 +275,7 @@ def qsub( def make_shell(shell, command): - """Returns a single command given a shell and a command to be qsub'ed + """Returns a single command given a shell and a command to be qsub'ed. Keyword parameters: @@ -312,55 +331,61 @@ def qstat(jobid, context="grid"): return retval -def qdel(jobid, context="grid"): +def qdel(jobid: int, context: str = "grid") -> None: """Halts a given job. - Keyword parameters: + Parameters: - jobid - The job identifier as returned by qsub() + jobid: The job identifier as returned by :py:func:`qsub` - context - The setshell context in which we should try a 'qsub'. Normally you don't - need to change the default. This variable can also be set to a context - dictionary in which case we just setup using that context instead of - probing for a new one, what can be fast. + context: The setshell context in which we should try a 'qsub'. Normally + you do not need to change the default. This variable can also be + set to a context dictionary in which case we just setup using that + context instead of probing for a new one, what can be fast. """ - scmd = ["qdel", "%d" % jobid] + scmd = ["qdel", f"{jobid}"] - logger.debug("Qdel command '%s'", " ".join(scmd)) + logger.debug(f"qdel command '{' '.join(scmd)}'") from .setshell import sexec sexec(context, scmd, error_on_nonzero=False) -def get_array_job_slice(total_length): +def get_array_job_slice(total_length: int) -> slice: """A helper function that let's you chunk a list in an SGE array job. - Use this function like ``a = a[get_array_job_slice(len(a))]`` to only process a chunk - of ``a``. - Parameters - ---------- - total_length : int - The length of the list that you are trying to slice + Use this function like ``a = a[get_array_job_slice(len(a))]`` to only + process a chunk of ``a``. + + + Parameters: + + total_length: The length of the list that you are trying to slice + + + Returns: - Returns - ------- - slice A slice to be used. - Raises - ------ - NotImplementedError - If "SGE_TASK_FIRST" and "SGE_TASK_STEPSIZE" are not 1. + + Raises: + + NotImplementedError: If "SGE_TASK_FIRST" and "SGE_TASK_STEPSIZE" are + not 1. """ + sge_task_id = os.environ.get("SGE_TASK_ID") + + if sge_task_id is None: + return slice(None) + try: - sge_task_id = int(sge_task_id) + sge_task_int = int(sge_task_id) except Exception: return slice(None) + if ( os.environ["SGE_TASK_FIRST"] != "1" or os.environ["SGE_TASK_STEPSIZE"] != "1" @@ -368,11 +393,15 @@ def get_array_job_slice(total_length): raise NotImplementedError( "Values other than 1 for SGE_TASK_FIRST and SGE_TASK_STEPSIZE is not supported!" ) - job_id = sge_task_id - 1 + + job_id = sge_task_int - 1 + number_of_parallel_jobs = int(os.environ["SGE_TASK_LAST"]) number_of_objects_per_job = int( math.ceil(total_length / number_of_parallel_jobs) ) + start = min(job_id * number_of_objects_per_job, total_length) end = min((job_id + 1) * number_of_objects_per_job, total_length) + return slice(start, end) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bd71e3a56f4a54b8a311a2033922e7ad051c87 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +import pathlib + +import pytest + + +@pytest.fixture +def datadir(request) -> pathlib.Path: + """Returns the directory in which the test is sitting.""" + + return pathlib.Path(request.fspath).parent / "data" diff --git a/tests/data/test_array.sh b/tests/data/test_array.sh new file mode 100644 index 0000000000000000000000000000000000000000..621525bd2fedd4a95bcdf3ba0eff37f53a32b935 --- /dev/null +++ b/tests/data/test_array.sh @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +echo "The job id is '$JOB_ID' and the task id is '$SGE_TASK_ID'" + +if [[ $SGE_TASK_ID == '1' ]]; then + exit 1 +else + exit 0 +fi diff --git a/gridtk/tests/test_script.sh b/tests/data/test_script.sh similarity index 60% rename from gridtk/tests/test_script.sh rename to tests/data/test_script.sh index 7d5bf02447310a1bce2c322750d21538bce42058..61ea8a9a397d5c9bc4a6e907d182a1a823ddb261 100644 --- a/gridtk/tests/test_script.sh +++ b/tests/data/test_script.sh @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + # We simply write one line to stdout and one line to stderr echo "This is a text message to std-out" echo "This is a text message to std-err" >&2 diff --git a/tests/test_local.py b/tests/test_local.py new file mode 100644 index 0000000000000000000000000000000000000000..6f779c0e77e57eee13483c3ad5b07d801c5556ef --- /dev/null +++ b/tests/test_local.py @@ -0,0 +1,559 @@ +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + +import os +import pathlib +import shutil +import subprocess +import time + +import gridtk.local + +from gridtk.models import Job +from gridtk.script import jman + + +def test_local(tmp_path: pathlib.Path, datadir: pathlib.Path): + # This test executes all commands of the local grid manager and asserts that everything is fine + + # first test, if the '/bin/bash' exists + bash = "/bin/bash" + assert os.path.exists(bash) + + jman_exec = shutil.which("jman") + assert jman_exec + + scheduler_job = None + + try: + + # first, add some commands to the database + script_1 = str(datadir / "test_script.sh") + script_2 = str(datadir / "test_array.sh") + rdir = str(datadir) + + # add a simple script that will write some information to the console + jman.main( + [ + shutil.which("jman"), + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_1", + bash, + script_1, + ] + ) + jman.main( + [ + shutil.which("jman"), + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_2", + "--dependencies", + "1", + "--parametric", + "1-7:2", + bash, + script_2, + ] + ) + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_3", + "--dependencies", + "1", + "2", + "--exec-dir", + rdir, + bash, + "test_array.sh", + ] + ) + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_1", + "--repeat", + "2", + bash, + script_1, + ] + ) + + # check that the database was created successfully + assert os.path.exists(str(tmp_path / "database.sql3")) + + # test that the list command works (should also work with the "default" + # grid manager) + jman.main( + [ + jman_exec, + "--database", + str(tmp_path / "database.sql3"), + "list", + "--job-ids", + "1", + ] + ) + jman.main( + [ + jman_exec, + "--database", + str(tmp_path / "database.sql3"), + "list", + "--job-ids", + "2", + "--print-array-jobs", + "--print-dependencies", + "--print-times", + ] + ) + jman.main( + [ + jman_exec, + "--database", + str(tmp_path / "database.sql3"), + "list", + "--job-ids", + "4-5", + "--print-array-jobs", + "--print-dependencies", + "--print-times", + ] + ) + + # get insight into the database + job_manager = gridtk.local.JobManagerLocal( + database=str(tmp_path / "database.sql3") + ) + session = job_manager.lock() + jobs = list(session.query(Job)) + assert len(jobs) == 5 + assert jobs[0].id == 1 + assert jobs[1].id == 2 + assert jobs[2].id == 3 + assert jobs[3].id == 4 + assert jobs[4].id == 5 + assert len(jobs[1].array) == 4 + assert jobs[0].status == "submitted" + assert jobs[1].status == "submitted" + assert jobs[2].status == "submitted" + assert jobs[3].status == "submitted" + assert jobs[4].status == "submitted" + assert all(j.submit_time is not None for j in jobs) + assert all(j.start_time is None for j in jobs) + assert all(j.finish_time is None for j in jobs) + assert all(j.submit_time is not None for j in jobs[1].array) + assert all(j.start_time is None for j in jobs[1].array) + assert all(j.finish_time is None for j in jobs[1].array) + + # check that the job dependencies are correct + waiting = jobs[0].get_jobs_waiting_for_us() + assert len(waiting) == 2 + assert waiting[0].id == 2 + assert waiting[1].id == 3 + waited = jobs[2].get_jobs_we_wait_for() + assert len(waited) == 2 + assert waited[0].id == 1 + assert waited[1].id == 2 + + # check dependencies for --repeat + waiting = jobs[3].get_jobs_waiting_for_us() + assert len(waiting) == 1 + assert waiting[0].id == 5 + waited = jobs[4].get_jobs_we_wait_for() + assert len(waited) == 1 + assert waited[0].id == 4 + + job_manager.unlock() + + # now, start the local execution of the job in a parallel job + scheduler_job = subprocess.Popen( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "run-scheduler", + "--sleep-time", + "5", + "--parallel", + "2", + ] + ) + + # sleep some time to assure that the scheduler was able to start the first job + time.sleep(5) + # ... and kill the scheduler + scheduler_job.kill() + scheduler_job = None + + # now, the first job needs to have status failure, and the second needs + # to be queued + session = job_manager.lock() + jobs = list(session.query(Job)) + assert len(jobs) == 5 + if jobs[0].status in ("submitted", "queued", "executing"): + # on slow machines, we don0t want the tests to fail, so we just skip + job_manager.unlock() + raise RuntimeError( + "This machine seems to be quite slow in processing parallel jobs." + ) + assert jobs[0].status == "failure" + assert jobs[1].status == "queued" + assert jobs[2].status == "waiting" + assert jobs[0].start_time is not None + assert jobs[0].finish_time is not None + assert jobs[1].start_time is None + assert jobs[1].finish_time is None + assert jobs[2].start_time is None + assert jobs[2].finish_time is None + + # the result files should already be there + assert os.path.exists(jobs[0].std_out_file()) + assert os.path.exists(jobs[0].std_err_file()) + job_manager.unlock() + + # reset the job 1 + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "resubmit", + "--job-id", + "1", + "--running-jobs", + "--overwrite-command", + bash, + script_1, + ] + ) + + # now, start the local execution of the job in a parallel job + scheduler_job = subprocess.Popen( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "run-scheduler", + "--sleep-time", + "5", + "--parallel", + "2", + ] + ) + + # sleep some time to assure that the scheduler was able to finish the first and start the second job + time.sleep(10) + # ... and kill the scheduler + scheduler_job.kill() + scheduler_job = None + + # Job 1 and two array jobs of job two should be finished now, the other two still need to be queued + session = job_manager.lock() + jobs = list(session.query(Job)) + assert len(jobs) == 5 + if ( + jobs[0].status in ("queued", "executing") + or jobs[1].status == "queued" + ): + # on slow machines, we don0t want the tests to fail, so we just skip + job_manager.unlock() + raise RuntimeError( + "This machine seems to be quite slow in processing parallel jobs." + ) + assert jobs[0].status == "failure" + assert jobs[1].status == "executing" + if ( + jobs[1].array[0].status == "executing" + or jobs[1].array[1].status == "executing" + ): + # on slow machines, we don0t want the tests to fail, so we just skip + job_manager.unlock() + raise RuntimeError( + "This machine seems to be quite slow in processing parallel jobs." + ) + assert jobs[1].array[0].status == "failure" + assert jobs[1].array[0].result == 1 + assert jobs[1].array[1].status == "success" + assert jobs[1].array[1].result == 0 + assert len([a for a in jobs[1].array if a.status == "queued"]) == 2 + out_file = jobs[0].std_out_file() + err_file = jobs[0].std_err_file() + job_manager.unlock() + + # the result files of the first job should now be there + assert os.path.isfile(out_file) + assert os.path.isfile(err_file) + assert ( + open(out_file).read().rstrip() + == "This is a text message to std-out" + ) + assert "This is a text message to std-err" in open( + err_file + ).read().split("\n") + + # resubmit all jobs + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "resubmit", + "--running-jobs", + ] + ) + # check that the log files have been cleaned + assert not os.path.exists(out_file) + assert not os.path.exists(err_file) + + # ... but the log dir still exists + assert os.path.exists(str(tmp_path / "logs")) + + # now, let the scheduler run all jobs, but this time in verbose mode + scheduler_job = subprocess.Popen( + [ + jman_exec, + "--local", + "-vv", + "--database", + str(tmp_path / "database.sql3"), + "run-scheduler", + "--sleep-time", + "1", + "--parallel", + "2", + "--die-when-finished", + ] + ) + # and wait for the job to finish (the timeout argument to Popen only exists from python 3.3 onwards) + scheduler_job.wait() + scheduler_job = None + + # check that all output files are generated again + assert os.path.isfile(out_file) + assert os.path.isfile(err_file) + assert ( + open(out_file).read().rstrip() + == "This is a text message to std-out" + ) + assert "This is a text message to std-err" in open( + err_file + ).read().split("\n") + + # check that exactly four output and four error files have been created + files = os.listdir(str(tmp_path / "logs")) + assert len(files) == 16 + for i in range(1, 8, 2): + assert "test_2.o2.%d" % i in files + assert "test_2.e2.%d" % i in files + + # check that all array jobs are finished now + session = job_manager.lock() + jobs = list(session.query(Job)) + assert len(jobs) == 5 + assert jobs[1].status == "failure" + assert jobs[1].array[0].status == "failure" + assert jobs[1].array[0].result == 1 + for i in range(1, 4): + assert jobs[1].array[i].status == "success" + assert jobs[1].array[i].result == 0 + assert jobs[2].status == "success" + assert jobs[2].result == 0 + + assert all(j.submit_time is not None for j in jobs) + assert all(j.start_time is not None for j in jobs) + assert all(j.finish_time is not None for j in jobs) + assert all(j.submit_time is not None for j in jobs[1].array) + assert all(j.start_time is not None for j in jobs[1].array) + assert all(j.finish_time is not None for j in jobs[1].array) + + job_manager.unlock() + + # test that the list command still works + jman.main( + [ + jman_exec, + "--database", + str(tmp_path / "database.sql3"), + "list", + "--print-array-jobs", + ] + ) + jman.main( + [ + jman_exec, + "--database", + str(tmp_path / "database.sql3"), + "list", + "--long", + "--print-array-jobs", + ] + ) + + # test that the report command works + jman.main( + [jman_exec, "--database", str(tmp_path / "database.sql3"), "report"] + ) + + # clean-up + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "delete", + "--job-ids", + "1+4", + ] + ) + + # check that the database and the log files are gone + assert len(os.listdir(tmp_path)) == 0 + + # add the scripts again, but this time with the --stop-on-failure option + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_1", + "--stop-on-failure", + bash, + script_1, + ] + ) + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_2", + "--dependencies", + "1", + "--parametric", + "1-7:2", + "--stop-on-failure", + bash, + script_2, + ] + ) + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "submit", + "--log-dir", + str(tmp_path / "logs"), + "--name", + "test_3", + "--dependencies", + "1", + "2", + "--exec-dir", + rdir, + "--stop-on-failure", + bash, + "test_array.sh", + ] + ) + + # and execute them, but without writing the log files + scheduler_job = subprocess.Popen( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "run-scheduler", + "--sleep-time", + "0.1", + "--parallel", + "2", + "--die-when-finished", + "--no-log-files", + ] + ) + # and wait for the job to finish (the timeout argument to Popen only exists from python 3.3 onwards) + scheduler_job.wait() + scheduler_job = None + + # assert that the log files are not there + assert not os.path.isfile(out_file) + assert not os.path.isfile(err_file) + + # check that all array jobs are finished now + session = job_manager.lock() + jobs = list(session.query(Job)) + assert len(jobs) == 3 + assert jobs[0].status == "failure" + assert jobs[0].result == 255 + assert jobs[1].status == "failure" + assert jobs[1].result is None + assert jobs[2].status == "failure" + assert jobs[2].result is None + job_manager.unlock() + + # and clean up again + jman.main( + [ + jman_exec, + "--local", + "--database", + str(tmp_path / "database.sql3"), + "delete", + ] + ) + assert len(os.listdir(tmp_path)) == 0 + + except KeyboardInterrupt: + # make sure that the keyboard interrupt is captured and the mess is cleaned up (i.e. by calling tearDown) + pass + + finally: + + if scheduler_job is not None: + scheduler_job.kill() diff --git a/gridtk/tests/test_tools.py b/tests/test_tools.py similarity index 90% rename from gridtk/tests/test_tools.py rename to tests/test_tools.py index 743bea6607f615757f3c5081bb9da4cb6832aa13..ee1c83dc11ee3e8afb4e4465e339288cf1970bb5 100644 --- a/gridtk/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,6 +1,10 @@ +# SPDX-FileCopyrightText: Copyright © 2022 Idiap Research Institute <contact@idiap.ch> +# +# SPDX-License-Identifier: GPL-3.0-or-later + import os -from ..tools import get_array_job_slice +from gridtk.tools import get_array_job_slice class SGE_EnvWrapper: @@ -49,6 +53,7 @@ class SGE_EnvWrapper: def test_get_array_job_slice(): with SGE_EnvWrapper() as wrapper: + s = get_array_job_slice(10) assert s == slice(0, 10) diff --git a/version.txt b/version.txt deleted file mode 100644 index 83e09d5d13cef4a6e5e9b325770bd2543fb471b5..0000000000000000000000000000000000000000 --- a/version.txt +++ /dev/null @@ -1 +0,0 @@ -1.8.5b0