diff --git a/.gitignore b/.gitignore deleted file mode 100644 index be9dfa5..0000000 --- a/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -*.pyc -*.sw? -*~ -.coverage -.eggs/ -__pycache__ -*.egg-info/ -build/ -dist/ -version.txt -/.hypothesis/ -/.tox/ diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 2d0a34a..0000000 --- a/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -Copyright (C) 2015 The Software Heritage developers - -See http://www.softwareheritage.org/ for more information. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 94a9ed0..0000000 --- a/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU 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. - - - Copyright (C) - - 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 . - -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: - - Copyright (C) - 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 -. - - 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 -. diff --git a/LICENSE.Celery b/LICENSE.Celery deleted file mode 100644 index 06221a2..0000000 --- a/LICENSE.Celery +++ /dev/null @@ -1,54 +0,0 @@ -Copyright (c) 2015-2016 Ask Solem & contributors. All rights reserved. -Copyright (c) 2012-2014 GoPivotal, Inc. All rights reserved. -Copyright (c) 2009, 2010, 2011, 2012 Ask Solem, and individual contributors. All rights reserved. - -Celery is licensed under The BSD License (3 Clause, also known as -the new BSD license). The license is an OSI approved Open Source -license and is GPL-compatible(1). - -The license text can also be found here: -http://www.opensource.org/licenses/BSD-3-Clause - -License -======= - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of Ask Solem, nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -Documentation License -===================== - -The documentation portion of Celery (the rendered contents of the -"docs" directory of a software distribution or checkout) is supplied -under the "Creative Commons Attribution-ShareAlike 4.0 -International" (CC BY-SA 4.0) License as described by -http://creativecommons.org/licenses/by-sa/4.0/ - -Footnotes -========= -(1) A GPL-compatible license makes it possible to - combine Celery with other software that is released - under the GPL, it does not mean that we're distributing - Celery under the GPL license. The BSD license, unlike the GPL, - let you distribute a modified version without making your - changes open source. diff --git a/PKG-INFO b/PKG-INFO index 92333fc..ffc6c79 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,65 +1,65 @@ Metadata-Version: 2.1 Name: swh.scheduler -Version: 0.0.35 +Version: 0.0.38 Summary: Software Heritage Scheduler Home-page: https://forge.softwareheritage.org/diffusion/DSCH/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN -Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest -Project-URL: Funding, https://www.softwareheritage.org/donate Project-URL: Source, https://forge.softwareheritage.org/source/swh-scheduler +Project-URL: Funding, https://www.softwareheritage.org/donate +Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Description: swh-scheduler ============= Job scheduler for the Software Heritage project. Task manager for asynchronous/delayed tasks, used for both recurrent (e.g., listing a forge, loading new stuff from a Git repository) and one-off activities (e.g., loading a specific version of a source package). # Tests ## Running test manually ### Test data To be able to run (unit) tests, you need to have the [[https://forge.softwareheritage.org/source/swh-storage-testdata.git|swh-storage-testdata]] in the parent directory. If you have set your environment following the [[ https://docs.softwareheritage.org/devel/getting-started.html#getting-started|Getting started]] - document everythong should be set up just fine. + document everything should be set up just fine. Otherwise: ``` ~/.../swh-scheduler$ git clone https://forge.softwareheritage.org/source/swh-storage-testdata.git ../swh-storage-testdata ``` ### Required services Unit tests that require a running celery broker uses an in memory broker/result backend by default, but you can choose to use a true broker by setting `CELERY_BROKER_URL` and `CELERY_RESULT_BACKEND` environment variables up. For example: ``` $ CELERY_BROKER_URL=amqp://localhost pifpaf run postgresql nosetests ..................................... ---------------------------------------------------------------------- Ran 37 tests in 15.578s OK ``` Platform: UNKNOWN Classifier: Programming Language :: Python :: 3 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Development Status :: 5 - Production/Stable Description-Content-Type: text/markdown Provides-Extra: testing diff --git a/README.md b/README.md index 01a2c41..c00f45f 100644 --- a/README.md +++ b/README.md @@ -1,45 +1,45 @@ swh-scheduler ============= Job scheduler for the Software Heritage project. Task manager for asynchronous/delayed tasks, used for both recurrent (e.g., listing a forge, loading new stuff from a Git repository) and one-off activities (e.g., loading a specific version of a source package). # Tests ## Running test manually ### Test data To be able to run (unit) tests, you need to have the [[https://forge.softwareheritage.org/source/swh-storage-testdata.git|swh-storage-testdata]] in the parent directory. If you have set your environment following the [[ https://docs.softwareheritage.org/devel/getting-started.html#getting-started|Getting started]] -document everythong should be set up just fine. +document everything should be set up just fine. Otherwise: ``` ~/.../swh-scheduler$ git clone https://forge.softwareheritage.org/source/swh-storage-testdata.git ../swh-storage-testdata ``` ### Required services Unit tests that require a running celery broker uses an in memory broker/result backend by default, but you can choose to use a true broker by setting `CELERY_BROKER_URL` and `CELERY_RESULT_BACKEND` environment variables up. For example: ``` $ CELERY_BROKER_URL=amqp://localhost pifpaf run postgresql nosetests ..................................... ---------------------------------------------------------------------- Ran 37 tests in 15.578s OK ``` diff --git a/data/README.md b/data/README.md deleted file mode 100644 index 762c332..0000000 --- a/data/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Install/Update template - -Install the `task` template in elasticsearch: - -``` shell -INSTANCE=http://something:9200 -TEMPLATE_NAME=template_swh_tasks -curl -i -H'Content-Type: application/json' -d@./elastic-template.json -XPUT ${INSTANCE}/_template/${TEMPLATE_NAME} -``` - -# Update index settings - -The index setup is fixed and defined on the template settings basis. - -When that setup needs to change, we need to update both the template -and the existing indices. - -To update index settings: - -``` shell -INDEX_NAME=swh-tasks-2017-11 -curl -i -H'Content-Type: application/json' -d@./update-index-settings.json -XPUT ${INSTANCE}/${INDEX_NAME}/_settings -``` diff --git a/data/elastic-template.json b/data/elastic-template.json deleted file mode 100644 index 3d9e75f..0000000 --- a/data/elastic-template.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "order": 0, - "index_patterns": ["swh-tasks-*"], - "settings": { - "index": { - "codec": "best_compression", - "refresh_interval": "30s", - "number_of_shards": 1 - } - }, - "mappings" : { - "task" : { - "_source" : { "enabled": true}, - "properties": { - "task_id": {"type": "double"}, - "task_policy": {"type": "text"}, - "task_status": {"type": "text"}, - "task_run_id": {"type": "double"}, - "arguments": { - "type": "object", - "properties" : { - "args": { - "type": "nested", - "dynamic": false - }, - "kwargs": { - "type": "text" - } - } - }, - "type": {"type": "text"}, - "backend_id": {"type": "text"}, - "metadata": { - "type": "object", - "enabled" : false - }, - "scheduled": { - "type": "date", - "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||strict_date_optional_time||epoch_millis" - }, - "started": { - "type": "date", - "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||strict_date_optional_time||epoch_millis" - }, - "ended": { - "type": "date", - "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||strict_date_optional_time||epoch_millis" - } - } - } - }, - "aliases": {} -} diff --git a/data/update-index-settings.json b/data/update-index-settings.json deleted file mode 100644 index ce3deab..0000000 --- a/data/update-index-settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "index": { - "refresh_interval": "1s" - } -} diff --git a/debian/changelog b/debian/changelog index 4096123..951f5b7 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,298 +1,300 @@ -swh-scheduler (0.0.35-1~swh1~bpo9+1) stretch-swh; urgency=medium +swh-scheduler (0.0.38-1~swh1) unstable-swh; urgency=medium - * Rebuild for stretch-backports. + * New upstream release 0.0.38 - (tagged by David Douard + on 2018-12-20 14:39:59 +0100) + * Upstream changes: - v0.0.38 - -- Antoine R. Dumont (@ardumont) Mon, 29 Oct 2018 10:07:09 +0100 + -- Software Heritage autobuilder (on jenkins-debian1) Wed, 09 Jan 2019 18:32:14 +0000 swh-scheduler (0.0.35-1~swh1) unstable-swh; urgency=medium * v0.0.35 * tests: Add SchedulerTestFixture * swh.scheduler.utils: Allow to add more task information * sql/40-swh-data: Update new indexer task types for local db -- Antoine R. Dumont (@ardumont) Mon, 29 Oct 2018 10:07:08 +0100 swh-scheduler (0.0.34-1~swh1) unstable-swh; urgency=medium * v0.0.34 * Finalize pytest migration -- Antoine R. Dumont (@ardumont) Thu, 25 Oct 2018 17:52:03 +0200 swh-scheduler (0.0.33-1~swh1) unstable-swh; urgency=medium * v0.0.33 -- David Douard Thu, 25 Oct 2018 16:03:16 +0200 swh-scheduler (0.0.32-1~swh1) unstable-swh; urgency=medium * v0.0.32 * tests: Add celery fixture to ease tests * tests: make tests use sql/ files from the package * tests: Starting migration towards pytest * listener: Make the listener code compatible with new celery (debian buster) * Make swh_scheduler_create_tasks_from_temp use indexes * setup: prepare for pypi upload * docs: add a simple README file -- Antoine R. Dumont (@ardumont) Mon, 22 Oct 2018 15:37:51 +0200 swh-scheduler (0.0.31-1~swh1) unstable-swh; urgency=medium * v0.0.31 * sql/swh-scheduler: Make the create_tasks call idempotent * swh.scheduler.utils: Open create_task_dict function * sql/scheduler-data: Add lister gitlab task types * sql/scheduler-data: Reference the existing production lister data * swh.scheduler.backend_es: Open sniffing options -- Antoine R. Dumont (@ardumont) Tue, 31 Jul 2018 06:55:39 +0200 swh-scheduler (0.0.30-1~swh1) unstable-swh; urgency=medium * v0.0.30 * swh-scheduler-schema.sql: Archive disabled oneshot tasks as well * swh.scheduler.cli: Add policy to pretty printing task routine * swh.scheduler.cli: Fix broken cli list-pending since api change -- Antoine R. Dumont (@ardumont) Fri, 22 Jun 2018 18:07:02 +0200 swh-scheduler (0.0.29-1~swh1) unstable-swh; urgency=medium * v0.0.29 * swh.scheduler.cli: Change archival period to rolling month - 1 week * swh.scheduler.updater.writer: Force filter resolution to list * swh.scheduler.cli: Change default archival period to current month * swh.scheduler.cli: Improve logging message * swh.scheduler.updater.backend: Adapt configuration path accordingly -- Antoine R. Dumont (@ardumont) Thu, 31 May 2018 11:42:51 +0200 swh-scheduler (0.0.28-1~swh1) unstable-swh; urgency=medium * v0.0.28 * Fix wrong runtime dependencies -- Antoine R. Dumont (@ardumont) Tue, 29 May 2018 14:12:15 +0200 swh-scheduler (0.0.27-1~swh1) unstable-swh; urgency=medium * v0.0.27 * scheduler: Deal with priority in tasks * scheduler-update: new package python3-swh.scheduler.updater * Contains tools in charge of consuming events from arbitrary sources * and update the scheduler db -- Antoine R. Dumont (@ardumont) Tue, 29 May 2018 12:27:34 +0200 swh-scheduler (0.0.26-1~swh1) unstable-swh; urgency=medium * v0.0.26 * swh.scheduler: Fix package build * swh.scheduler.tests: Test remote scheduler api as well * swh.scheduler: Add tests around removing archivable tasks * swh.scheduler: Add tests around filtering archivable tasks * swh-scheduler-schema: Fix unneeded drop instructions * swh.scheduler.cli: Improve docstring * swh.scheduler.cli: Permit to specify the backend to use in cli * swh.scheduler.api: Bootstrap scheduler's remote api * swh.scheduler: Use `get_scheduler` api to instantiate a scheduler * swh.scheduler.backend: Fix docstring -- Antoine R. Dumont (@ardumont) Thu, 26 Apr 2018 17:34:07 +0200 swh-scheduler (0.0.25-1~swh1) unstable-swh; urgency=medium * v0.0.25 * swh.scheduler.cli.archive: Index arguments.kwargs as text -- Antoine R. Dumont (@ardumont) Wed, 18 Apr 2018 12:34:43 +0200 swh-scheduler (0.0.24-1~swh1) unstable-swh; urgency=medium * v0.0.24 * data/template: Do not index the arguments field (it's in _source) * data/README: Add a small readme to explain es install step * swh.scheduler.cli: Add a bulk index flag to separate read from index -- Antoine R. Dumont (@ardumont) Fri, 13 Apr 2018 14:55:32 +0200 swh-scheduler (0.0.23-1~swh1) unstable-swh; urgency=medium * swh.scheduler.cli.archive: Delete only completely indexed tasks * Prior to this commit, it could happen that we removed tasks even * though we did not yet index associated task_run. * Related T986 -- Antoine R. Dumont (@ardumont) Tue, 10 Apr 2018 17:43:07 +0200 swh-scheduler (0.0.22-1~swh1) unstable-swh; urgency=medium * v0.0.22 * Update to a more recent python3-elasticsearch client -- Antoine R. Dumont (@ardumont) Mon, 09 Apr 2018 16:09:16 +0200 swh-scheduler (0.0.21-1~swh1) unstable-swh; urgency=medium * v0.0.21 * Adapt default configuration * Fix typo in configuration variable name -- Antoine R. Dumont (@ardumont) Fri, 30 Mar 2018 15:02:55 +0200 swh-scheduler (0.0.20-1~swh1) unstable-swh; urgency=medium * v0.0.20 * swh.scheduler.cli.archive: Open completed oneshot or disabled * recurring tasks archival endpoint * swh.core.serializer: Move to msgpack serialization format * swh.scheduler.cli: Unify pretty print output * sql/data: Add new task type for loading mercurial dump * swh.scheduler.cli: Add sample use case for the scheduling cli * swh.scheduler.cli: Open policy column to the scheduling cli * swh.scheduler.cli: Open the delimiter option as cli argument * Fix issue when updating task-type without any retry delay defined * swh-scheduler/data: Add new oneshot scheduling load-mercurial task * backend: fix default scheduling_db value for consistency * backend: doc: fix return value of create_tasks -- Antoine R. Dumont (@ardumont) Fri, 30 Mar 2018 11:44:18 +0200 swh-scheduler (0.0.19-1~swh1) unstable-swh; urgency=medium * v0.0.19 * swh.scheduler.utils: Open utility function to create oneshot task -- Antoine R. Dumont (@ardumont) Wed, 29 Nov 2017 12:51:15 +0100 swh-scheduler (0.0.18-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.18 * Celery 4 compatibility -- Nicolas Dandrimont Wed, 08 Nov 2017 17:06:22 +0100 swh-scheduler (0.0.17-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler version 0.0.17 * Update packaging runes -- Nicolas Dandrimont Thu, 12 Oct 2017 18:49:02 +0200 swh-scheduler (0.0.16-1~swh1) unstable-swh; urgency=medium * Release swh-scheduler v0.0.16 * add some tests * implement one-shot tasks * implement retry on temporary failure -- Nicolas Dandrimont Mon, 07 Aug 2017 18:44:03 +0200 swh-scheduler (0.0.15-1~swh1) unstable-swh; urgency=medium * Release swh-scheduler v0.0.15 * Add some methods to get the length of task queues * worker: Show logs on stdout if loglevel = debug -- Nicolas Dandrimont Mon, 19 Jun 2017 19:44:56 +0200 swh-scheduler (0.0.14-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler 0.0.14 * Make the return value of tasks available in the listener -- Nicolas Dandrimont Mon, 12 Jun 2017 17:50:32 +0200 swh-scheduler (0.0.13-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.13 * Use systemd for logging rather than PostgreSQL -- Nicolas Dandrimont Fri, 07 Apr 2017 11:57:50 +0200 swh-scheduler (0.0.12-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.12 * Only log to database if the configuration is present -- Nicolas Dandrimont Thu, 09 Mar 2017 11:12:45 +0100 swh-scheduler (0.0.11-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.11 * add utils.get_task -- Nicolas Dandrimont Tue, 14 Feb 2017 19:49:34 +0100 swh-scheduler (0.0.10-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.10 * Allow disabling tasks -- Nicolas Dandrimont Thu, 20 Oct 2016 17:20:17 +0200 swh-scheduler (0.0.9-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.9 * Revert management of one shot tasks * Add possibility of launching several worker instances -- Nicolas Dandrimont Fri, 02 Sep 2016 17:09:18 +0200 swh-scheduler (0.0.7-1~swh1) unstable-swh; urgency=medium * v0.0.7 * Add oneshot task -- Antoine R. Dumont (@ardumont) Fri, 01 Jul 2016 16:42:45 +0200 swh-scheduler (0.0.6-1~swh1) unstable-swh; urgency=medium * Release swh-scheduler v0.0.6 * More reliability and efficiency when scheduling a lot ot tasks -- Nicolas Dandrimont Wed, 24 Feb 2016 18:46:57 +0100 swh-scheduler (0.0.5-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.5 * Use copy for task mass-scheduling -- Nicolas Dandrimont Wed, 24 Feb 2016 12:13:38 +0100 swh-scheduler (0.0.4-1~swh1) unstable-swh; urgency=medium * Release swh-scheduler v0.0.4 * general cleanup of the backend * use arrow instead of dateutil * add new cli program -- Nicolas Dandrimont Tue, 23 Feb 2016 17:46:04 +0100 swh-scheduler (0.0.3-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler version 0.0.3 * Implement the timestamp arguments to the task_run functions * Make the celery event listener use a reliable queue -- Nicolas Dandrimont Mon, 22 Feb 2016 15:14:28 +0100 swh-scheduler (0.0.2-1~swh1) unstable-swh; urgency=medium * Release swh.scheduler v0.0.2 * Multiple schema changes * Initial releases for the celery job runner and the event listener -- Nicolas Dandrimont Fri, 19 Feb 2016 18:50:47 +0100 swh-scheduler (0.0.1-1~swh1) unstable-swh; urgency=medium * Initial release * Release swh.scheduler v0.0.1 * Move swh.core.scheduling and swh.core.worker to swh.scheduler -- Nicolas Dandrimont Mon, 15 Feb 2016 11:07:30 +0100 diff --git a/docs/.gitignore b/docs/.gitignore deleted file mode 100644 index 58a761e..0000000 --- a/docs/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -_build/ -apidoc/ -*-stamp diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index c30c50a..0000000 --- a/docs/Makefile +++ /dev/null @@ -1 +0,0 @@ -include ../../swh-docs/Makefile.sphinx diff --git a/docs/_static/.placeholder b/docs/_static/.placeholder deleted file mode 100644 index e69de29..0000000 diff --git a/docs/_templates/.placeholder b/docs/_templates/.placeholder deleted file mode 100644 index e69de29..0000000 diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 190deb7..0000000 --- a/docs/conf.py +++ /dev/null @@ -1 +0,0 @@ -from swh.docs.sphinx.conf import * # NoQA diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 0cb463d..0000000 --- a/docs/index.rst +++ /dev/null @@ -1,21 +0,0 @@ -.. _swh-scheduler: - -Software Heritage - Job scheduler -================================= - -Task manager for asynchronous/delayed tasks, used for both recurrent (e.g., -listing a forge, loading new stuff from a Git repository) and one-off -activities (e.g., loading a specific version of a source package). - - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index afa4cf3..0000000 --- a/pytest.ini +++ /dev/null @@ -1,2 +0,0 @@ -[pytest] -norecursedirs = docs diff --git a/requirements-swh.txt b/requirements-swh.txt index e7de3e1..e3c44ce 100644 --- a/requirements-swh.txt +++ b/requirements-swh.txt @@ -1 +1 @@ -swh.core >= 0.0.44 +swh.core >= 0.0.48 diff --git a/requirements-test.txt b/requirements-test.txt deleted file mode 100644 index 6c62abe..0000000 --- a/requirements-test.txt +++ /dev/null @@ -1,3 +0,0 @@ -hypothesis -pytest -celery diff --git a/requirements.txt b/requirements.txt index a5b03b6..6964b75 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,15 +1,15 @@ # Add here external Python modules dependencies, one per line. Module names # should match https://pypi.python.org/pypi names. For the full spec or # dependency lines, see https://pip.readthedocs.org/en/1.1/requirements.html arrow -celery +celery >= 4 Click elasticsearch > 5.4 flask kombu psycopg2 vcversioner # test dependencies # hypothesis diff --git a/sql/.gitignore b/sql/.gitignore deleted file mode 100644 index d501764..0000000 --- a/sql/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*-stamp -autodoc/ -swh-scheduler.dump diff --git a/sql/Makefile b/sql/Makefile deleted file mode 100644 index 5fc56d0..0000000 --- a/sql/Makefile +++ /dev/null @@ -1,71 +0,0 @@ -# Depends: postgresql-client, postgresql-autodoc - -DBNAME = softwareheritage-scheduler-dev -DOCDIR = autodoc - -SQL_SCHEMA = 30-swh-schema.sql -SQL_DATA = 40-swh-data.sql -SQLS = $(SQL_SCHEMA) $(SQL_DATA) -SQL_FILES = $(abspath $(addprefix $(CURDIR)/../swh/scheduler/sql/,$(SQLS))) - -PSQL_BIN = psql -PSQL_FLAGS = --echo-all -X -v ON_ERROR_STOP=1 -PSQL = $(PSQL_BIN) $(PSQL_FLAGS) - -PIFPAF=$(findstring postgresql://,$(PIFPAF_URLS)) - -all: - -createdb: createdb-stamp -createdb-stamp: $(SQL_FILES) -ifndef PIFPAF - -dropdb $(DBNAME) -endif - createdb $(DBNAME) -ifndef PIFPAF - touch $@ -else - rm -f $@ -endif - -filldb: filldb-stamp -filldb-stamp: createdb-stamp - cat $(SQL_FILES) | $(PSQL) $(DBNAME) -ifndef PIFPAF - touch $@ -else - rm -f $@ -endif - -dropdb: - -dropdb $(DBNAME) - -dumpdb: swh-scheduler.dump -swh-scheduler.dump: filldb-stamp - pg_dump -Fc $(DBNAME) > $@ - -$(DOCDIR): - test -d $(DOCDIR)/ || mkdir $(DOCDIR) - -doc: autodoc-stamp $(DOCDIR)/swh-scheduler.pdf -autodoc-stamp: filldb-stamp $(DOCDIR) - postgresql_autodoc -d $(DBNAME) -f $(DOCDIR)/swh-scheduler - cp -a $(DOCDIR)/swh-scheduler.dot $(DOCDIR)/swh-scheduler.dot.orig -ifndef PIFPAF - touch $@ -else - rm -f $@ -endif - -$(DOCDIR)/swh-scheduler.pdf: $(DOCDIR)/swh-scheduler.dot autodoc-stamp - dot -T pdf $< > $@ -$(DOCDIR)/swh-scheduler.svg: $(DOCDIR)/swh-scheduler.dot autodoc-stamp - dot -T svg $< > $@ - -clean: - rm -rf *-stamp $(DOCDIR)/ - -distclean: clean dropdb - rm -f swh-scheduler.dump - -.PHONY: all initdb createdb dropdb doc clean diff --git a/sql/updater/sql/Makefile b/sql/updater/sql/Makefile deleted file mode 100644 index 30263f2..0000000 --- a/sql/updater/sql/Makefile +++ /dev/null @@ -1,73 +0,0 @@ -# Depends: postgresql-client, postgresql-autodoc - -DBNAME = softwareheritage-scheduler-updater-dev -DOCDIR = autodoc - -SQL_INIT = 10-swh-init.sql -SQL_SCHEMA = 30-swh-schema.sql -SQL_FUNC = 40-swh-func.sql -SQLS = $(SQL_INIT) $(SQL_SCHEMA) $(SQL_FUNC) -SQL_FILES = $(abspath $(addprefix \ - $(CURDIR)/../../../swh/scheduler/sql/updater/,$(SQLS))) - -PSQL_BIN = psql -PSQL_FLAGS = --echo-all -X -v ON_ERROR_STOP=1 -PSQL = $(PSQL_BIN) $(PSQL_FLAGS) - -PIFPAF=$(findstring postgresql://,$(PIFPAF_URLS)) - -all: - -createdb: createdb-stamp -createdb-stamp: $(SQL_FILES) -ifndef PIFPAF - -dropdb $(DBNAME) -endif - createdb $(DBNAME) -ifndef PIFPAF - touch $@ -else - rm -f $@ -endif - -filldb: filldb-stamp -filldb-stamp: createdb-stamp - cat $(SQL_FILES) | $(PSQL) $(DBNAME) -ifndef PIFPAF - touch $@ -else - rm -f $@ -endif - -dropdb: - -dropdb $(DBNAME) - -dumpdb: swh-scheduler-updater.dump -swh-scheduler-updater.dump: filldb-stamp - pg_dump -Fc $(DBNAME) > $@ - -$(DOCDIR): - test -d $(DOCDIR)/ || mkdir $(DOCDIR) - -doc: autodoc-stamp $(DOCDIR)/swh-scheduler-updater.pdf -autodoc-stamp: filldb-stamp $(DOCDIR) - postgresql_autodoc -d $(DBNAME) -f $(DOCDIR)/swh-scheduler-updater - cp -a $(DOCDIR)/swh-scheduler-updater.dot $(DOCDIR)/swh-scheduler-updater.dot.orig -ifndef PIFPAF - touch $@ -else - rm -f $@ -endif - -$(DOCDIR)/swh-scheduler-updater.pdf: $(DOCDIR)/swh-scheduler-updater.dot autodoc-stamp - dot -T pdf $< > $@ -$(DOCDIR)/swh-scheduler-updater.svg: $(DOCDIR)/swh-scheduler-updater.dot autodoc-stamp - dot -T svg $< > $@ - -clean: - rm -rf *-stamp $(DOCDIR)/ - -distclean: clean dropdb - rm -f swh-scheduler-updater.dump - -.PHONY: all initdb createdb dropdb doc clean diff --git a/sql/updates/02.sql b/sql/updates/02.sql deleted file mode 100644 index 04fc040..0000000 --- a/sql/updates/02.sql +++ /dev/null @@ -1,66 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 01 --- to_version: 02 --- description: Allow mass-creation of task runs - -begin; - -insert into dbversion (version, release, description) - values (2, now(), 'Work In Progress'); - -create or replace function swh_scheduler_mktemp_task_run () - returns void - language sql -as $$ - create temporary table tmp_task_run ( - like task_run excluding indexes - ) on commit drop; - alter table tmp_task_run - drop column id, - drop column status; -$$; - -comment on function swh_scheduler_mktemp_task_run () is 'Create a temporary table for bulk task run scheduling'; - -create or replace function swh_scheduler_schedule_task_run_from_temp () - returns void - language plpgsql -as $$ -begin - insert into task_run (task, backend_id, metadata, scheduled, status) - select task, backend_id, metadata, scheduled, 'scheduled' - from tmp_task_run; - return; -end; -$$; - -create or replace function swh_scheduler_start_task_run (backend_id text, - metadata jsonb default '{}'::jsonb, - ts timestamptz default now()) - returns task_run - language sql -as $$ - update task_run - set started = ts, - status = 'started', - metadata = coalesce(task_run.metadata, '{}'::jsonb) || swh_scheduler_start_task_run.metadata - where task_run.backend_id = swh_scheduler_start_task_run.backend_id - returning *; -$$; - -create or replace function swh_scheduler_end_task_run (backend_id text, - status task_run_status, - metadata jsonb default '{}'::jsonb, - ts timestamptz default now()) - returns task_run - language sql -as $$ - update task_run - set ended = ts, - status = swh_scheduler_end_task_run.status, - metadata = coalesce(task_run.metadata, '{}'::jsonb) || swh_scheduler_end_task_run.metadata - where task_run.backend_id = swh_scheduler_end_task_run.backend_id - returning *; -$$; - -commit; diff --git a/sql/updates/03.sql b/sql/updates/03.sql deleted file mode 100644 index 5ec51d5..0000000 --- a/sql/updates/03.sql +++ /dev/null @@ -1,26 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 02 --- to_version: 03 --- description: Fix a bug in handling default intervals for task types - -begin; - -insert into dbversion (version, release, description) - values (3, now(), 'Work In Progress'); - -create or replace function swh_scheduler_create_tasks_from_temp () - returns setof task - language plpgsql -as $$ -begin - return query - insert into task (type, arguments, next_run, status, current_interval) - select type, arguments, next_run, 'next_run_not_scheduled', - (select default_interval from task_type tt where tt.type = tmp_task.type) - from tmp_task - returning task.*; -end; -$$; - - -commit; diff --git a/sql/updates/04.sql b/sql/updates/04.sql deleted file mode 100644 index a051388..0000000 --- a/sql/updates/04.sql +++ /dev/null @@ -1,53 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 03 --- to_version: 04 --- description: Add a maximum queue length to the task types in the scheduler - -begin; - -insert into dbversion (version, release, description) -values (4, now(), 'Work In Progress'); - -alter table task_type add column max_queue_length bigint; -comment on column task_type.max_queue_length is 'Maximum length of the queue for this type of tasks'; - - -drop function swh_scheduler_peek_ready_tasks (timestamptz, bigint); -drop function swh_scheduler_grab_ready_tasks (timestamptz, bigint); - -create or replace function swh_scheduler_peek_ready_tasks (task_type text, ts timestamptz default now(), - num_tasks bigint default NULL) - returns setof task - language sql - stable -as $$ -select * from task - where next_run <= ts - and type = task_type - and status = 'next_run_not_scheduled' - order by next_run - limit num_tasks; -$$; - -create or replace function swh_scheduler_grab_ready_tasks (task_type text, ts timestamptz default now(), - num_tasks bigint default NULL) - returns setof task - language sql -as $$ - update task - set status='next_run_scheduled' - from ( - select id from task - where next_run <= ts - and type = task_type - and status='next_run_not_scheduled' - order by next_run - limit num_tasks - for update skip locked - ) next_tasks - where task.id = next_tasks.id - returning task.*; -$$; - - -commit; diff --git a/sql/updates/05.sql b/sql/updates/05.sql deleted file mode 100644 index b55a533..0000000 --- a/sql/updates/05.sql +++ /dev/null @@ -1,144 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 04 --- to_version: 05 --- description: Add reccurrence logic for temporary failures and one-shot tasks - -alter type task_status add value if not exists 'completed' before 'disabled'; -alter type task_run_status add value if not exists 'permfailed' after 'failed'; - -begin; - -insert into dbversion (version, release, description) -values (5, now(), 'Work In Progress'); - -alter table task_type add column num_retries bigint; -alter table task_type add column retry_delay interval; - -comment on column task_type.num_retries is 'Default number of retries on transient failures'; -comment on column task_type.retry_delay is 'Retry delay for the task'; - -create type task_policy as enum ('recurring', 'oneshot'); -comment on type task_policy is 'Recurrence policy of the given task'; - -alter table task add column policy task_policy not null default 'recurring'; -alter table task add column retries_left bigint not null default 0; - -comment on column task.policy is 'Whether the task is one-shot or recurring'; -comment on column task.retries_left is 'The number of "short delay" retries of the task in case of ' - 'transient failure'; - - -create or replace function swh_scheduler_mktemp_task () - returns void - language sql -as $$ - create temporary table tmp_task ( - like task excluding indexes - ) on commit drop; - alter table tmp_task - drop column id, - drop column current_interval, - drop column status, - alter column policy drop not null, - alter column retries_left drop not null; -$$; - -comment on function swh_scheduler_mktemp_task () is 'Create a temporary table for bulk task creation'; - -create or replace function swh_scheduler_create_tasks_from_temp () - returns setof task - language plpgsql -as $$ -begin - return query - insert into task (type, arguments, next_run, status, current_interval, policy, retries_left) - select type, arguments, next_run, 'next_run_not_scheduled', - (select default_interval from task_type tt where tt.type = tmp_task.type), - coalesce(policy, 'recurring'), - coalesce(retries_left, (select num_retries from task_type tt where tt.type = tmp_task.type), 0) - from tmp_task - returning task.*; -end; -$$; - -comment on function swh_scheduler_create_tasks_from_temp () is 'Create tasks in bulk from the temporary table'; - -drop trigger update_interval_on_task_end on task_run; -drop function swh_scheduler_compute_new_task_interval (text, interval, task_run_status) cascade; -drop function swh_scheduler_update_task_interval () cascade; - -create or replace function swh_scheduler_update_task_on_task_end () - returns trigger - language plpgsql -as $$ -declare - cur_task task%rowtype; - cur_task_type task_type%rowtype; - adjustment_factor float; - new_interval interval; -begin - select * from task where id = new.task into cur_task; - select * from task_type where type = cur_task.type into cur_task_type; - - case - when new.status = 'permfailed' then - update task - set status = 'disabled' - where id = cur_task.id; - when new.status in ('eventful', 'uneventful') then - case - when cur_task.policy = 'oneshot' then - update task - set status = 'completed' - where id = cur_task.id; - when cur_task.policy = 'recurring' then - if new.status = 'uneventful' then - adjustment_factor := 1/cur_task_type.backoff_factor; - else - adjustment_factor := 1/cur_task_type.backoff_factor; - end if; - new_interval := greatest( - cur_task_type.min_interval, - least( - cur_task_type.max_interval, - adjustment_factor * cur_task.current_interval)); - update task - set status = 'next_run_not_scheduled', - next_run = now() + new_interval, - current_interval = new_interval, - retries_left = coalesce(cur_task_type.num_retries, 0) - where id = cur_task.id; - end case; - else -- new.status in 'failed', 'lost' - if cur_task.retries_left > 0 then - update task - set status = 'next_run_not_scheduled', - next_run = now() + cur_task_type.retry_delay, - retries_left = cur_task.retries_left - 1 - where id = cur_task.id; - else -- no retries left - case - when cur_task.policy = 'oneshot' then - update task - set status = 'disabled' - where id = cur_task.id; - when cur_task.policy = 'recurring' then - update task - set status = 'next_run_not_scheduled', - next_run = now() + cur_task.current_interval, - retries_left = coalesce(cur_task_type.num_retries, 0) - where id = cur_task.id; - end case; - end if; -- retries - end case; - return null; -end; -$$; - -create trigger update_task_on_task_end - after update of status on task_run - for each row - when (new.status NOT IN ('scheduled', 'started')) - execute procedure swh_scheduler_update_task_on_task_end (); - -commit; diff --git a/sql/updates/06.sql b/sql/updates/06.sql deleted file mode 100644 index 8aa1d9f..0000000 --- a/sql/updates/06.sql +++ /dev/null @@ -1,23 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 05 --- to_version: 06 --- description: relax constraints on intervals for one-shot tasks - -begin; - -insert into dbversion (version, release, description) - values (6, now(), 'Work In Progress'); - - -alter table task_type - alter column default_interval drop not null, - alter column min_interval drop not null, - alter column max_interval drop not null, - alter column backoff_factor drop not null; - -alter table task - alter column current_interval drop not null, - add constraint task_check check (policy <> 'recurring' or current_interval is not null); - -commit; - diff --git a/sql/updates/07.sql b/sql/updates/07.sql deleted file mode 100644 index 6082e0a..0000000 --- a/sql/updates/07.sql +++ /dev/null @@ -1,54 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 06 --- to_version: 07 --- description: Archive 'oneshot' and disabled 'recurring' tasks (status = 'disabled') - -insert into dbversion (version, release, description) -values (7, now(), 'Work In Progress'); - -create type task_record as ( - task_id bigint, - task_policy task_policy, - task_status task_status, - task_run_id bigint, - arguments jsonb, - type text, - backend_id text, - metadata jsonb, - scheduled timestamptz, - started timestamptz, - ended timestamptz -); - -create index task_run_id_asc_idx on task_run(task asc, ended asc); - -create or replace function swh_scheduler_task_to_archive( - ts timestamptz, last_id bigint default -1, lim bigint default 10) - returns setof task_record - language sql stable -as $$ - select t.id as task_id, t.policy as task_policy, - t.status as task_status, tr.id as task_run_id, - t.arguments, t.type, tr.backend_id, tr.metadata, - tr.scheduled, tr.started, tr.ended - from task_run tr inner join task t on tr.task=t.id - where ((t.policy = 'oneshot' and t.status ='completed') or - (t.policy = 'recurring' and t.status ='disabled')) and - tr.ended < ts and - t.id > last_id - order by tr.task, tr.ended - limit lim; -$$; - -comment on function swh_scheduler_task_to_archive is 'Read archivable tasks function'; - -create or replace function swh_scheduler_delete_archive_tasks( - task_ids bigint[]) - returns void - language sql -as $$ - delete from task_run where task in (select * from unnest(task_ids)); - delete from task where id in (select * from unnest(task_ids)); -$$; - -comment on function swh_scheduler_delete_archive_tasks is 'Clean up archived tasks function'; diff --git a/sql/updates/08.sql b/sql/updates/08.sql deleted file mode 100644 index b9ac8fb..0000000 --- a/sql/updates/08.sql +++ /dev/null @@ -1,51 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 07 --- to_version: 08 --- description: Improve task to archive filtering function - -insert into dbversion (version, release, description) -values (8, now(), 'Work In Progress'); - -drop function swh_scheduler_task_to_archive(timestamptz, bigint, bigint); - -create or replace function swh_scheduler_task_to_archive( - ts_after timestamptz, ts_before timestamptz, last_id bigint default -1, - lim bigint default 10) - returns setof task_record - language sql stable -as $$ - select t.id as task_id, t.policy as task_policy, - t.status as task_status, tr.id as task_run_id, - t.arguments, t.type, tr.backend_id, tr.metadata, - tr.scheduled, tr.started, tr.ended - from task_run tr inner join task t on tr.task=t.id - where ((t.policy = 'oneshot' and t.status ='completed') or - (t.policy = 'recurring' and t.status ='disabled')) and - ts_after <= tr.ended and tr.ended < ts_before and - t.id > last_id - order by tr.task, tr.ended - limit lim; -$$; - -comment on function swh_scheduler_task_to_archive is 'Read archivable tasks function'; - -drop function swh_scheduler_delete_archive_tasks(bigint[]); - -create or replace function swh_scheduler_delete_archived_tasks( - task_ids bigint[], task_run_ids bigint[]) - returns void - language sql -as $$ - -- clean up task_run_ids - delete from task_run where id in (select * from unnest(task_run_ids)); - -- clean up only tasks whose associated task_run are all cleaned up. - -- Remaining tasks will stay there and will be cleaned up when - -- remaining data have been indexed - delete from task - where id in (select t.id - from task t left outer join task_run tr on t.id=tr.task - where t.id in (select * from unnest(task_ids)) - and tr.task is null); -$$; - -comment on function swh_scheduler_delete_archived_tasks is 'Clean up archived tasks function'; diff --git a/sql/updates/09.sql b/sql/updates/09.sql deleted file mode 100644 index 7fe97ca..0000000 --- a/sql/updates/09.sql +++ /dev/null @@ -1,205 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 08 --- to_version: 09 --- description: Schedule task with priority - -insert into dbversion (version, release, description) -values (9, now(), 'Work In Progress'); - -create type task_priority as enum('high', 'normal', 'low'); -comment on type task_priority is 'Priority of the given task'; - -create table priority_ratio( - id task_priority primary key, - ratio float not null -); - -comment on table priority_ratio is 'Oneshot task''s reading ratio per priority'; -comment on column priority_ratio.id is 'Task priority id'; -comment on column priority_ratio.ratio is 'Percentage of tasks to read per priority'; - -insert into priority_ratio (id, ratio) values ('high', 0.5); -insert into priority_ratio (id, ratio) values ('normal', 0.3); -insert into priority_ratio (id, ratio) values ('low', 0.2); - -alter table task add column priority task_priority references priority_ratio(id); -comment on column task.priority is 'Policy of the given task'; - -drop function swh_scheduler_peek_ready_tasks(text, timestamptz, bigint); -drop function swh_scheduler_grab_ready_tasks(text, timestamptz, bigint); - -create or replace function swh_scheduler_peek_no_priority_tasks (task_type text, ts timestamptz default now(), - num_tasks bigint default NULL) - returns setof task - language sql - stable -as $$ -select * from task - where next_run <= ts - and type = task_type - and status = 'next_run_not_scheduled' - and priority is null - order by next_run - limit num_tasks - for update skip locked; -$$; - -comment on function swh_scheduler_peek_no_priority_tasks (text, timestamptz, bigint) -is 'Retrieve tasks without priority'; - -create or replace function swh_scheduler_nb_priority_tasks(num_tasks_priority bigint, task_priority task_priority) - returns numeric - language sql stable -as $$ - select ceil(num_tasks_priority * (select ratio from priority_ratio where id = task_priority)) :: numeric -$$; - -comment on function swh_scheduler_nb_priority_tasks (bigint, task_priority) -is 'Given a priority task and a total number, compute the number of tasks to read'; - -create or replace function swh_scheduler_peek_tasks_with_priority (task_type text, ts timestamptz default now(), - num_tasks_priority bigint default NULL, - task_priority task_priority default 'normal') - returns setof task - language sql - stable -as $$ - select * - from task t - where t.next_run <= ts - and t.type = task_type - and t.status = 'next_run_not_scheduled' - and t.priority = task_priority - order by t.next_run - limit num_tasks_priority - for update skip locked; -$$; - -comment on function swh_scheduler_peek_tasks_with_priority(text, timestamptz, bigint, task_priority) -is 'Retrieve tasks with a given priority'; - -create or replace function swh_scheduler_peek_priority_tasks (task_type text, ts timestamptz default now(), - num_tasks_priority bigint default NULL) - returns setof task - language plpgsql -as $$ -declare - r record; - count_row bigint; - nb_diff bigint; - nb_high bigint; - nb_normal bigint; - nb_low bigint; -begin - -- expected values to fetch - select swh_scheduler_nb_priority_tasks(num_tasks_priority, 'high') into nb_high; - select swh_scheduler_nb_priority_tasks(num_tasks_priority, 'normal') into nb_normal; - select swh_scheduler_nb_priority_tasks(num_tasks_priority, 'low') into nb_low; - nb_diff := 0; - count_row := 0; - - for r in select * from swh_scheduler_peek_tasks_with_priority(task_type, ts, nb_high, 'high') - loop - count_row := count_row + 1; - return next r; - end loop; - - if count_row < nb_high then - nb_normal := nb_normal + nb_high - count_row; - end if; - - count_row := 0; - for r in select * from swh_scheduler_peek_tasks_with_priority(task_type, ts, nb_normal, 'normal') - loop - count_row := count_row + 1; - return next r; - end loop; - - if count_row < nb_normal then - nb_low := nb_low + nb_normal - count_row; - end if; - - return query select * from swh_scheduler_peek_tasks_with_priority(task_type, ts, nb_low, 'low'); -end -$$; - -comment on function swh_scheduler_peek_priority_tasks(text, timestamptz, bigint) -is 'Retrieve priority tasks'; - -create or replace function swh_scheduler_peek_ready_tasks (task_type text, ts timestamptz default now(), - num_tasks bigint default NULL, num_tasks_priority bigint default NULL) - returns setof task - language plpgsql -as $$ -declare - r record; - count_row bigint; - nb_diff bigint; - nb_tasks bigint; -begin - count_row := 0; - - for r in select * from swh_scheduler_peek_priority_tasks(task_type, ts, num_tasks_priority) - order by priority, next_run - loop - count_row := count_row + 1; - return next r; - end loop; - - if count_row < num_tasks_priority then - nb_tasks := num_tasks + num_tasks_priority - count_row; - else - nb_tasks := num_tasks; - end if; - - for r in select * from swh_scheduler_peek_no_priority_tasks(task_type, ts, nb_tasks) - order by priority, next_run - loop - return next r; - end loop; - - return; -end -$$; - -comment on function swh_scheduler_peek_ready_tasks(text, timestamptz, bigint, bigint) -is 'Retrieve tasks with/without priority in order'; - -create or replace function swh_scheduler_grab_ready_tasks (task_type text, ts timestamptz default now(), - num_tasks bigint default NULL, - num_tasks_priority bigint default NULL) - returns setof task - language sql -as $$ - update task - set status='next_run_scheduled' - from ( - select id from swh_scheduler_peek_ready_tasks(task_type, ts, num_tasks, num_tasks_priority) - ) next_tasks - where task.id = next_tasks.id - returning task.*; -$$; - -comment on function swh_scheduler_grab_ready_tasks (text, timestamptz, bigint, bigint) -is 'Grab tasks ready for scheduling and change their status'; - -create index on task(priority); - -create or replace function swh_scheduler_create_tasks_from_temp () - returns setof task - language plpgsql -as $$ -begin - return query - insert into task (type, arguments, next_run, status, current_interval, policy, retries_left, priority) - select type, arguments, next_run, 'next_run_not_scheduled', - (select default_interval from task_type tt where tt.type = tmp_task.type), - coalesce(policy, 'recurring'), - coalesce(retries_left, (select num_retries from task_type tt where tt.type = tmp_task.type), 0), - coalesce(priority, null) - from tmp_task - returning task.*; -end; -$$; - -comment on function swh_scheduler_create_tasks_from_temp () is 'Create tasks in bulk from the temporary table'; diff --git a/sql/updates/10.sql b/sql/updates/10.sql deleted file mode 100644 index bd57768..0000000 --- a/sql/updates/10.sql +++ /dev/null @@ -1,47 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 09 --- to_version: 10 --- description: Schedule task with priority - -insert into dbversion (version, release, description) -values (10, now(), 'Work In Progress'); - -drop type task_record cascade; -create type task_record as ( - task_id bigint, - task_policy task_policy, - task_status task_status, - task_run_id bigint, - arguments jsonb, - type text, - backend_id text, - metadata jsonb, - scheduled timestamptz, - started timestamptz, - ended timestamptz, - task_run_status task_run_status -); - -drop index task_run_id_asc_idx; -create index task_run_id_started_asc_idx on task_run(task asc, started asc); - -create or replace function swh_scheduler_task_to_archive( - ts_after timestamptz, ts_before timestamptz, last_id bigint default -1, - lim bigint default 10) - returns setof task_record - language sql stable -as $$ - select t.id as task_id, t.policy as task_policy, - t.status as task_status, tr.id as task_run_id, - t.arguments, t.type, tr.backend_id, tr.metadata, - tr.scheduled, tr.started, tr.ended, tr.status as task_run_status - from task_run tr inner join task t on tr.task=t.id - where ((t.policy = 'oneshot' and t.status in ('completed', 'disabled')) or - (t.policy = 'recurring' and t.status = 'disabled')) and - ((ts_after <= tr.started and tr.started < ts_before) or tr.started is null) and - t.id > last_id - order by tr.task, tr.started - limit lim; -$$; - -comment on function swh_scheduler_task_to_archive is 'Read archivable tasks function'; diff --git a/sql/updates/11.sql b/sql/updates/11.sql deleted file mode 100644 index 75edc4f..0000000 --- a/sql/updates/11.sql +++ /dev/null @@ -1,64 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 10 --- to_version: 11 --- description: Upgrade scheduler create_tasks routine - -insert into dbversion (version, release, description) -values (11, now(), 'Work In Progress'); - -create or replace function swh_scheduler_mktemp_task () - returns void - language sql -as $$ - create temporary table tmp_task ( - like task excluding indexes - ) on commit drop; - alter table tmp_task - alter column retries_left drop not null, - drop column id; -$$; - -comment on function swh_scheduler_mktemp_task () is 'Create a temporary table for bulk task creation'; - -create or replace function swh_scheduler_create_tasks_from_temp () - returns setof task - language plpgsql -as $$ -begin - -- update the default values in one go - -- this is separated from the insert/select to avoid too much - -- juggling - update tmp_task t - set current_interval = tt.default_interval, - retries_left = coalesce(retries_left, tt.num_retries, 0) - from task_type tt - where tt.type=t.type; - - insert into task (type, arguments, next_run, status, current_interval, policy, - retries_left, priority) - select type, arguments, next_run, status, current_interval, policy, - retries_left, priority - from tmp_task t - where not exists(select 1 - from task - where type = t.type and - arguments = t.arguments and - policy = t.policy and - ((priority is null and t.priority is null) - or priority = t.priority) and - status = t.status); - - return query - select distinct t.* - from tmp_task tt inner join task t on ( - t.type = tt.type and - t.arguments = tt.arguments and - t.status = tt.status and - ((t.priority is null and tt.priority is null) - or t.priority=tt.priority) and - t.policy=tt.policy - ); -end; -$$; - -comment on function swh_scheduler_create_tasks_from_temp () is 'Create tasks in bulk from the temporary table'; diff --git a/sql/updates/12.sql b/sql/updates/12.sql deleted file mode 100644 index 3ab8c42..0000000 --- a/sql/updates/12.sql +++ /dev/null @@ -1,51 +0,0 @@ --- SWH Scheduler Schema upgrade --- from_version: 11 --- to_version: 12 --- description: Upgrade scheduler create_tasks routine - -insert into dbversion (version, release, description) - values (12, now(), 'Work In Progress'); - -create or replace function swh_scheduler_create_tasks_from_temp () - returns setof task - language plpgsql -as $$ -begin - -- update the default values in one go - -- this is separated from the insert/select to avoid too much - -- juggling - update tmp_task t - set current_interval = tt.default_interval, - retries_left = coalesce(retries_left, tt.num_retries, 0) - from task_type tt - where tt.type=t.type; - - insert into task (type, arguments, next_run, status, current_interval, policy, - retries_left, priority) - select type, arguments, next_run, status, current_interval, policy, - retries_left, priority - from tmp_task t - where not exists(select 1 - from task - where type = t.type and - arguments->'args' = t.arguments->'args' and - arguments->'kwargs' = t.arguments->'kwargs' and - policy = t.policy and - priority is not distinct from t.priority and - status = t.status); - - return query - select distinct t.* - from tmp_task tt inner join task t on ( - tt.type = t.type and - tt.arguments->'args' = t.arguments->'args' and - tt.arguments->'kwargs' = t.arguments->'kwargs' and - tt.policy = t.policy and - tt.priority is not distinct from t.priority and - tt.status = t.status - ); -end; -$$; - -comment on function swh_scheduler_create_tasks_from_temp () is 'Create tasks in bulk from the temporary table'; - diff --git a/swh.scheduler.egg-info/PKG-INFO b/swh.scheduler.egg-info/PKG-INFO index 92333fc..ffc6c79 100644 --- a/swh.scheduler.egg-info/PKG-INFO +++ b/swh.scheduler.egg-info/PKG-INFO @@ -1,65 +1,65 @@ Metadata-Version: 2.1 Name: swh.scheduler -Version: 0.0.35 +Version: 0.0.38 Summary: Software Heritage Scheduler Home-page: https://forge.softwareheritage.org/diffusion/DSCH/ Author: Software Heritage developers Author-email: swh-devel@inria.fr License: UNKNOWN -Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest -Project-URL: Funding, https://www.softwareheritage.org/donate Project-URL: Source, https://forge.softwareheritage.org/source/swh-scheduler +Project-URL: Funding, https://www.softwareheritage.org/donate +Project-URL: Bug Reports, https://forge.softwareheritage.org/maniphest Description: swh-scheduler ============= Job scheduler for the Software Heritage project. Task manager for asynchronous/delayed tasks, used for both recurrent (e.g., listing a forge, loading new stuff from a Git repository) and one-off activities (e.g., loading a specific version of a source package). # Tests ## Running test manually ### Test data To be able to run (unit) tests, you need to have the [[https://forge.softwareheritage.org/source/swh-storage-testdata.git|swh-storage-testdata]] in the parent directory. If you have set your environment following the [[ https://docs.softwareheritage.org/devel/getting-started.html#getting-started|Getting started]] - document everythong should be set up just fine. + document everything should be set up just fine. Otherwise: ``` ~/.../swh-scheduler$ git clone https://forge.softwareheritage.org/source/swh-storage-testdata.git ../swh-storage-testdata ``` ### Required services Unit tests that require a running celery broker uses an in memory broker/result backend by default, but you can choose to use a true broker by setting `CELERY_BROKER_URL` and `CELERY_RESULT_BACKEND` environment variables up. For example: ``` $ CELERY_BROKER_URL=amqp://localhost pifpaf run postgresql nosetests ..................................... ---------------------------------------------------------------------- Ran 37 tests in 15.578s OK ``` Platform: UNKNOWN Classifier: Programming Language :: Python :: 3 Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3) Classifier: Operating System :: OS Independent Classifier: Development Status :: 5 - Production/Stable Description-Content-Type: text/markdown Provides-Extra: testing diff --git a/swh.scheduler.egg-info/SOURCES.txt b/swh.scheduler.egg-info/SOURCES.txt index c70dbeb..910cb10 100644 --- a/swh.scheduler.egg-info/SOURCES.txt +++ b/swh.scheduler.egg-info/SOURCES.txt @@ -1,91 +1,55 @@ -.gitignore -AUTHORS -LICENSE -LICENSE.Celery MANIFEST.in Makefile README.md -pytest.ini requirements-swh.txt -requirements-test.txt requirements.txt setup.py -tox.ini version.txt bin/swh-worker-control -data/README.md -data/elastic-template.json -data/update-index-settings.json -debian/changelog -debian/compat -debian/control -debian/copyright -debian/rules -debian/source/format -docs/.gitignore -docs/Makefile -docs/conf.py -docs/index.rst -docs/_static/.placeholder -docs/_templates/.placeholder -sql/.gitignore -sql/Makefile -sql/updater/sql/Makefile -sql/updates/02.sql -sql/updates/03.sql -sql/updates/04.sql -sql/updates/05.sql -sql/updates/06.sql -sql/updates/07.sql -sql/updates/08.sql -sql/updates/09.sql -sql/updates/10.sql -sql/updates/11.sql -sql/updates/12.sql swh/__init__.py swh.scheduler.egg-info/PKG-INFO swh.scheduler.egg-info/SOURCES.txt swh.scheduler.egg-info/dependency_links.txt swh.scheduler.egg-info/entry_points.txt swh.scheduler.egg-info/requires.txt swh.scheduler.egg-info/top_level.txt swh/scheduler/__init__.py swh/scheduler/backend.py swh/scheduler/backend_es.py swh/scheduler/cli.py swh/scheduler/task.py swh/scheduler/utils.py swh/scheduler/api/__init__.py swh/scheduler/api/client.py swh/scheduler/api/server.py swh/scheduler/celery_backend/__init__.py swh/scheduler/celery_backend/config.py swh/scheduler/celery_backend/listener.py swh/scheduler/celery_backend/runner.py swh/scheduler/sql/30-swh-schema.sql swh/scheduler/sql/40-swh-data.sql swh/scheduler/sql/updater/10-swh-init.sql swh/scheduler/sql/updater/30-swh-schema.sql swh/scheduler/sql/updater/40-swh-func.sql swh/scheduler/tests/__init__.py swh/scheduler/tests/celery_testing.py swh/scheduler/tests/scheduler_testing.py swh/scheduler/tests/test_api_client.py swh/scheduler/tests/test_fixtures.py swh/scheduler/tests/test_scheduler.py swh/scheduler/tests/test_task.py swh/scheduler/tests/test_utils.py swh/scheduler/tests/updater/__init__.py swh/scheduler/tests/updater/test_backend.py swh/scheduler/tests/updater/test_consumer.py swh/scheduler/tests/updater/test_events.py swh/scheduler/tests/updater/test_ghtorrent.py swh/scheduler/tests/updater/test_writer.py swh/scheduler/updater/__init__.py swh/scheduler/updater/backend.py swh/scheduler/updater/consumer.py swh/scheduler/updater/events.py swh/scheduler/updater/writer.py swh/scheduler/updater/ghtorrent/__init__.py swh/scheduler/updater/ghtorrent/cli.py swh/scheduler/updater/ghtorrent/fake.py \ No newline at end of file diff --git a/swh.scheduler.egg-info/requires.txt b/swh.scheduler.egg-info/requires.txt index aab4582..dd2c8d5 100644 --- a/swh.scheduler.egg-info/requires.txt +++ b/swh.scheduler.egg-info/requires.txt @@ -1,14 +1,14 @@ -Click arrow -celery +celery>=4 +Click elasticsearch>5.4 flask kombu psycopg2 -swh.core>=0.0.44 vcversioner +swh.core>=0.0.48 [testing] -celery hypothesis pytest +celery>=4 diff --git a/swh/scheduler/backend.py b/swh/scheduler/backend.py index a7a406a..835c089 100644 --- a/swh/scheduler/backend.py +++ b/swh/scheduler/backend.py @@ -1,521 +1,523 @@ # Copyright (C) 2015-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import binascii import datetime from functools import wraps import json import tempfile from arrow import Arrow, utcnow import psycopg2 import psycopg2.extras from psycopg2.extensions import AsIs from swh.core.config import SWHConfig def adapt_arrow(arrow): return AsIs("'%s'::timestamptz" % arrow.isoformat()) psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json) psycopg2.extensions.register_adapter(Arrow, adapt_arrow) def autocommit(fn): @wraps(fn) def wrapped(self, *args, **kwargs): autocommit = False if 'cursor' not in kwargs or not kwargs['cursor']: autocommit = True kwargs['cursor'] = self.cursor() try: ret = fn(self, *args, **kwargs) except Exception: if autocommit: self.rollback() raise if autocommit: self.commit() return ret return wrapped class DbBackend: """Mixin intended to be used within scheduling db backend classes cf. swh.scheduler.backend.SchedulerBackend, and swh.scheduler.updater.backend.SchedulerUpdaterBackend """ def reconnect(self): if not self.db or self.db.closed: self.db = psycopg2.connect( dsn=self.db_conn_dsn, cursor_factory=psycopg2.extras.RealDictCursor, ) def cursor(self): """Return a fresh cursor on the database, with auto-reconnection in case of failure """ cur = None # Get a fresh cursor and reconnect at most three times tries = 0 while True: tries += 1 try: cur = self.db.cursor() cur.execute('select 1') break except psycopg2.OperationalError: if tries < 3: self.reconnect() else: raise return cur def commit(self): """Commit a transaction""" self.db.commit() def rollback(self): """Rollback a transaction""" self.db.rollback() def close_connection(self): """Close db connection""" if self.db and not self.db.closed: self.db.close() def _format_query(self, query, keys): """Format a query with the given keys""" query_keys = ', '.join(keys) placeholders = ', '.join(['%s'] * len(keys)) return query.format(keys=query_keys, placeholders=placeholders) def _format_multiquery(self, query, keys, values): """Format a query with placeholders generated for multiple values""" query_keys = ', '.join(keys) placeholders = '), ('.join( [', '.join(['%s'] * len(keys))] * len(values) ) ret_values = sum([[value[key] for key in keys] for value in values], []) return ( query.format(keys=query_keys, placeholders=placeholders), ret_values, ) def copy_to(self, items, tblname, columns, default_columns={}, cursor=None, item_cb=None): def escape(data): if data is None: return '' if isinstance(data, bytes): return '\\x%s' % binascii.hexlify(data).decode('ascii') elif isinstance(data, str): return '"%s"' % data.replace('"', '""') elif isinstance(data, (datetime.datetime, Arrow)): # We escape twice to make sure the string generated by # isoformat gets escaped return escape(data.isoformat()) elif isinstance(data, dict): return escape(json.dumps(data)) elif isinstance(data, list): return escape("{%s}" % ','.join(escape(d) for d in data)) elif isinstance(data, psycopg2.extras.Range): # We escape twice here too, so that we make sure # everything gets passed to copy properly return escape( '%s%s,%s%s' % ( '[' if data.lower_inc else '(', '-infinity' if data.lower_inf else escape(data.lower), 'infinity' if data.upper_inf else escape(data.upper), ']' if data.upper_inc else ')', ) ) else: # We don't escape here to make sure we pass literals properly return str(data) with tempfile.TemporaryFile('w+') as f: for d in items: if item_cb is not None: item_cb(d) line = [] for k in columns: v = d.get(k) if not v: v = default_columns.get(k) v = escape(v) line.append(v) f.write(','.join(line)) f.write('\n') f.seek(0) cursor.copy_expert('COPY %s (%s) FROM STDIN CSV' % ( tblname, ', '.join(columns)), f) class SchedulerBackend(SWHConfig, DbBackend): """Backend for the Software Heritage scheduling database. """ CONFIG_BASE_FILENAME = 'scheduler' DEFAULT_CONFIG = { 'scheduling_db': ('str', 'dbname=softwareheritage-scheduler-dev'), } def __init__(self, **override_config): super().__init__() self.config = self.parse_config_file(global_config=False) self.config.update(override_config) self.db = None self.db_conn_dsn = self.config['scheduling_db'] self.reconnect() task_type_keys = [ 'type', 'description', 'backend_name', 'default_interval', 'min_interval', 'max_interval', 'backoff_factor', 'max_queue_length', 'num_retries', 'retry_delay', ] @autocommit def create_task_type(self, task_type, cursor=None): """Create a new task type ready for scheduling. Args: task_type (dict): a dictionary with the following keys: - type (str): an identifier for the task type - description (str): a human-readable description of what the task does - backend_name (str): the name of the task in the job-scheduling backend - default_interval (datetime.timedelta): the default interval between two task runs - min_interval (datetime.timedelta): the minimum interval between two task runs - max_interval (datetime.timedelta): the maximum interval between two task runs - backoff_factor (float): the factor by which the interval changes at each run - max_queue_length (int): the maximum length of the task queue for this task type """ query = self._format_query( """insert into task_type ({keys}) values ({placeholders})""", self.task_type_keys, ) cursor.execute(query, [task_type[key] for key in self.task_type_keys]) @autocommit def get_task_type(self, task_type_name, cursor=None): """Retrieve the task type with id task_type_name""" query = self._format_query( "select {keys} from task_type where type=%s", self.task_type_keys, ) cursor.execute(query, (task_type_name,)) ret = cursor.fetchone() return ret @autocommit def get_task_types(self, cursor=None): query = self._format_query( "select {keys} from task_type", self.task_type_keys, ) cursor.execute(query) ret = cursor.fetchall() return ret task_create_keys = [ 'type', 'arguments', 'next_run', 'policy', 'status', 'retries_left', 'priority' ] task_keys = task_create_keys + ['id', 'current_interval', 'status'] @autocommit - def create_tasks(self, tasks, cursor=None): + def create_tasks(self, tasks, policy='recurring', cursor=None): """Create new tasks. Args: tasks (list): each task is a dictionary with the following keys: - type (str): the task type - arguments (dict): the arguments for the task runner, keys: - args (list of str): arguments - kwargs (dict str -> str): keyword arguments - next_run (datetime.datetime): the next scheduled run for the task Returns: a list of created tasks. """ cursor.execute('select swh_scheduler_mktemp_task()') self.copy_to(tasks, 'tmp_task', self.task_create_keys, default_columns={ - 'policy': 'recurring', + 'policy': policy, 'status': 'next_run_not_scheduled' }, cursor=cursor) query = self._format_query( 'select {keys} from swh_scheduler_create_tasks_from_temp()', self.task_keys, ) cursor.execute(query) return cursor.fetchall() @autocommit def set_status_tasks(self, task_ids, status='disabled', cursor=None): """Set the tasks' status whose ids are listed.""" + if not task_ids: + return query = "UPDATE task SET status = %s WHERE id IN %s" cursor.execute(query, (status, tuple(task_ids),)) return None @autocommit def disable_tasks(self, task_ids, cursor=None): """Disable the tasks whose ids are listed.""" return self.set_status_tasks(task_ids) @autocommit def get_tasks(self, task_ids, cursor=None): """Retrieve the info of tasks whose ids are listed.""" query = self._format_query('select {keys} from task where id in %s', self.task_keys) cursor.execute(query, (tuple(task_ids),)) return cursor.fetchall() @autocommit def peek_ready_tasks(self, task_type, timestamp=None, num_tasks=None, num_tasks_priority=None, cursor=None): """Fetch the list of ready tasks Args: task_type (str): filtering task per their type timestamp (datetime.datetime): peek tasks that need to be executed before that timestamp num_tasks (int): only peek at num_tasks tasks (with no priority) num_tasks_priority (int): only peek at num_tasks_priority tasks (with priority) Returns: a list of tasks """ if timestamp is None: timestamp = utcnow() cursor.execute( '''select * from swh_scheduler_peek_ready_tasks( %s, %s, %s :: bigint, %s :: bigint)''', (task_type, timestamp, num_tasks, num_tasks_priority) ) return cursor.fetchall() @autocommit def grab_ready_tasks(self, task_type, timestamp=None, num_tasks=None, num_tasks_priority=None, cursor=None): """Fetch the list of ready tasks, and mark them as scheduled Args: task_type (str): filtering task per their type timestamp (datetime.datetime): grab tasks that need to be executed before that timestamp num_tasks (int): only grab num_tasks tasks (with no priority) num_tasks_priority (int): only grab oneshot num_tasks tasks (with priorities) Returns: a list of tasks """ if timestamp is None: timestamp = utcnow() cursor.execute( '''select * from swh_scheduler_grab_ready_tasks( %s, %s, %s :: bigint, %s :: bigint)''', (task_type, timestamp, num_tasks, num_tasks_priority) ) return cursor.fetchall() task_run_create_keys = ['task', 'backend_id', 'scheduled', 'metadata'] @autocommit def schedule_task_run(self, task_id, backend_id, metadata=None, timestamp=None, cursor=None): """Mark a given task as scheduled, adding a task_run entry in the database. Args: task_id (int): the identifier for the task being scheduled backend_id (str): the identifier of the job in the backend metadata (dict): metadata to add to the task_run entry timestamp (datetime.datetime): the instant the event occurred Returns: a fresh task_run entry """ if metadata is None: metadata = {} if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_schedule_task_run(%s, %s, %s, %s)', (task_id, backend_id, metadata, timestamp) ) return cursor.fetchone() @autocommit def mass_schedule_task_runs(self, task_runs, cursor=None): """Schedule a bunch of task runs. Args: task_runs (list): a list of dicts with keys: - task (int): the identifier for the task being scheduled - backend_id (str): the identifier of the job in the backend - metadata (dict): metadata to add to the task_run entry - scheduled (datetime.datetime): the instant the event occurred Returns: None """ cursor.execute('select swh_scheduler_mktemp_task_run()') self.copy_to(task_runs, 'tmp_task_run', self.task_run_create_keys, cursor=cursor) cursor.execute('select swh_scheduler_schedule_task_run_from_temp()') @autocommit def start_task_run(self, backend_id, metadata=None, timestamp=None, cursor=None): """Mark a given task as started, updating the corresponding task_run entry in the database. Args: backend_id (str): the identifier of the job in the backend metadata (dict): metadata to add to the task_run entry timestamp (datetime.datetime): the instant the event occurred Returns: the updated task_run entry """ if metadata is None: metadata = {} if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_start_task_run(%s, %s, %s)', (backend_id, metadata, timestamp) ) return cursor.fetchone() @autocommit def end_task_run(self, backend_id, status, metadata=None, timestamp=None, result=None, cursor=None): """Mark a given task as ended, updating the corresponding task_run entry in the database. Args: backend_id (str): the identifier of the job in the backend status (str): how the task ended; one of: 'eventful', 'uneventful', 'failed' metadata (dict): metadata to add to the task_run entry timestamp (datetime.datetime): the instant the event occurred Returns: the updated task_run entry """ if metadata is None: metadata = {} if timestamp is None: timestamp = utcnow() cursor.execute( 'select * from swh_scheduler_end_task_run(%s, %s, %s, %s)', (backend_id, status, metadata, timestamp) ) return cursor.fetchone() @autocommit def filter_task_to_archive(self, after_ts, before_ts, limit=10, last_id=-1, cursor=None): """Returns the list of task/task_run prior to a given date to archive. """ last_task_run_id = None while True: row = None cursor.execute( "select * from swh_scheduler_task_to_archive(%s, %s, %s, %s)", (after_ts, before_ts, last_id, limit) ) for row in cursor: # nested type index does not accept bare values # transform it as a dict to comply with this row['arguments']['args'] = { i: v for i, v in enumerate(row['arguments']['args']) } kwargs = row['arguments']['kwargs'] row['arguments']['kwargs'] = json.dumps(kwargs) yield row if not row: break _id = row.get('task_id') _task_run_id = row.get('task_run_id') if last_id == _id and last_task_run_id == _task_run_id: break last_id = _id last_task_run_id = _task_run_id @autocommit def delete_archived_tasks(self, task_ids, cursor=None): """Delete archived tasks as much as possible. Only the task_ids whose complete associated task_run have been cleaned up will be. """ _task_ids = _task_run_ids = [] for task_id in task_ids: _task_ids.append(task_id['task_id']) _task_run_ids.append(task_id['task_run_id']) cursor.execute( "select * from swh_scheduler_delete_archived_tasks(%s, %s)", (_task_ids, _task_run_ids)) diff --git a/swh/scheduler/celery_backend/config.py b/swh/scheduler/celery_backend/config.py index b31a6f6..6bed5d0 100644 --- a/swh/scheduler/celery_backend/config.py +++ b/swh/scheduler/celery_backend/config.py @@ -1,203 +1,257 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information +import itertools +import importlib import logging import os import urllib.parse from celery import Celery -from celery.signals import setup_logging +from celery.signals import setup_logging, celeryd_after_setup from celery.utils.log import ColorFormatter from celery.worker.control import Panel from kombu import Exchange, Queue from kombu.five import monotonic as _monotonic import requests +from swh.scheduler.task import Task + from swh.core.config import load_named_config from swh.core.logger import JournalHandler DEFAULT_CONFIG_NAME = 'worker' CONFIG_NAME_ENVVAR = 'SWH_WORKER_INSTANCE' CONFIG_NAME_TEMPLATE = 'worker/%s' DEFAULT_CONFIG = { 'task_broker': ('str', 'amqp://guest@localhost//'), 'task_modules': ('list[str]', []), 'task_queues': ('list[str]', []), 'task_soft_time_limit': ('int', 0), } @setup_logging.connect def setup_log_handler(loglevel=None, logfile=None, format=None, colorize=None, **kwargs): """Setup logging according to Software Heritage preferences. We use the command-line loglevel for tasks only, as we never really care about the debug messages from celery. """ if loglevel is None: loglevel = logging.DEBUG formatter = logging.Formatter(format) root_logger = logging.getLogger('') root_logger.setLevel(logging.INFO) if loglevel == logging.DEBUG: color_formatter = ColorFormatter(format) if colorize else formatter console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(color_formatter) root_logger.addHandler(console) systemd_journal = JournalHandler() systemd_journal.setLevel(logging.DEBUG) systemd_journal.setFormatter(formatter) root_logger.addHandler(systemd_journal) celery_logger = logging.getLogger('celery') celery_logger.setLevel(logging.INFO) # Silence useless "Starting new HTTP connection" messages urllib3_logger = logging.getLogger('urllib3') urllib3_logger.setLevel(logging.WARNING) swh_logger = logging.getLogger('swh') swh_logger.setLevel(loglevel) # get_task_logger makes the swh tasks loggers children of celery.task celery_task_logger = logging.getLogger('celery.task') celery_task_logger.setLevel(loglevel) +@celeryd_after_setup.connect +def setup_queues_and_tasks(sender, instance, **kwargs): + """Signal called on worker start. + + This automatically registers swh.scheduler.task.Task subclasses as + available celery tasks. + + This also subscribes the worker to the "implicit" per-task queues defined + for these task classes. + + """ + + for module_name in itertools.chain( + # celery worker -I flag + instance.app.conf['include'], + # set from the celery / swh worker instance configuration file + instance.app.conf['imports'], + ): + module = importlib.import_module(module_name) + for name in dir(module): + obj = getattr(module, name) + if ( + isinstance(obj, type) + and issubclass(obj, Task) + and obj != Task # Don't register the abstract class itself + ): + class_name = '%s.%s' % (module_name, name) + instance.app.register_task_class(class_name, obj) + + for task_name in instance.app.tasks: + if task_name.startswith('swh.'): + instance.app.amqp.queues.select_add(task_name) + + @Panel.register def monotonic(state): """Get the current value for the monotonic clock""" return {'monotonic': _monotonic()} class TaskRouter: """Route tasks according to the task_queue attribute in the task class""" - def route_for_task(self, task, args=None, kwargs=None): - task_class = app.tasks[task] - if hasattr(task_class, 'task_queue'): - return {'queue': task_class.task_queue} - return None + def route_for_task(self, task, *args, **kwargs): + if task.startswith('swh.'): + return {'queue': task} class CustomCelery(Celery): def get_queue_stats(self, queue_name): """Get the statistics regarding a queue on the broker. Arguments: queue_name: name of the queue to check - Returns a dictionary raw from the RabbitMQ management API. + Returns a dictionary raw from the RabbitMQ management API; + or `None` if the current configuration does not use RabbitMQ. Interesting keys: - consumers (number of consumers for the queue) - messages (number of messages in queue) - messages_unacknowledged (number of messages currently being processed) Documentation: https://www.rabbitmq.com/management.html#http-api """ conn_info = self.connection().info() + if conn_info['transport'] == 'memory': + # We're running in a test environment, without RabbitMQ. + return None url = 'http://{hostname}:{port}/api/queues/{vhost}/{queue}'.format( hostname=conn_info['hostname'], port=conn_info['port'] + 10000, vhost=urllib.parse.quote(conn_info['virtual_host'], safe=''), queue=urllib.parse.quote(queue_name, safe=''), ) credentials = (conn_info['userid'], conn_info['password']) r = requests.get(url, auth=credentials) + if r.status_code == 404: + return {} if r.status_code != 200: raise ValueError('Got error %s when reading queue stats: %s' % ( r.status_code, r.json())) return r.json() def get_queue_length(self, queue_name): """Shortcut to get a queue's length""" - return self.get_queue_stats(queue_name)['messages'] + stats = self.get_queue_stats(queue_name) + if stats: + return stats.get('messages') + + def register_task_class(self, name, cls): + """Register a class-based task under the given name""" + if name in self.tasks: + return + + task_instance = cls() + task_instance.name = name + self.register_task(task_instance) INSTANCE_NAME = os.environ.get(CONFIG_NAME_ENVVAR) if INSTANCE_NAME: CONFIG_NAME = CONFIG_NAME_TEMPLATE % INSTANCE_NAME else: CONFIG_NAME = DEFAULT_CONFIG_NAME # Load the Celery config CONFIG = load_named_config(CONFIG_NAME, DEFAULT_CONFIG) # Celery Queues CELERY_QUEUES = [Queue('celery', Exchange('celery'), routing_key='celery')] for queue in CONFIG['task_queues']: CELERY_QUEUES.append(Queue(queue, Exchange(queue), routing_key=queue)) # Instantiate the Celery app app = CustomCelery() app.conf.update( # The broker - BROKER_URL=CONFIG['task_broker'], + broker_url=CONFIG['task_broker'], # Timezone configuration: all in UTC - CELERY_ENABLE_UTC=True, - CELERY_TIMEZONE='UTC', + enable_utc=True, + timezone='UTC', # Imported modules - CELERY_IMPORTS=CONFIG['task_modules'], + imports=CONFIG['task_modules'], # Time (in seconds, or a timedelta object) for when after stored task # tombstones will be deleted. None means to never expire results. - CELERY_TASK_RESULT_EXPIRES=None, + result_expires=None, # A string identifying the default serialization method to use. Can # be json (default), pickle, yaml, msgpack, or any custom # serialization methods that have been registered with - CELERY_TASK_SERIALIZER='msgpack', + task_serializer='msgpack', # Result serialization format - CELERY_RESULT_SERIALIZER='msgpack', + result_serializer='msgpack', # Late ack means the task messages will be acknowledged after the task has # been executed, not just before, which is the default behavior. - CELERY_ACKS_LATE=True, + task_acks_late=True, # A string identifying the default serialization method to use. # Can be pickle (default), json, yaml, msgpack or any custom serialization # methods that have been registered with kombu.serialization.registry - CELERY_ACCEPT_CONTENT=['msgpack', 'json', 'pickle'], + accept_content=['msgpack', 'json'], # If True the task will report its status as “started” # when the task is executed by a worker. - CELERY_TRACK_STARTED=True, + task_track_started=True, # Default compression used for task messages. Can be gzip, bzip2 # (if available), or any custom compression schemes registered # in the Kombu compression registry. - # CELERY_MESSAGE_COMPRESSION='bzip2', + # result_compression='bzip2', + # task_compression='bzip2', # Disable all rate limits, even if tasks has explicit rate limits set. # (Disabling rate limits altogether is recommended if you don’t have any # tasks using them.) - CELERY_DISABLE_RATE_LIMITS=True, + worker_disable_rate_limits=True, # Task hard time limit in seconds. The worker processing the task will be # killed and replaced with a new one when this is exceeded. - # CELERYD_TASK_TIME_LIMIT=3600, + # task_time_limit=3600, # Task soft time limit in seconds. # The SoftTimeLimitExceeded exception will be raised when this is exceeded. # The task can catch this to e.g. clean up before the hard time limit # comes. - CELERYD_TASK_SOFT_TIME_LIMIT=CONFIG['task_soft_time_limit'], + task_soft_time_limit=CONFIG['task_soft_time_limit'], # Task routing - CELERY_ROUTES=TaskRouter(), + task_routes=TaskRouter(), # Task queues this worker will consume from - CELERY_QUEUES=CELERY_QUEUES, + task_queues=CELERY_QUEUES, # Allow pool restarts from remote - CELERYD_POOL_RESTARTS=True, + worker_pool_restarts=True, # Do not prefetch tasks - CELERYD_PREFETCH_MULTIPLIER=1, + worker_prefetch_multiplier=1, # Send events - CELERY_SEND_EVENTS=True, + worker_send_task_events=True, # Do not send useless task_sent events - CELERY_SEND_TASK_SENT_EVENT=False, + task_send_sent_event=False, ) diff --git a/swh/scheduler/celery_backend/runner.py b/swh/scheduler/celery_backend/runner.py index bae11d8..ff9ae6c 100644 --- a/swh/scheduler/celery_backend/runner.py +++ b/swh/scheduler/celery_backend/runner.py @@ -1,105 +1,111 @@ # Copyright (C) 2015-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import arrow -from celery import group from swh.scheduler import get_scheduler, compute_nb_tasks_from from .config import app as main_app # Max batch size for tasks MAX_NUM_TASKS = 10000 def run_ready_tasks(backend, app): """Run tasks that are ready - Args + Args: backend (Scheduler): backend to read tasks to schedule app (App): Celery application to send tasks to Returns: - A list of dictionaries: - { + A list of dictionaries:: + + { 'task': the scheduler's task id, 'backend_id': Celery's task id, 'scheduler': arrow.utcnow() - } + } - The result can be used to block-wait for the tasks' results: + The result can be used to block-wait for the tasks' results:: - backend_tasks = run_ready_tasks(self.scheduler, app) - for task in backend_tasks: - AsyncResult(id=task['backend_id']).get() + backend_tasks = run_ready_tasks(self.scheduler, app) + for task in backend_tasks: + AsyncResult(id=task['backend_id']).get() """ all_backend_tasks = [] while True: cursor = backend.cursor() task_types = {} pending_tasks = [] for task_type in backend.get_task_types(cursor=cursor): task_type_name = task_type['type'] task_types[task_type_name] = task_type max_queue_length = task_type['max_queue_length'] backend_name = task_type['backend_name'] - if max_queue_length and backend_name in app.tasks: - queue_name = app.tasks[backend_name].task_queue - queue_length = app.get_queue_length(queue_name) - num_tasks = min(max_queue_length - queue_length, - MAX_NUM_TASKS) + if max_queue_length: + try: + queue_length = app.get_queue_length(backend_name) + except ValueError: + queue_length = None + + if queue_length is None: + # Running without RabbitMQ (probably a test env). + num_tasks = MAX_NUM_TASKS + else: + num_tasks = min(max_queue_length - queue_length, + MAX_NUM_TASKS) else: num_tasks = MAX_NUM_TASKS if num_tasks > 0: num_tasks, num_tasks_priority = compute_nb_tasks_from( num_tasks) pending_tasks.extend( backend.grab_ready_tasks( task_type_name, num_tasks=num_tasks, num_tasks_priority=num_tasks_priority, cursor=cursor)) if not pending_tasks: return all_backend_tasks - celery_tasks = [] + backend_tasks = [] for task in pending_tasks: args = task['arguments']['args'] kwargs = task['arguments']['kwargs'] - celery_task = app.tasks[ - task_types[task['type']]['backend_name'] - ].s(*args, **kwargs) - - celery_tasks.append(celery_task) + backend_name = task_types[task['type']]['backend_name'] + celery_result = app.send_task( + backend_name, args=args, kwargs=kwargs, + ) - group_result = group(celery_tasks).delay() + data = { + 'task': task['id'], + 'backend_id': celery_result.id, + 'scheduled': arrow.utcnow(), + } - backend_tasks = [{ - 'task': task['id'], - 'backend_id': group_result.results[i].id, - 'scheduled': arrow.utcnow(), - } for i, task in enumerate(pending_tasks)] + backend_tasks.append(data) backend.mass_schedule_task_runs(backend_tasks, cursor=cursor) backend.commit() all_backend_tasks.extend(backend_tasks) if __name__ == '__main__': for module in main_app.conf.CELERY_IMPORTS: __import__(module) main_backend = get_scheduler('local') try: run_ready_tasks(main_backend, main_app) except Exception: main_backend.rollback() raise diff --git a/swh/scheduler/cli.py b/swh/scheduler/cli.py index 7ec6258..f806071 100644 --- a/swh/scheduler/cli.py +++ b/swh/scheduler/cli.py @@ -1,308 +1,363 @@ # Copyright (C) 2016-2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import arrow import click import csv import itertools import json import locale import logging from swh.core import utils from . import compute_nb_tasks_from from .backend_es import SWHElasticSearchClient locale.setlocale(locale.LC_ALL, '') ARROW_LOCALE = locale.getlocale(locale.LC_TIME)[0] class DateTimeType(click.ParamType): name = 'time and date' def convert(self, value, param, ctx): if not isinstance(value, arrow.Arrow): value = arrow.get(value) return value DATETIME = DateTimeType() CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) def pretty_print_list(list, indent): """Pretty-print a list""" return ''.join('%s%s\n' % (' ' * indent, item) for item in list) def pretty_print_dict(dict, indent): """Pretty-print a list""" return ''.join('%s%s: %s\n' % (' ' * indent, click.style(key, bold=True), value) for key, value in dict.items()) def pretty_print_task(task): """Pretty-print a task""" next_run = arrow.get(task['next_run']) lines = [ '%s %s\n' % (click.style('Task', bold=True), task['id']), click.style(' Next run: ', bold=True), "%s (%s)" % (next_run.humanize(locale=ARROW_LOCALE), next_run.format()), '\n', click.style(' Interval: ', bold=True), str(task['current_interval']), '\n', click.style(' Type: ', bold=True), task['type'], '\n', click.style(' Policy: ', bold=True), task['policy'], '\n', click.style(' Args:\n', bold=True), pretty_print_list(task['arguments']['args'], indent=4), click.style(' Keyword args:\n', bold=True), pretty_print_dict(task['arguments']['kwargs'], indent=4), ] return ''.join(lines) +def list_task_types(ctx, param, value): + if not value or ctx.resilient_parsing: + return + click.echo("Known task types:") + for tasktype in ctx.obj.get_task_types(): + click.echo('{type}:\n {description}'.format(**tasktype)) + ctx.exit() + + @click.group(context_settings=CONTEXT_SETTINGS) @click.option('--cls', '-c', default='local', help="Scheduler's class, default to 'local'") @click.option('--database', '-d', help='Scheduling database DSN') @click.option('--url', '-u', help="(Optional) Scheduler's url access") @click.pass_context def cli(ctx, cls, database, url): """Software Heritage Scheduler CLI interface Default to use the the local scheduler instance (plugged to the main scheduler db). """ scheduler = None override_config = {} from . import get_scheduler if cls == 'local': if database: override_config = {'scheduling_db': database} scheduler = get_scheduler(cls, args=override_config) elif cls == 'remote': if url: override_config = {'url': url} scheduler = get_scheduler(cls, args=override_config) if not scheduler: raise ValueError('Scheduler class (local/remote) must be instantiated') ctx.obj = scheduler @cli.group('task') +@click.option('--list-types', '-l', is_flag=True, default=False, is_eager=True, + expose_value=False, callback=list_task_types) @click.pass_context def task(ctx): """Manipulate tasks.""" pass @task.command('schedule') @click.option('--columns', '-c', multiple=True, default=['type', 'args', 'kwargs', 'next_run'], type=click.Choice([ 'type', 'args', 'kwargs', 'policy', 'next_run']), help='columns present in the CSV file') @click.option('--delimiter', '-d', default=',') @click.argument('file', type=click.File(encoding='utf-8')) @click.pass_context def schedule_tasks(ctx, columns, delimiter, file): """Schedule tasks from a CSV input file. The following columns are expected, and can be set through the -c option: - type: the type of the task to be scheduled (mandatory) - args: the arguments passed to the task (JSON list, defaults to an empty list) - kwargs: the keyword arguments passed to the task (JSON object, defaults to an empty dict) - next_run: the date at which the task should run (datetime, defaults to now) The CSV can be read either from a named file, or from stdin (use - as filename). Use sample: cat scheduling-task.txt | \ python3 -m swh.scheduler.cli \ --database 'service=swh-scheduler-dev' \ task schedule \ --columns type --columns kwargs --columns policy \ --delimiter ';' - """ tasks = [] now = arrow.utcnow() reader = csv.reader(file, delimiter=delimiter) for line in reader: task = dict(zip(columns, line)) args = json.loads(task.pop('args', '[]')) kwargs = json.loads(task.pop('kwargs', '{}')) task['arguments'] = { 'args': args, 'kwargs': kwargs, } task['next_run'] = DATETIME.convert(task.get('next_run', now), None, None) tasks.append(task) created = ctx.obj.create_tasks(tasks) output = [ 'Created %d tasks\n' % len(created), ] for task in created: output.append(pretty_print_task(task)) click.echo_via_pager('\n'.join(output)) +@task.command('add') +@click.argument('type', nargs=1, required=True) +@click.argument('options', nargs=-1) +@click.option('--policy', '-p', default='recurring', + type=click.Choice(['recurring', 'oneshot'])) +@click.option('--next-run', '-n', default=None) +@click.pass_context +def schedule_task(ctx, type, options, policy, next_run): + """Schedule one task from arguments. + + Use sample: + + swh-scheduler --database 'service=swh-scheduler' \ + task add swh-lister-pypi + + swh-scheduler --database 'service=swh-scheduler' \ + task add swh-lister-debian --policy=oneshot distribution=stretch + + """ + now = arrow.utcnow() + + args = [x for x in options if '=' not in x] + kw = dict(x.split('=', 1) for x in options if '=' in x) + task = {'type': type, + 'policy': policy, + 'arguments': { + 'args': args, + 'kwargs': kw, + }, + 'next_run': DATETIME.convert(next_run or now, + None, None), + } + created = ctx.obj.create_tasks([task]) + + output = [ + 'Created %d tasks\n' % len(created), + ] + for task in created: + output.append(pretty_print_task(task)) + + click.echo('\n'.join(output)) + + @task.command('list-pending') -@click.option('--task-type', '-t', required=True, - help='The tasks\' type concerned by the listing') +@click.argument('task-types', required=True, nargs=-1) @click.option('--limit', '-l', required=False, type=click.INT, help='The maximum number of tasks to fetch') @click.option('--before', '-b', required=False, type=DATETIME, help='List all jobs supposed to run before the given date') @click.pass_context -def list_pending_tasks(ctx, task_type, limit, before): +def list_pending_tasks(ctx, task_types, limit, before): """List the tasks that are going to be run. You can override the number of tasks to fetch """ num_tasks, num_tasks_priority = compute_nb_tasks_from(limit) - pending = ctx.obj.peek_ready_tasks( - task_type, timestamp=before, - num_tasks=num_tasks, num_tasks_priority=num_tasks_priority) - output = [ - 'Found %d tasks\n' % len(pending) - ] - for task in pending: - output.append(pretty_print_task(task)) + output = [] + for task_type in task_types: + pending = ctx.obj.peek_ready_tasks( + task_type, timestamp=before, + num_tasks=num_tasks, num_tasks_priority=num_tasks_priority) + output.append('Found %d %s tasks\n' % ( + len(pending), task_type)) - click.echo_via_pager('\n'.join(output)) + for task in pending: + output.append(pretty_print_task(task)) + + click.echo('\n'.join(output)) @task.command('archive') @click.option('--before', '-b', default=None, help='''Task whose ended date is anterior will be archived. Default to current month's first day.''') @click.option('--after', '-a', default=None, help='''Task whose ended date is after the specified date will be archived. Default to prior month's first day.''') @click.option('--batch-index', default=1000, type=click.INT, help='Batch size of tasks to read from db to archive') @click.option('--bulk-index', default=200, type=click.INT, help='Batch size of tasks to bulk index') @click.option('--batch-clean', default=1000, type=click.INT, help='Batch size of task to clean after archival') @click.option('--dry-run/--no-dry-run', is_flag=True, default=False, help='Default to list only what would be archived.') @click.option('--verbose', is_flag=True, default=False, help='Default to list only what would be archived.') @click.option('--cleanup/--no-cleanup', is_flag=True, default=True, help='Clean up archived tasks (default)') @click.option('--start-from', type=click.INT, default=-1, help='(Optional) default task id to start from. Default is -1.') @click.pass_context def archive_tasks(ctx, before, after, batch_index, bulk_index, batch_clean, dry_run, verbose, cleanup, start_from): """Archive task/task_run whose (task_type is 'oneshot' and task_status is 'completed') or (task_type is 'recurring' and task_status is 'disabled'). With --dry-run flag set (default), only list those. """ es_client = SWHElasticSearchClient() logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) log = logging.getLogger('swh.scheduler.cli.archive') logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('elasticsearch').setLevel(logging.WARN) if dry_run: log.info('**DRY-RUN** (only reading db)') if not cleanup: log.info('**NO CLEANUP**') now = arrow.utcnow() # Default to archive tasks from a rolling month starting the week # prior to the current one if not before: before = now.shift(weeks=-1).format('YYYY-MM-DD') if not after: after = now.shift(weeks=-1).shift(months=-1).format('YYYY-MM-DD') log.debug('index: %s; cleanup: %s; period: [%s ; %s]' % ( not dry_run, not dry_run and cleanup, after, before)) def group_by_index_name(data, es_client=es_client): """Given a data record, determine the index's name through its ending date. This varies greatly depending on the task_run's status. """ date = data.get('started') if not date: date = data['scheduled'] return es_client.compute_index_name(date.year, date.month) def index_data(before, last_id, batch_index, backend=ctx.obj): tasks_in = backend.filter_task_to_archive( after, before, last_id=last_id, limit=batch_index) for index_name, tasks_group in itertools.groupby( tasks_in, key=group_by_index_name): log.debug('Index tasks to %s' % index_name) if dry_run: for task in tasks_group: yield task continue yield from es_client.streaming_bulk( index_name, tasks_group, source=['task_id', 'task_run_id'], chunk_size=bulk_index, log=log) gen = index_data(before, last_id=start_from, batch_index=batch_index) if cleanup: for task_ids in utils.grouper(gen, n=batch_clean): task_ids = list(task_ids) log.info('Clean up %s tasks: [%s, ...]' % ( len(task_ids), task_ids[0])) if dry_run: # no clean up continue ctx.obj.delete_archived_tasks(task_ids) else: for task_ids in utils.grouper(gen, n=batch_index): task_ids = list(task_ids) log.info('Indexed %s tasks: [%s, ...]' % ( len(task_ids), task_ids[0])) @cli.group('task-run') @click.pass_context def task_run(ctx): """Manipulate task runs.""" pass if __name__ == '__main__': cli() diff --git a/swh/scheduler/sql/40-swh-data.sql b/swh/scheduler/sql/40-swh-data.sql index b41ed1b..59279d6 100644 --- a/swh/scheduler/sql/40-swh-data.sql +++ b/swh/scheduler/sql/40-swh-data.sql @@ -1,246 +1,286 @@ insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'swh-loader-mount-dump-and-load-svn-repository', 'Loading svn repositories from svn dump', 'swh.loader.svn.tasks.MountAndLoadSvnRepository', '1 day', '1 day', '1 day', 1, 1000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'origin-update-svn', 'Create dump of a remote svn repository, mount it and load it', 'swh.loader.svn.tasks.DumpMountAndLoadSvnRepository', '1 day', '1 day', '1 day', 1, 1000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, num_retries, max_queue_length) values ( 'swh-deposit-archive-loading', 'Loading deposit archive into swh through swh-loader-tar', 'swh.deposit.loader.tasks.LoadDepositArchiveTsk', '1 day', '1 day', '1 day', 1, 3, 1000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, num_retries, max_queue_length) values ( 'swh-deposit-archive-checks', 'Pre-checking deposit step before loading into swh archive', 'swh.deposit.loader.tasks.ChecksDepositTsk', '1 day', '1 day', '1 day', 1, 3, 1000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'swh-vault-cooking', 'Cook a Vault bundle', 'swh.vault.cooking_tasks.SWHCookingTask', '1 day', '1 day', '1 day', 1, 10000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'origin-update-hg', 'Loading mercurial repository swh-loader-mercurial', 'swh.loader.mercurial.tasks.LoadMercurial', '1 day', '1 day', '1 day', 1, 1000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'origin-load-archive-hg', 'Loading archive mercurial repository swh-loader-mercurial', 'swh.loader.mercurial.tasks.LoadArchiveMercurial', '1 day', '1 day', '1 day', 1, 1000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'origin-update-git', 'Update an origin of type git', 'swh.loader.git.tasks.UpdateGitRepository', '64 days', '12:00:00', '64 days', 2, 5000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor) values ( 'swh-lister-github-incremental', 'Incrementally list GitHub', 'swh.lister.github.tasks.IncrementalGitHubLister', '1 day', '1 day', '1 day', 1); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor) values ( 'swh-lister-github-full', 'Full update of GitHub repos list', 'swh.lister.github.tasks.FullGitHubRelister', '90 days', '90 days', '90 days', 1); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor) values ( 'swh-lister-debian', 'List a Debian distribution', 'swh.lister.debian.tasks.DebianListerTask', '1 day', '1 day', '1 day', 1); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor) values ( 'swh-lister-gitlab-incremental', 'Incrementally list a Gitlab instance', 'swh.lister.gitlab.tasks.IncrementalGitLabLister', '1 day', '1 day', '1 day', 1); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor) values ( 'swh-lister-gitlab-full', 'Full update of a Gitlab instance''s repos list', 'swh.lister.gitlab.tasks.FullGitLabRelister', '90 days', '90 days', '90 days', 1); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor) values ( 'swh-lister-pypi', 'Full pypi lister', 'swh.lister.pypi.tasks.PyPIListerTask', '1 days', '1 days', '1 days', 1); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( 'origin-update-pypi', 'Load Pypi origin', 'swh.loader.pypi.tasks.LoadPyPI', '64 days', '12:00:00', '64 days', 2, 5000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( - 'orchestrator', - 'swh.indexer orchestrator task', - 'swh.indexer.tasks.OrchestratorAllContents', + 'indexer_mimetype', + 'Mimetype indexer task', + 'swh.indexer.tasks.ContentMimetype', '1 day', '12:00:00', '1 days', 2, 5000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( - 'orchestrator_text', - 'swh.indexer text orchestrator task', - 'swh.indexer.tasks.OrchestratorTextContents', + 'indexer_range_mimetype', + 'Mimetype Range indexer task', + 'swh.indexer.tasks.ContentRangeMimetype', '1 day', '12:00:00', '1 days', 2, 5000); + insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( - 'indexer_mimetype', - 'Mimetype indexer task', - 'swh.indexer.tasks.ContentMimetype', + 'indexer_fossology_license', + 'Fossology license indexer task', + 'swh.indexer.tasks.ContentFossologyLicense', '1 day', '12:00:00', '1 days', 2, 5000); insert into task_type( type, description, backend_name, default_interval, min_interval, max_interval, backoff_factor, max_queue_length) values ( - 'indexer_fossology_license', - 'Fossology license indexer task', - 'swh.indexer.tasks.ContentFossologyLicense', + 'indexer_range_fossology_license', + 'Fossology license range indexer task', + 'swh.indexer.tasks.ContentRangeFossologyLicense', + '1 day', '12:00:00', '1 days', 2, + 5000); + +insert into task_type( + type, + description, + backend_name, + default_interval, min_interval, max_interval, backoff_factor, + max_queue_length) +values ( + 'indexer_origin_head', + 'Origin Head indexer task', + 'swh.indexer.tasks.OriginHead', + '1 day', '12:00:00', '1 days', 2, + 5000); + +insert into task_type( + type, + description, + backend_name, + default_interval, min_interval, max_interval, backoff_factor, + max_queue_length) +values ( + 'indexer_revision_metadata', + 'Revision Metadata indexer task', + 'swh.indexer.tasks.RevisionMetadata', + '1 day', '12:00:00', '1 days', 2, + 5000); + +insert into task_type( + type, + description, + backend_name, + default_interval, min_interval, max_interval, backoff_factor, + max_queue_length) +values ( + 'indexer_origin_metadata', + 'Origin Metadata indexer task', + 'swh.indexer.tasks.OriginMetadata', '1 day', '12:00:00', '1 days', 2, 5000); diff --git a/swh/scheduler/task.py b/swh/scheduler/task.py index a6d1b38..0bea878 100644 --- a/swh/scheduler/task.py +++ b/swh/scheduler/task.py @@ -1,179 +1,50 @@ # Copyright (C) 2015-2017 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import celery.app.task from celery.utils.log import get_task_logger -from celery.app.task import TaskType -if TaskType is type: - # From Celery 3.1.25, celery/celery/app/task.py - # Copyright (c) 2015 Ask Solem & contributors. All rights reserved. - # Copyright (c) 2012-2014 GoPivotal, Inc. All rights reserved. - # Copyright (c) 2009, 2010, 2011, 2012 Ask Solem, and individual - # contributors. All rights reserved. - # - # Redistribution and use in source and binary forms, with or without - # modification, are permitted provided that the following conditions are - # met: - # * Redistributions of source code must retain the above copyright - # notice, this list of conditions and the following disclaimer. - # * Redistributions in binary form must reproduce the above copyright - # notice, this list of conditions and the following disclaimer in the - # documentation and/or other materials provided with the - # distribution. - # * Neither the name of Ask Solem, nor the names of its contributors - # may be used to endorse or promote products derived from this - # software without specific prior written permission. - # - # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Ask Solem OR CONTRIBUTORS BE - # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - # THE POSSIBILITY OF SUCH DAMAGE. - from celery import current_app - from celery.local import Proxy - from celery.utils import gen_task_name - - class _CompatShared(object): - - def __init__(self, name, cons): - self.name = name - self.cons = cons - - def __hash__(self): - return hash(self.name) - - def __repr__(self): - return '' % (self.name, ) - - def __call__(self, app): - return self.cons(app) - - class TaskType(type): - """Meta class for tasks. - - Automatically registers the task in the task registry (except if the - :attr:`Task.abstract`` attribute is set). - - If no :attr:`Task.name` attribute is provided, then the name is - generated from the module and class name. - - """ - _creation_count = {} # used by old non-abstract task classes - - def __new__(cls, name, bases, attrs): - new = super(TaskType, cls).__new__ - task_module = attrs.get('__module__') or '__main__' - - # - Abstract class: abstract attribute should not be inherited. - abstract = attrs.pop('abstract', None) - if abstract or not attrs.get('autoregister', True): - return new(cls, name, bases, attrs) - - # The 'app' attribute is now a property, with the real app located - # in the '_app' attribute. Previously this was a regular attribute, - # so we should support classes defining it. - app = attrs.pop('_app', None) or attrs.pop('app', None) - - # Attempt to inherit app from one the bases - if not isinstance(app, Proxy) and app is None: - for base in bases: - if getattr(base, '_app', None): - app = base._app - break - else: - app = current_app._get_current_object() - attrs['_app'] = app - - # - Automatically generate missing/empty name. - task_name = attrs.get('name') - if not task_name: - attrs['name'] = task_name = gen_task_name(app, name, - task_module) - - if not attrs.get('_decorated'): - # non decorated tasks must also be shared in case - # an app is created multiple times due to modules - # imported under multiple names. - # Hairy stuff, here to be compatible with 2.x. - # People should not use non-abstract task classes anymore, - # use the task decorator. - from celery._state import connect_on_app_finalize - unique_name = '.'.join([task_module, name]) - if unique_name not in cls._creation_count: - # the creation count is used as a safety - # so that the same task is not added recursively - # to the set of constructors. - cls._creation_count[unique_name] = 1 - connect_on_app_finalize(_CompatShared( - unique_name, - lambda app: TaskType.__new__(cls, name, bases, - dict(attrs, _app=app)), - )) - - # - Create and register class. - # Because of the way import happens (recursively) - # we may or may not be the first time the task tries to register - # with the framework. There should only be one class for each task - # name, so we always return the registered version. - tasks = app._tasks - if task_name not in tasks: - tasks.register(new(cls, name, bases, attrs)) - instance = tasks[task_name] - instance.bind(app) - return instance.__class__ - - -class Task(celery.app.task.Task, metaclass=TaskType): +class Task(celery.app.task.Task): """a schedulable task (abstract class) - Sub-classes must implement the run() method. Sub-classes that - want their tasks to get routed to a non-default task queue must - override the task_queue attribute. + Sub-classes must implement the run_task() method. Current implementation is based on Celery. See http://docs.celeryproject.org/en/latest/reference/celery.app.task.html for how to use tasks once instantiated """ abstract = True - task_queue = 'celery' def run(self, *args, **kwargs): """This method is called by the celery worker when a task is received. Should not be overridden as we need our special events to be sent for the reccurrent scheduler. Override run_task instead.""" try: result = self.run_task(*args, **kwargs) except Exception as e: self.send_event('task-result-exception') raise e from None else: self.send_event('task-result', result=result) return result def run_task(self, *args, **kwargs): """Perform the task. Must return a json-serializable value as it is passed back to the task scheduler using a celery event. """ raise NotImplementedError('tasks must implement the run_task() method') @property def log(self): if not hasattr(self, '__log'): self.__log = get_task_logger('%s.%s' % (__name__, self.__class__.__name__)) return self.__log diff --git a/swh/scheduler/tests/celery_testing.py b/swh/scheduler/tests/celery_testing.py index 2859e9c..acc8ad6 100644 --- a/swh/scheduler/tests/celery_testing.py +++ b/swh/scheduler/tests/celery_testing.py @@ -1,18 +1,18 @@ import os def setup_celery(): os.environ.setdefault('CELERY_BROKER_URL', 'memory://') os.environ.setdefault('CELERY_RESULT_BACKEND', 'cache+memory://') class CeleryTestFixture: """Mix this in a test subject class to setup Celery config for testing purpose. Can be overriden by CELERY_BROKER_URL and CELERY_RESULT_BACKEND env vars. """ - def setUp(sel): + def setUp(self): setup_celery() super().setUp() diff --git a/swh/scheduler/tests/scheduler_testing.py b/swh/scheduler/tests/scheduler_testing.py index ba11ec3..1fad1f6 100644 --- a/swh/scheduler/tests/scheduler_testing.py +++ b/swh/scheduler/tests/scheduler_testing.py @@ -1,71 +1,80 @@ import glob -import pytest import os.path import datetime from celery.result import AsyncResult from celery.contrib.testing.worker import start_worker import celery.contrib.testing.tasks # noqa +import pytest from swh.core.tests.db_testing import DbTestFixture, DB_DUMP_TYPES from swh.core.utils import numfile_sortkey as sortkey from swh.scheduler import get_scheduler from swh.scheduler.celery_backend.runner import run_ready_tasks from swh.scheduler.celery_backend.config import app from swh.scheduler.tests.celery_testing import CeleryTestFixture from . import SQL_DIR DUMP_FILES = os.path.join(SQL_DIR, '*.sql') @pytest.mark.db class SchedulerTestFixture(CeleryTestFixture, DbTestFixture): """Base class for test case classes, providing an SWH scheduler as the `scheduler` attribute.""" SCHEDULER_DB_NAME = 'softwareheritage-scheduler-test-fixture' - def add_scheduler_task_type(self, task_type, backend_name): + def add_scheduler_task_type(self, task_type, backend_name, + task_class=None): task_type = { 'type': task_type, 'description': 'Update a git repository', 'backend_name': backend_name, 'default_interval': datetime.timedelta(days=64), 'min_interval': datetime.timedelta(hours=12), 'max_interval': datetime.timedelta(days=64), 'backoff_factor': 2, 'max_queue_length': None, 'num_retries': 7, 'retry_delay': datetime.timedelta(hours=2), } self.scheduler.create_task_type(task_type) + if task_class: + app.register_task_class(backend_name, task_class) def run_ready_tasks(self): """Runs the scheduler and a Celery worker, then blocks until all tasks are completed.""" + + # Make sure the worker is listening to all task-specific queues + for task in self.scheduler.get_task_types(): + app.amqp.queues.select_add(task['backend_name']) + with start_worker(app): backend_tasks = run_ready_tasks(self.scheduler, app) for task in backend_tasks: + # Make sure the task completed AsyncResult(id=task['backend_id']).get() @classmethod def setUpClass(cls): all_dump_files = sorted(glob.glob(DUMP_FILES), key=sortkey) all_dump_files = [(x, DB_DUMP_TYPES[os.path.splitext(x)[1]]) for x in all_dump_files] cls.add_db(name=cls.SCHEDULER_DB_NAME, dumps=all_dump_files) super().setUpClass() def setUp(self): super().setUp() self.scheduler_config = { 'scheduling_db': 'dbname=' + self.SCHEDULER_DB_NAME} self.scheduler = get_scheduler('local', self.scheduler_config) def tearDown(self): self.scheduler.close_connection() super().tearDown() diff --git a/swh/scheduler/tests/test_fixtures.py b/swh/scheduler/tests/test_fixtures.py index 9e9146e..e69ac9d 100644 --- a/swh/scheduler/tests/test_fixtures.py +++ b/swh/scheduler/tests/test_fixtures.py @@ -1,38 +1,39 @@ # Copyright (C) 2018 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import unittest from swh.scheduler.tests.scheduler_testing import SchedulerTestFixture from swh.scheduler.task import Task from swh.scheduler.utils import create_task_dict task_has_run = False class SomeTestTask(Task): def run(self, *, foo): global task_has_run assert foo == 'bar' task_has_run = True class FixtureTest(SchedulerTestFixture, unittest.TestCase): def setUp(self): super().setUp() self.add_scheduler_task_type( 'some_test_task_type', - 'swh.scheduler.tests.test_fixtures.SomeTestTask') + 'swh.scheduler.tests.test_fixtures.SomeTestTask', + SomeTestTask, + ) def test_task_run(self): self.scheduler.create_tasks([create_task_dict( 'some_test_task_type', 'oneshot', foo='bar', )]) - self.assertEqual(task_has_run, False) self.run_ready_tasks() self.assertEqual(task_has_run, True) diff --git a/swh/scheduler/tests/test_task.py b/swh/scheduler/tests/test_task.py index 7e2130e..9abe842 100644 --- a/swh/scheduler/tests/test_task.py +++ b/swh/scheduler/tests/test_task.py @@ -1,28 +1,38 @@ # Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information import unittest +from celery import current_app as app + from swh.scheduler import task from .celery_testing import CeleryTestFixture class Task(CeleryTestFixture, unittest.TestCase): def test_not_implemented_task(self): class NotImplementedTask(task.Task): + name = 'NotImplementedTask' + pass + app.register_task(NotImplementedTask()) + with self.assertRaises(NotImplementedError): NotImplementedTask().run() def test_add_task(self): class AddTask(task.Task): + name = 'AddTask' + def run_task(self, x, y): return x + y + app.register_task(AddTask()) + r = AddTask().apply([2, 3]) self.assertTrue(r.successful()) self.assertEqual(r.result, 5) diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 70265ee..0000000 --- a/tox.ini +++ /dev/null @@ -1,17 +0,0 @@ -[tox] -envlist=flake8,py3 - -[testenv:py3] -deps = - .[testing] - pytest-cov - pifpaf -commands = - pifpaf run postgresql -- pytest --cov=swh --cov-branch {posargs} - -[testenv:flake8] -skip_install = true -deps = - flake8 -commands = - {envpython} -m flake8 diff --git a/version.txt b/version.txt index 83ca342..2fc4a81 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -v0.0.35-0-g762b528 \ No newline at end of file +v0.0.38-0-gb6bc2f2 \ No newline at end of file