├── .coveragerc
├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.md
├── ckanserviceprovider
├── __init__.py
├── db.py
├── default_settings.py
├── job.py
├── util.py
└── web.py
├── doc
├── Makefile
├── _themes
│ ├── LICENSE
│ ├── flask_small
│ │ ├── layout.html
│ │ ├── static
│ │ │ └── flasky.css_t
│ │ └── theme.conf
│ └── flask_theme_support.py
├── conf.py
└── index.rst
├── example
├── __init__.py
├── jobs.py
└── main.py
├── requirements-dev.txt
├── requirements.txt
├── setup.cfg
├── setup.py
└── tests
├── __init__.py
├── settings_test.py
├── test_db.py
├── test_joberror.py
└── test_web.py
/.coveragerc:
--------------------------------------------------------------------------------
1 | [run]
2 | source = ckanserviceprovider
3 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Tests
2 | on: [push, pull_request]
3 | jobs:
4 | test:
5 | strategy:
6 | matrix:
7 | python-version: [3.7, 3.8, 3.9, "3.10", "3.11"]
8 | fail-fast: false
9 | name: Python ${{ matrix.python-version }}
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v3
13 | - uses: actions/setup-python@v4
14 | with:
15 | python-version: ${{ matrix.python-version }}
16 | - name: Install requirements (Python 3)
17 | run: pip install -r requirements-dev.txt && pip install .
18 | - name: Run tests
19 | run: pytest --cov=ckanserviceprovider --cov-append --cov-report=xml --disable-warnings tests
20 | - name: Upload coverage report to codecov
21 | uses: codecov/codecov-action@v3
22 | with:
23 | file: ./coverage.xml
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | syntax: glob
2 | # generic
3 | *.pyc
4 | *.swp
5 | *.swo
6 | ckanserviceprovider.egg-info/*
7 | *.db
8 | settings_local.py
9 | dist/*
10 | build/*
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/ckan/ckan-service-provider/actions/workflows/test.yml)
2 | [](https://pypi.python.org/pypi/ckanserviceprovider/)
3 | [](https://pypi.python.org/pypi/ckanserviceprovider/)
4 | [](https://pypi.python.org/pypi/ckanserviceprovider/)
5 | [](https://pypi.python.org/pypi/ckanserviceprovider/)
6 | [](https://pypi.python.org/pypi/ckanserviceprovider/)
7 |
8 | [DataPusher]: https://github.com/okfn/datapusher
9 | [PyPI]: https://pypi.python.org/pypi/ckanserviceprovider
10 |
11 |
12 | # CKAN Service Provider
13 |
14 | A library for making web services that make functions available as synchronous
15 | or asynchronous jobs. Used by [DataPusher][].
16 |
17 |
18 | ## Getting Started
19 |
20 | To install ckanserviceprovider for development:
21 |
22 | ```bash
23 | git clone https://github.com/ckan/ckan-service-provider.git
24 | cd ckan-service-provider
25 | pip install -r requirements-dev.txt
26 | ```
27 |
28 | To get started making a web service with ckanserviceprovider have a look at
29 | [/example](example). You can run the example server with
30 | `python example/main.py example/settings_local.py`.
31 |
32 | For a real-world example have a look at [DataPusher][].
33 |
34 |
35 | ## Running the Tests
36 |
37 | To run the ckanserviceprovider tests:
38 |
39 | ```bash
40 | pytest
41 | ```
42 |
43 |
44 | ## Building the Documentation
45 |
46 | To build the ckanserviceprovider docs:
47 |
48 | ```bash
49 | python setup.py build_sphinx
50 | ```
51 |
52 |
53 | ## Releasing a New Version
54 |
55 | To release a new version of ckanserviceprovider:
56 |
57 | 1. Increment the version number in [setup.py](setup.py)
58 |
59 | 2. Build a source distribution of the new version and publish it to
60 | [PyPI][]:
61 |
62 | ```bash
63 | python setup.py sdist bdist_wheel
64 | pip install --upgrade twine
65 | twine upload dist/*
66 | ```
67 |
68 | You may want to test installing and running the new version from PyPI in a
69 | clean virtualenv before continuing to the next step.
70 |
71 | 3. Commit your setup.py changes to git, tag the release, and push the changes
72 | and the tag to GitHub:
73 |
74 | ```bash
75 | git commit setup.py -m "Bump version number"
76 | git tag 0.0.1
77 | git push
78 | git push origin 0.0.1
79 | ```
80 |
81 | (Replace both instances of 0.0.1 with the number of the version you're
82 | releasing.)
83 |
84 |
85 | ## Authors
86 |
87 | The original authors of ckanserviceprovider were
88 | David Raznick and
89 | Dominik Moritz . For the current list of contributors
90 | see [github.com/ckan/ckan-service-provider/contributors](https://github.com/ckan/ckan-service-provider/contributors)
91 |
--------------------------------------------------------------------------------
/ckanserviceprovider/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ckan/ckan-service-provider/3f7fc99a9fbed5bbac064b3068887aff97adfcc3/ckanserviceprovider/__init__.py
--------------------------------------------------------------------------------
/ckanserviceprovider/db.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """A module that encapsulates CKAN Service Provider's model/database.
3 |
4 | This module provides a set of public functions that other modules should call
5 | to interact with the database, rather than using sqlalchemy directly.
6 |
7 | TODO: Some more refactoring is still needed to have the model completely
8 | encapsulated in this module, other modules are still using sqlalchemy directly
9 | in some places.
10 |
11 | The database contains:
12 |
13 | 1. A jobs table that tracks the statuses of pending and completed jobs
14 | 2. A metdata table that contains (key, value) metadata pairs associated with
15 | jobs
16 | 3. A logs table that contains log output from jobs.
17 |
18 | This module's public interface includes:
19 |
20 | init()
21 | Initialise the database connection on application or test startup, creating the
22 | database and tables if necessary.
23 |
24 | drop_all()
25 | Delete all the database tables, for tests.
26 |
27 | get_job()
28 | Get a dictionary representation of a job from the database.
29 |
30 | add_pending_job()
31 | Add a new job with status "pending" to the database.
32 | Jobs always have status "pending" when they're first added.
33 |
34 | mark_job_as_*()
35 | A set of functions for updating an existing job in the database.
36 | There are a limited number of ways in which CKAN Service Provider updates jobs.
37 | For example marking a job as completed successfully, or marking a job as
38 | failed with an error. These mark_job_as_*() functions define all the ways that
39 | a job can be updated.
40 |
41 | See the functions' own docstrings for details.
42 |
43 | """
44 |
45 | import datetime
46 | import json
47 |
48 | import sqlalchemy
49 |
50 |
51 | # Some module-global constants. Some of these are accessed directly by other
52 | # modules. It would be good to factor these out.
53 | ENGINE = None
54 | _METADATA = None
55 | JOBS_TABLE = None
56 | METADATA_TABLE = None
57 | LOGS_TABLE = None
58 |
59 |
60 | def init(uri, echo=False):
61 | """Initialise the database.
62 |
63 | Initialise the sqlalchemy engine, metadata and table objects that we use to
64 | connect to the database.
65 |
66 | Create the database and the database tables themselves if they don't
67 | already exist.
68 |
69 | :param uri: the sqlalchemy database URI
70 | :type uri: string
71 |
72 | :param echo: whether or not to have the sqlalchemy engine log all
73 | statements to stdout
74 | :type echo: bool
75 |
76 | """
77 | global ENGINE, _METADATA, JOBS_TABLE, METADATA_TABLE, LOGS_TABLE
78 | ENGINE = sqlalchemy.create_engine(uri, echo=echo, convert_unicode=True)
79 | _METADATA = sqlalchemy.MetaData(ENGINE)
80 | JOBS_TABLE = _init_jobs_table()
81 | METADATA_TABLE = _init_metadata_table()
82 | LOGS_TABLE = _init_logs_table()
83 | _METADATA.create_all(ENGINE)
84 |
85 |
86 | def drop_all():
87 | """Delete all the database tables (if they exist).
88 |
89 | This is for tests to reset the DB. Note that this will delete *all* tables
90 | in the database, not just tables created by this module (for example
91 | apscheduler's tables will also be deleted).
92 |
93 | """
94 | if _METADATA:
95 | _METADATA.drop_all(ENGINE)
96 |
97 |
98 | def get_job(job_id, limit=None, use_aps_id=False):
99 | """Return the job with the given job_id as a dict.
100 |
101 | The dict also includes any metadata or logs associated with the job.
102 |
103 | Returns None instead of a dict if there's no job with the given job_id.
104 |
105 | The keys of a job dict are:
106 |
107 | "job_id": The unique identifier for the job (unicode)
108 |
109 | "job_type": The name of the job function that will be executed for this
110 | job (unicode)
111 |
112 | "status": The current status of the job, e.g. "pending", "complete", or
113 | "error" (unicode)
114 |
115 | "data": Any output data returned by the job if it has completed
116 | successfully. This may be any JSON-serializable type, e.g. None, a
117 | string, a dict, etc.
118 |
119 | "error": If the job failed with an error this will be a dict with a
120 | "message" key whose value is a string error message. The dict may also
121 | have other keys specific to the particular type of error. If the job
122 | did not fail with an error then "error" will be None.
123 |
124 | "requested_timestamp": The time at which the job was requested (string)
125 |
126 | "finished_timestamp": The time at which the job finished (string)
127 |
128 | "sent_data": The input data for the job, provided by the client site.
129 | This may be any JSON-serializable type, e.g. None, a string, a dict,
130 | etc.
131 |
132 | "result_url": The callback URL that CKAN Service Provider will post the
133 | result to when the job finishes (unicode)
134 |
135 | "api_key": The API key that CKAN Service Provider will use when posting
136 | the job result to the result_url (unicode or None). A None here doesn't
137 | mean that there was no API key: CKAN Service Provider deletes the API
138 | key from the database after it has posted the result to the result_url.
139 |
140 | "job_key": The key that users must provide (in the Authorization header of
141 | the HTTP request) to be authorized to modify the job (unicode).
142 | For example requests to the CKAN Service Provider API need this to get
143 | the status or output data of a job or to delete a job.
144 | If you login to CKAN Service Provider as an administrator then you can
145 | administer any job without providing its job_key.
146 |
147 | "metadata": Any custom metadata associated with the job (dict)
148 |
149 | "logs": Any logs associated with the job (list)
150 |
151 | """
152 | # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
153 | # warnings.
154 | if job_id:
155 | job_id = str(job_id)
156 |
157 | if use_aps_id:
158 | result = ENGINE.execute(
159 | JOBS_TABLE.select().where(JOBS_TABLE.c.aps_job_id == job_id)
160 | ).first()
161 | else:
162 | result = ENGINE.execute(
163 | JOBS_TABLE.select().where(JOBS_TABLE.c.job_id == job_id)
164 | ).first()
165 |
166 | if not result:
167 | return None
168 |
169 | # Turn the result into a dictionary representation of the job.
170 | result_dict = {}
171 | for field in list(result.keys()):
172 | value = getattr(result, field)
173 | if value is None:
174 | result_dict[field] = value
175 | elif field in ("sent_data", "data", "error"):
176 | result_dict[field] = json.loads(value)
177 | elif isinstance(value, datetime.datetime):
178 | result_dict[field] = value.isoformat()
179 | else:
180 | result_dict[field] = str(value)
181 |
182 | result_dict["metadata"] = _get_metadata(job_id)
183 | result_dict["logs"] = _get_logs(job_id, limit=limit)
184 |
185 | return result_dict
186 |
187 |
188 | def add_pending_job(
189 | job_id, job_key, job_type, api_key, data=None, metadata=None, result_url=None
190 | ):
191 | """Add a new job with status "pending" to the jobs table.
192 |
193 | All code that adds jobs to the jobs table should go through this function.
194 | Code that adds to the jobs table manually should be refactored to use this
195 | function.
196 |
197 | May raise unspecified exceptions from Python core, SQLAlchemy or JSON!
198 | TODO: Document and unit test these!
199 |
200 | :param job_id: a unique identifier for the job, used as the primary key in
201 | ckanserviceprovider's "jobs" database table
202 | :type job_id: unicode
203 |
204 | :param job_key: the key required to administer the job via the API
205 | :type job_key: unicode
206 |
207 | :param job_type: the name of the job function that will be executed for
208 | this job
209 | :type job_key: unicode
210 |
211 | :param api_key: the client site API key that ckanserviceprovider will use
212 | when posting the job result to the result_url
213 | :type api_key: unicode
214 |
215 | :param data: The input data for the job (called sent_data elsewhere)
216 | :type data: Any JSON-serializable type
217 |
218 | :param metadata: A dict of arbitrary (key, value) metadata pairs to be
219 | stored along with the job. The keys should be strings, the values can
220 | be strings or any JSON-encodable type.
221 | :type metadata: dict
222 |
223 | :param result_url: the callback URL that ckanserviceprovider will post the
224 | job result to when the job has finished
225 | :type result_url: unicode
226 |
227 | """
228 | if not data:
229 | data = {}
230 | data = json.dumps(data)
231 |
232 | # Turn strings into unicode to stop SQLAlchemy
233 | # "Unicode type received non-unicode bind param value" warnings.
234 | if job_id:
235 | job_id = str(job_id)
236 | if job_type:
237 | job_type = str(job_type)
238 | if result_url:
239 | result_url = str(result_url)
240 | if api_key:
241 | api_key = str(api_key)
242 | if job_key:
243 | job_key = str(job_key)
244 | data = str(data)
245 |
246 | if not metadata:
247 | metadata = {}
248 |
249 | conn = ENGINE.connect()
250 | trans = conn.begin()
251 | try:
252 | conn.execute(
253 | JOBS_TABLE.insert().values(
254 | job_id=job_id,
255 | job_type=job_type,
256 | status="pending",
257 | requested_timestamp=datetime.datetime.now(),
258 | sent_data=data,
259 | result_url=result_url,
260 | api_key=api_key,
261 | job_key=job_key,
262 | )
263 | )
264 |
265 | # Insert any (key, value) metadata pairs that the job has into the
266 | # metadata table.
267 | inserts = []
268 | for key, value in list(metadata.items()):
269 | type_ = "string"
270 | if not isinstance(value, str):
271 | value = json.dumps(value)
272 | type_ = "json"
273 |
274 | # Turn strings into unicode to stop SQLAlchemy
275 | # "Unicode type received non-unicode bind param value" warnings.
276 | key = str(key)
277 | value = str(value)
278 |
279 | inserts.append(
280 | {"job_id": job_id, "key": key, "value": value, "type": type_}
281 | )
282 | if inserts:
283 | conn.execute(METADATA_TABLE.insert(), inserts)
284 | trans.commit()
285 | except Exception:
286 | trans.rollback()
287 | raise
288 | finally:
289 | conn.close()
290 |
291 |
292 | class InvalidErrorObjectError(Exception):
293 | pass
294 |
295 |
296 | def _validate_error(error):
297 | """Validate and return the given error object.
298 |
299 | Based on the given error object, return either None or a dict with a
300 | "message" key whose value is a string (the dict may also have any other
301 | keys that it wants).
302 |
303 | The given "error" object can be:
304 |
305 | - None, in which case None is returned
306 |
307 | - A string, in which case a dict like this will be returned:
308 | {"message": error_string}
309 |
310 | - A dict with a "message" key whose value is a string, in which case the
311 | dict will be returned unchanged
312 |
313 | :param error: the error object to validate
314 |
315 | :raises InvalidErrorObjectError: If the error object doesn't match any of
316 | the allowed types
317 |
318 | """
319 | if error is None:
320 | return None
321 | elif isinstance(error, str):
322 | return {"message": error}
323 | else:
324 | try:
325 | message = error["message"]
326 | if isinstance(message, str):
327 | return error
328 | else:
329 | raise InvalidErrorObjectError("error['message'] must be a string")
330 | except (TypeError, KeyError):
331 | raise InvalidErrorObjectError(
332 | "error must be either a string or a dict with a message key"
333 | )
334 |
335 |
336 | def _update_job(job_id, job_dict):
337 | """Update the database row for the given job_id with the given job_dict.
338 |
339 | All functions that update rows in the jobs table do it by calling this
340 | helper function.
341 |
342 | job_dict is a dict with values corresponding to the database columns that
343 | should be updated, e.g.:
344 |
345 | {"status": "complete", "data": ...}
346 |
347 | """
348 | # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
349 | # warnings.
350 | if job_id:
351 | job_id = str(job_id)
352 |
353 | if "error" in job_dict:
354 | job_dict["error"] = _validate_error(job_dict["error"])
355 | job_dict["error"] = json.dumps(job_dict["error"])
356 | # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
357 | # warnings.
358 | job_dict["error"] = str(job_dict["error"])
359 |
360 | # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
361 | # warnings.
362 | if "data" in job_dict:
363 | job_dict["data"] = str(job_dict["data"])
364 |
365 | ENGINE.execute(
366 | JOBS_TABLE.update().where(JOBS_TABLE.c.job_id == job_id).values(**job_dict)
367 | )
368 |
369 |
370 | def mark_job_as_completed(job_id, data=None):
371 | """Mark a job as completed successfully.
372 |
373 | :param job_id: the job_id of the job to be updated
374 | :type job_id: unicode
375 |
376 | :param data: the output data returned by the job
377 | :type data: any JSON-serializable type (including None)
378 |
379 | """
380 | update_dict = {
381 | "status": "complete",
382 | "data": json.dumps(data),
383 | "finished_timestamp": datetime.datetime.now(),
384 | }
385 | _update_job(job_id, update_dict)
386 |
387 |
388 | def mark_job_as_missed(job_id):
389 | """Mark a job as missed because it was in the queue for too long.
390 |
391 | :param job_id: the job_id of the job to be updated
392 | :type job_id: unicode
393 |
394 | """
395 | update_dict = {
396 | "status": "error",
397 | "error": "Job delayed too long, service full",
398 | "finished_timestamp": datetime.datetime.now(),
399 | }
400 | _update_job(job_id, update_dict)
401 |
402 |
403 | def mark_job_as_errored(job_id, error_object):
404 | """Mark a job as failed with an error.
405 |
406 | :param job_id: the job_id of the job to be updated
407 | :type job_id: unicode
408 |
409 | :param error_object: the error returned by the job
410 | :type error_object: either a string or a dict with a "message" key whose
411 | value is a string
412 |
413 | """
414 | update_dict = {
415 | "status": "error",
416 | "error": error_object,
417 | "finished_timestamp": datetime.datetime.now(),
418 | }
419 | _update_job(job_id, update_dict)
420 |
421 |
422 | def mark_job_as_failed_to_post_result(job_id):
423 | """Mark a job as 'failed to post result'.
424 |
425 | This happens when a job completes (either successfully or with an error)
426 | then trying to post the job result back to the job's callback URL fails.
427 |
428 | FIXME: This overwrites any error from the job itself!
429 |
430 | :param job_id: the job_id of the job to be updated
431 | :type job_id: unicode
432 |
433 | """
434 | update_dict = {
435 | "error": "Process completed but unable to post to result_url",
436 | }
437 | _update_job(job_id, update_dict)
438 |
439 |
440 | def delete_api_key(job_id):
441 | """Delete the given job's API key from the database.
442 |
443 | The API key is used when posting the job's result to the client's callback
444 | URL. This function should be called to delete the API key after the result
445 | has been posted - the API key is no longer needed.
446 |
447 | """
448 | _update_job(job_id, {"api_key": None})
449 |
450 |
451 | def set_aps_job_id(job_id, aps_job_id):
452 |
453 | _update_job(job_id, {"aps_job_id": aps_job_id})
454 |
455 |
456 | def _init_jobs_table():
457 | """Initialise the "jobs" table in the db."""
458 | _jobs_table = sqlalchemy.Table(
459 | "jobs",
460 | _METADATA,
461 | sqlalchemy.Column("job_id", sqlalchemy.UnicodeText, primary_key=True),
462 | sqlalchemy.Column("job_type", sqlalchemy.UnicodeText),
463 | sqlalchemy.Column("status", sqlalchemy.UnicodeText, index=True),
464 | sqlalchemy.Column("data", sqlalchemy.UnicodeText),
465 | sqlalchemy.Column("error", sqlalchemy.UnicodeText),
466 | sqlalchemy.Column("requested_timestamp", sqlalchemy.DateTime),
467 | sqlalchemy.Column("finished_timestamp", sqlalchemy.DateTime),
468 | sqlalchemy.Column("sent_data", sqlalchemy.UnicodeText),
469 | sqlalchemy.Column("aps_job_id", sqlalchemy.UnicodeText),
470 | # Callback URL:
471 | sqlalchemy.Column("result_url", sqlalchemy.UnicodeText),
472 | # CKAN API key:
473 | sqlalchemy.Column("api_key", sqlalchemy.UnicodeText),
474 | # Key to administer job:
475 | sqlalchemy.Column("job_key", sqlalchemy.UnicodeText),
476 | )
477 | return _jobs_table
478 |
479 |
480 | def _init_metadata_table():
481 | """Initialise the "metadata" table in the db."""
482 | _metadata_table = sqlalchemy.Table(
483 | "metadata",
484 | _METADATA,
485 | sqlalchemy.Column(
486 | "job_id",
487 | sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
488 | nullable=False,
489 | primary_key=True,
490 | ),
491 | sqlalchemy.Column("key", sqlalchemy.UnicodeText, primary_key=True),
492 | sqlalchemy.Column("value", sqlalchemy.UnicodeText, index=True),
493 | sqlalchemy.Column("type", sqlalchemy.UnicodeText),
494 | )
495 | return _metadata_table
496 |
497 |
498 | def _init_logs_table():
499 | """Initialise the "logs" table in the db."""
500 | _logs_table = sqlalchemy.Table(
501 | "logs",
502 | _METADATA,
503 | sqlalchemy.Column(
504 | "job_id",
505 | sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
506 | nullable=False,
507 | ),
508 | sqlalchemy.Column("timestamp", sqlalchemy.DateTime),
509 | sqlalchemy.Column("message", sqlalchemy.UnicodeText),
510 | sqlalchemy.Column("level", sqlalchemy.UnicodeText),
511 | sqlalchemy.Column("module", sqlalchemy.UnicodeText),
512 | sqlalchemy.Column("funcName", sqlalchemy.UnicodeText),
513 | sqlalchemy.Column("lineno", sqlalchemy.Integer),
514 | )
515 | return _logs_table
516 |
517 |
518 | def _get_metadata(job_id):
519 | """Return any metadata for the given job_id from the metadata table."""
520 | # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
521 | # warnings.
522 | job_id = str(job_id)
523 |
524 | results = ENGINE.execute(
525 | METADATA_TABLE.select().where(METADATA_TABLE.c.job_id == job_id)
526 | ).fetchall()
527 | metadata = {}
528 | for row in results:
529 | value = row["value"]
530 | if row["type"] == "json":
531 | value = json.loads(value)
532 | metadata[row["key"]] = value
533 | return metadata
534 |
535 |
536 | def _get_logs(job_id, limit=None):
537 | """Return any logs for the given job_id from the logs table."""
538 | # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
539 | # warnings.
540 | job_id = str(job_id)
541 | try:
542 | int(limit)
543 | limit_is_valid = True
544 | except (ValueError, TypeError):
545 | # None or "one" (or similar)
546 | limit_is_valid = False
547 |
548 | if not limit_is_valid:
549 | results = ENGINE.execute(
550 | LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)
551 | ).fetchall()
552 | else:
553 | results = ENGINE.execute(
554 | LOGS_TABLE.select()
555 | .where(LOGS_TABLE.c.job_id == job_id)
556 | .order_by(LOGS_TABLE.c.timestamp.desc())
557 | .limit(limit)
558 | ).fetchall()
559 |
560 | results = [dict(result) for result in results]
561 |
562 | for result in results:
563 | result.pop("job_id")
564 |
565 | return results
566 |
567 |
568 | def add_logs(job_id, message=None, level=None, module=None, funcName=None, lineno=None):
569 | """for tests only"""
570 | if job_id:
571 | job_id = str(job_id)
572 | if message:
573 | message = str(message)
574 | if level:
575 | level = str(level)
576 | if module:
577 | module = str(module)
578 | if funcName:
579 | funcName = str(funcName)
580 | if lineno:
581 | lineno = str(lineno)
582 | conn = ENGINE.connect()
583 | trans = conn.begin()
584 |
585 | conn.execute(
586 | LOGS_TABLE.insert().values(
587 | job_id=job_id,
588 | timestamp=datetime.datetime.now(),
589 | message=message,
590 | level=level,
591 | module=module,
592 | funcName=funcName,
593 | lineno=lineno,
594 | )
595 | )
596 | trans.commit()
597 | conn.close()
598 |
--------------------------------------------------------------------------------
/ckanserviceprovider/default_settings.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | DEBUG = False
4 | TESTING = False
5 | SECRET_KEY = "please_replace_me"
6 | USERNAME = "admin"
7 | PASSWORD = "pass"
8 |
9 | # database
10 |
11 | SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite://")
12 | SQLALCHEMY_ECHO = False
13 |
14 | # webserver host and port
15 |
16 | HOST = "0.0.0.0"
17 | PORT = 8000
18 |
19 | # logging
20 |
21 | LOG_FILE = "/tmp/ckan_service.log"
22 | STDERR = True
23 |
24 | # project configuration
25 | NAME = "service"
26 |
27 | # days to keep when clearing
28 | KEEP_JOBS_AGE = 14
29 |
--------------------------------------------------------------------------------
/ckanserviceprovider/job.py:
--------------------------------------------------------------------------------
1 | from . import web
2 |
3 |
4 | def asynchronous(func):
5 | web.async_types[func.__name__] = func
6 | return func
7 |
8 |
9 | def synchronous(func):
10 | web.sync_types[func.__name__] = func
11 | return func
12 |
--------------------------------------------------------------------------------
/ckanserviceprovider/util.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | import logging
5 | import datetime
6 | from future.utils import python_2_unicode_compatible
7 |
8 | from . import db
9 |
10 |
11 | @python_2_unicode_compatible
12 | class JobError(Exception):
13 | """The exception type that jobs raise to signal failure."""
14 |
15 | def __init__(self, message):
16 | """Initialize a JobError with the given error message string.
17 |
18 | The error message string that you give here will be returned to the
19 | client site in the job dict's "error" key.
20 |
21 | """
22 | self.message = message
23 |
24 | def as_dict(self):
25 | """Return a dictionary representation of this JobError object.
26 |
27 | Returns a dictionary with a "message" key whose value is a string error
28 | message - suitable for use as the "error" key in a ckanserviceprovider
29 | job dict.
30 |
31 | """
32 | return {"message": self.message}
33 |
34 | def __str__(self):
35 | return self.message
36 |
37 |
38 | class StoringHandler(logging.Handler):
39 | """A handler that stores the logging records
40 | in the database."""
41 |
42 | def __init__(self, task_id, input):
43 | logging.Handler.__init__(self)
44 | self.task_id = task_id
45 | self.input = input
46 |
47 | def emit(self, record):
48 | conn = db.ENGINE.connect()
49 | try:
50 | # Turn strings into unicode to stop SQLAlchemy
51 | # "Unicode type received non-unicode bind param value" warnings.
52 | message = str(record.getMessage())
53 | level = str(record.levelname)
54 | module = str(record.module)
55 | funcName = str(record.funcName)
56 |
57 | conn.execute(
58 | db.LOGS_TABLE.insert().values(
59 | job_id=self.task_id,
60 | timestamp=datetime.datetime.now(),
61 | message=message,
62 | level=level,
63 | module=module,
64 | funcName=funcName,
65 | lineno=record.lineno,
66 | )
67 | )
68 | finally:
69 | conn.close()
70 |
--------------------------------------------------------------------------------
/ckanserviceprovider/web.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | import uuid
5 | import datetime
6 | import sys
7 | import json
8 | import traceback
9 | import logging
10 | import logging.handlers
11 |
12 | import flask
13 | import flask_login as flogin
14 | import werkzeug
15 | from apscheduler.schedulers.background import BackgroundScheduler as Scheduler
16 | import apscheduler.events as events
17 | import apscheduler.jobstores.sqlalchemy as sqlalchemy_store
18 | from apscheduler.triggers.date import DateTrigger
19 | import sqlalchemy.sql as sql
20 | import sqlalchemy as sa
21 | import requests
22 | from werkzeug.middleware.proxy_fix import ProxyFix
23 |
24 | from . import db
25 | from . import util
26 | from . import default_settings
27 |
28 | # Some module-global constants. Some of these are accessed directly by other
29 | # modules. It would be good to factor out as many of these as possible.
30 | sync_types = {}
31 | async_types = {}
32 | job_statuses = ["pending", "complete", "error"]
33 | app = flask.Flask(__name__)
34 | scheduler = None
35 | _users = None
36 | _names = None
37 | SSL_VERIFY = None
38 |
39 |
40 | def init():
41 | """Initialise and configure the app, database, scheduler, etc.
42 |
43 | This should be called once at application startup or at tests startup
44 | (and not e.g. called once for each test case).
45 |
46 | """
47 | global _users, _names
48 | _configure_app(app)
49 | _users, _names = _init_login_manager(app)
50 | _configure_logger()
51 | init_scheduler(app.config.get("SQLALCHEMY_DATABASE_URI"))
52 | db.init(app.config.get("SQLALCHEMY_DATABASE_URI"))
53 |
54 |
55 | def _configure_app(app_):
56 | """Configure the Flask WSGI app."""
57 | app_.url_map.strict_slashes = False
58 | app_.config.from_object(default_settings)
59 | app_.config.from_envvar("JOB_CONFIG", silent=True)
60 | db_url = app_.config.get("SQLALCHEMY_DATABASE_URI")
61 | if not db_url:
62 | raise Exception("No db_url in config")
63 | app_.wsgi_app = ProxyFix(app_.wsgi_app)
64 |
65 | global SSL_VERIFY
66 | if app_.config.get("SSL_VERIFY") in ["False", "FALSE", "0", False, 0]:
67 | SSL_VERIFY = False
68 | else:
69 | SSL_VERIFY = True
70 |
71 | return app_
72 |
73 |
74 | def _init_login_manager(app_):
75 | """Initialise and configure the login manager."""
76 | login_manager = flogin.LoginManager()
77 | login_manager.setup_app(app_)
78 | login_manager.anonymous_user = Anonymous
79 | login_manager.login_view = "login"
80 |
81 | users = {app_.config["USERNAME"]: User("Admin", 0)}
82 | names = dict((int(v.get_id()), k) for k, v in list(users.items()))
83 |
84 | @login_manager.user_loader
85 | def load_user(userid):
86 | userid = int(userid)
87 | name = names.get(userid)
88 | return users.get(name)
89 |
90 | return users, names
91 |
92 |
93 | def _configure_logger_for_production(logger):
94 | """Configure the given logger for production deployment.
95 |
96 | Logs to stderr and file, and emails errors to admins.
97 |
98 | """
99 | stderr_handler = logging.StreamHandler(sys.stderr)
100 | stderr_handler.setLevel(logging.INFO)
101 | ts_formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
102 | if "STDERR" in app.config and app.config["STDERR"]:
103 | stderr_handler.setFormatter(ts_formatter)
104 | logger.addHandler(stderr_handler)
105 |
106 | if "LOG_FILE" in app.config and app.config["LOG_FILE"]:
107 | file_handler = logging.handlers.RotatingFileHandler(
108 | app.config.get("LOG_FILE"), maxBytes=67108864, backupCount=5
109 | )
110 | file_handler.setLevel(logging.INFO)
111 | file_handler.setFormatter(ts_formatter)
112 | logger.addHandler(file_handler)
113 |
114 | mail_handler = logging.handlers.SMTPHandler(
115 | "127.0.0.1",
116 | app.config.get("FROM_EMAIL"),
117 | app.config.get("ADMINS", []),
118 | "CKAN Service Error",
119 | )
120 | mail_handler.setLevel(logging.ERROR)
121 | if "FROM_EMAIL" in app.config:
122 | logger.addHandler(mail_handler)
123 |
124 |
125 | def _configure_logger_for_debugging(logger):
126 | """Configure the given logger for debug mode."""
127 | logger.addHandler(app.logger.handlers[0])
128 |
129 |
130 | def _configure_logger():
131 | """Configure the logging module."""
132 | if not app.debug:
133 | _configure_logger_for_production(logging.getLogger())
134 | elif not app.testing:
135 | _configure_logger_for_debugging(logging.getLogger())
136 |
137 |
138 | def init_scheduler(db_uri):
139 | """Initialise and configure the scheduler."""
140 | global scheduler
141 | scheduler = Scheduler()
142 | scheduler.misfire_grace_time = 3600
143 | scheduler.add_jobstore(sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), "default")
144 | scheduler.add_listener(
145 | job_listener,
146 | events.EVENT_JOB_EXECUTED | events.EVENT_JOB_MISSED | events.EVENT_JOB_ERROR,
147 | )
148 | return scheduler
149 |
150 |
151 | class User(flogin.UserMixin):
152 | def __init__(self, name, id, active=True):
153 | self.name = name
154 | self.id = id
155 | self.active = active
156 |
157 | def is_active(self):
158 | return self.active
159 |
160 |
161 | class Anonymous(flogin.AnonymousUserMixin):
162 | name = "Anonymous"
163 |
164 |
165 | class RunNowTrigger(object):
166 | """Custom apscheduler trigger to run job once and only
167 | once"""
168 |
169 | def __init__(self):
170 | self.run = False
171 |
172 | def get_next_fire_time(self, start_date):
173 | if not self.run:
174 | self.run = True
175 | return datetime.datetime.now()
176 |
177 | def __str__(self):
178 | return "RunTriggerNow, run = %s" % self.run
179 |
180 | def __repr__(self):
181 | return "RunTriggerNow, run = %s" % self.run
182 |
183 |
184 | def job_listener(event):
185 | """Listens to completed job"""
186 | aps_job_id = event.job_id
187 |
188 | job = db.get_job(aps_job_id, use_aps_id=True)
189 | job_id = job['job_id']
190 |
191 | if event.code == events.EVENT_JOB_MISSED:
192 | db.mark_job_as_missed(job_id)
193 | elif event.exception:
194 | if isinstance(event.exception, util.JobError):
195 | error_object = event.exception.as_dict()
196 | else:
197 | error_object = "\n".join(
198 | [event.traceback] + [repr(event.exception)]
199 | )
200 | db.mark_job_as_errored(job_id, error_object)
201 | else:
202 | db.mark_job_as_completed(job_id, event.retval)
203 | api_key = db.get_job(job_id)["api_key"]
204 | result_ok = send_result(job_id, api_key)
205 |
206 | if not result_ok:
207 | db.mark_job_as_failed_to_post_result(job_id)
208 |
209 | # Optionally notify tests that job_listener() has finished.
210 | if "_TEST_CALLBACK_URL" in app.config:
211 | requests.get(app.config["_TEST_CALLBACK_URL"])
212 |
213 |
214 | headers = {str("Content-Type"): str("application/json")}
215 |
216 |
217 | @app.route("/", methods=["GET"])
218 | def index():
219 | """Show link to documentation.
220 |
221 | :rtype: A dictionary with the following keys
222 | :param help: Help text
223 | :type help: string
224 | """
225 | return flask.jsonify(
226 | help="""
227 | Get help at:
228 | http://ckan-service-provider.readthedocs.org/."""
229 | )
230 |
231 |
232 | @app.route("/status", methods=["GET"])
233 | def status():
234 | """Show version, available job types and name of service.
235 |
236 | **Results:**
237 |
238 | :rtype: A dictionary with the following keys
239 | :param version: Version of the service provider
240 | :type version: float
241 | :param job_types: Available job types
242 | :type job_types: list of strings
243 | :param name: Name of the service
244 | :type name: string
245 | :param stats: Shows stats for jobs in queue
246 | :type stats: dictionary
247 | """
248 | job_types = sorted(list(async_types.keys()) + list(sync_types.keys()))
249 |
250 | counts = {}
251 | for job_status in job_statuses:
252 | counts[job_status] = db.ENGINE.execute(
253 | db.JOBS_TABLE.count().where(db.JOBS_TABLE.c.status == job_status)
254 | ).first()[0]
255 |
256 | return flask.jsonify(
257 | version=0.1,
258 | job_types=job_types,
259 | name=app.config.get("NAME", "example"),
260 | stats=counts,
261 | )
262 |
263 |
264 | def check_auth(username, password):
265 | """This function is called to check if a username /
266 | password combination is valid.
267 | """
268 | return username == app.config["USERNAME"] and password == app.config["PASSWORD"]
269 |
270 |
271 | @app.route("/login", methods=["POST", "GET"])
272 | def login():
273 | """Log in as administrator
274 |
275 | You can use wither basic auth or form based login (via POST).
276 |
277 | :param username: The administrator's username
278 | :type username: string
279 | :param password: The administrator's password
280 | :type password: string
281 | """
282 | username = None
283 | password = None
284 | next = flask.request.args.get("next")
285 | auth = flask.request.authorization
286 |
287 | if flask.request.method == "POST":
288 | username = flask.request.form["username"]
289 | password = flask.request.form["password"]
290 |
291 | if auth and auth.type == "basic":
292 | username = auth.username
293 | password = auth.password
294 |
295 | if not flogin.current_user.is_active:
296 | error = "You have to login with proper credentials"
297 | if username and password:
298 | if check_auth(username, password):
299 | user = _users.get(username)
300 | if user:
301 | if flogin.login_user(user):
302 | return flask.redirect(next or flask.url_for("user"))
303 | error = "Could not log in user."
304 | else:
305 | error = "User not found."
306 | else:
307 | error = "Wrong username or password."
308 | else:
309 | error = "No username or password."
310 | return flask.Response(
311 | "Could not verify your access level for that URL.\n {}".format(error),
312 | 401,
313 | {str("WWW-Authenticate"): str('Basic realm="Login Required"')},
314 | )
315 | return flask.redirect(next or flask.url_for("user"))
316 |
317 |
318 | @app.route("/user", methods=["GET"])
319 | def user():
320 | """Show information about the current user
321 |
322 | :rtype: A dictionary with the following keys
323 | :param id: User id
324 | :type id: int
325 | :param name: User name
326 | :type name: string
327 | :param is_active: Whether the user is currently active
328 | :type is_active: bool
329 | :param is_anonymous: The anonymous user is the default user if you
330 | are not logged in
331 | :type is_anonymous: bool
332 | """
333 | user = flogin.current_user
334 | return flask.jsonify(
335 | {
336 | "id": user.get_id(),
337 | "name": user.name,
338 | "is_active": user.is_active(),
339 | "is_anonymous": user.is_anonymous,
340 | }
341 | )
342 |
343 |
344 | @app.route("/logout")
345 | def logout():
346 | """Log out the active user"""
347 | flogin.logout_user()
348 | next = flask.request.args.get("next")
349 | return flask.redirect(next or flask.url_for("user"))
350 |
351 |
352 | @app.route("/job", methods=["GET"])
353 | def job_list():
354 | """List all jobs.
355 |
356 | :param _limit: maximum number of jobs to show (default 100)
357 | :type _limit: int
358 | :param _offset: how many jobs to skip before showin the first one (default 0)
359 | :type _offset: int
360 | :param _status: filter jobs by status (complete, error)
361 | :type _status: string
362 |
363 | Also, you can filter the jobs by their metadata. Use the metadata key
364 | as parameter key and the value as value.
365 |
366 | :rtype: A list of job ids
367 | """
368 | args = dict((key, value) for key, value in list(flask.request.args.items()))
369 | limit = args.pop("_limit", 100)
370 | offset = args.pop("_offset", 0)
371 |
372 | select = (
373 | sql.select(
374 | [db.JOBS_TABLE.c.job_id],
375 | from_obj=[
376 | db.JOBS_TABLE.outerjoin(
377 | db.METADATA_TABLE,
378 | db.JOBS_TABLE.c.job_id == db.METADATA_TABLE.c.job_id,
379 | )
380 | ],
381 | )
382 | .group_by(db.JOBS_TABLE.c.job_id)
383 | .order_by(db.JOBS_TABLE.c.requested_timestamp.desc())
384 | .limit(limit)
385 | .offset(offset)
386 | )
387 |
388 | status = args.pop("_status", None)
389 | if status:
390 | select = select.where(db.JOBS_TABLE.c.status == status)
391 |
392 | ors = []
393 | for key, value in args.items():
394 | # Turn strings into unicode to stop SQLAlchemy
395 | # "Unicode type received non-unicode bind param value" warnings.
396 | key = str(key)
397 |
398 | ors.append(
399 | sql.and_(db.METADATA_TABLE.c.key == key, db.METADATA_TABLE.c.value == value)
400 | )
401 |
402 | if ors:
403 | select = select.where(sql.or_(*ors))
404 | select = select.having(sql.func.count(db.JOBS_TABLE.c.job_id) == len(ors))
405 |
406 | result = db.ENGINE.execute(select)
407 | listing = []
408 | for (job_id,) in result:
409 | listing.append(flask.url_for("job_status", job_id=job_id))
410 |
411 | return flask.jsonify(list=listing)
412 |
413 |
414 | class DatetimeJsonEncoder(json.JSONEncoder):
415 | # Custon JSON encoder
416 | def default(self, obj):
417 | if isinstance(obj, datetime.datetime):
418 | return obj.isoformat()
419 |
420 | return json.JSONEncoder.default(self, obj)
421 |
422 |
423 | @app.route("/job/", methods=["GET"])
424 | def job_status(job_id, show_job_key=False, ignore_auth=False):
425 | """Show a specific job.
426 |
427 | :param limit: Limit the number of logs
428 | :type limit: integer
429 |
430 | **Results:**
431 |
432 | :rtype: A dictionary with the following keys
433 | :param status: Status of job (complete, error)
434 | :type status: string
435 | :param sent_data: Input data for job
436 | :type sent_data: json encodable data
437 | :param job_id: An identifier for the job
438 | :type job_id: string
439 | :param result_url: Callback url
440 | :type result_url: url string
441 | :param data: Results from job.
442 | :type data: json encodable data
443 | :param error: Error raised during job execution
444 | :type error: string
445 | :param metadata: Metadata provided when submitting job.
446 | :type metadata: list of key - value pairs
447 | :param requested_timestamp: Time the job started
448 | :type requested_timestamp: timestamp
449 | :param finished_timestamp: Time the job finished
450 | :type finished_timestamp: timestamp
451 |
452 | :statuscode 200: no error
453 | :statuscode 403: not authorized to view the job's data
454 | :statuscode 404: job id not found
455 | :statuscode 409: an error occurred
456 | """
457 | limit = flask.request.args.get("limit")
458 | job_dict = db.get_job(job_id, limit=limit)
459 | if not job_dict:
460 | return json.dumps({"error": "job_id not found"}), 404, headers
461 | if not ignore_auth and not is_authorized(job_dict):
462 | return json.dumps({"error": "not authorized"}), 403, headers
463 | job_dict.pop("api_key", None)
464 | if not show_job_key:
465 | job_dict.pop("job_key", None)
466 | return flask.Response(
467 | json.dumps(job_dict, cls=DatetimeJsonEncoder), mimetype="application/json"
468 | )
469 |
470 |
471 | @app.route("/job/", methods=["DELETE"])
472 | def job_delete(job_id):
473 | """Deletes the job together with its logs and metadata.
474 |
475 | :param job_id: An identifier for the job
476 | :type job_id: string
477 |
478 | :statuscode 200: no error
479 | :statuscode 403: not authorized to delete the job
480 | :statuscode 404: the job could not be found
481 | :statuscode 409: an error occurred
482 | """
483 | conn = db.ENGINE.connect()
484 | job = db.get_job(job_id)
485 | if not job:
486 | return json.dumps({"error": "job_id not found"}), 404, headers
487 | if not is_authorized(job):
488 | return json.dumps({"error": "not authorized"}), 403, headers
489 | trans = conn.begin()
490 | try:
491 | conn.execute(db.JOBS_TABLE.delete().where(db.JOBS_TABLE.c.job_id == job_id))
492 | trans.commit()
493 | return json.dumps({"success": True}), 200, headers
494 | except Exception as e:
495 | trans.rollback()
496 | return json.dumps({"error": str(e)}), 409, headers
497 | finally:
498 | conn.close()
499 |
500 |
501 | @app.route("/job", methods=["DELETE"])
502 | def clear_jobs():
503 | """Clear old jobs
504 |
505 | :param days: Jobs for how many days should be kept (default: 10)
506 | :type days: integer
507 |
508 | :statuscode 200: no error
509 | :statuscode 403: not authorized to delete jobs
510 | :statuscode 409: an error occurred
511 | """
512 | if not is_authorized():
513 | return json.dumps({"error": "not authorized"}), 403, headers
514 |
515 | days = flask.request.args.get("days", None)
516 | return _clear_jobs(days)
517 |
518 |
519 | def _clear_jobs(days=None):
520 | if days is None:
521 | days = app.config.get("KEEP_JOBS_AGE")
522 | else:
523 | try:
524 | days = int(days)
525 | except Exception as e:
526 | return json.dumps({"error": str(e)}), 409, headers
527 | conn = db.ENGINE.connect()
528 | trans = conn.begin()
529 | date = datetime.datetime.now() - datetime.timedelta(days=days)
530 | try:
531 | conn.execute(
532 | db.JOBS_TABLE.delete().where(db.JOBS_TABLE.c.finished_timestamp < date)
533 | )
534 | trans.commit()
535 | return json.dumps({"success": True}), 200, headers
536 | except Exception as e:
537 | trans.rollback()
538 | return json.dumps({"error": str(e)}), 409, headers
539 | finally:
540 | conn.close()
541 |
542 |
543 | @app.route("/job//data", methods=["GET"])
544 | def job_data(job_id):
545 | """Get the raw data that the job returned. The mimetype
546 | will be the value provided in the metdata for the key ``mimetype``.
547 |
548 | **Results:**
549 |
550 | :rtype: string
551 |
552 | :statuscode 200: no error
553 | :statuscode 403: not authorized to view the job's data
554 | :statuscode 404: job id not found
555 | :statuscode 409: an error occurred
556 | """
557 | job_dict = db.get_job(job_id)
558 | if not job_dict:
559 | return json.dumps({"error": "job_id not found"}), 404, headers
560 | if not is_authorized(job_dict):
561 | return json.dumps({"error": "not authorized"}), 403, headers
562 | if job_dict["error"]:
563 | return json.dumps({"error": job_dict["error"]}), 409, headers
564 | content_type = job_dict["metadata"].get("mimetype")
565 | return flask.Response(job_dict["data"], mimetype=content_type)
566 |
567 |
568 | @app.route("/job/", methods=["POST"])
569 | @app.route("/job", methods=["POST"])
570 | def job(job_id=None):
571 | """Submit a job. If no id is provided, a random id will be generated.
572 |
573 | :param job_type: Which kind of job should be run. Has to be one of the
574 | available job types.
575 | :type job_type: string
576 | :param api_key: An API key that is needed to execute the job. This could
577 | be a CKAN API key that is needed to write any data. The key will also be
578 | used to administer jobs. If you don't want to use a real API key, you can
579 | provide a random string that you keep secure.
580 | :type api_key: string
581 | :param data: Data that is send to the job as input. (Optional)
582 | :type data: json encodable data
583 | :param result_url: Callback url that is called once the job has finished.
584 | (Optional)
585 | :type result_url: url string
586 | :param metadata: Data needed for the execution of the job which is not
587 | the input data. (Optional)
588 | :type metadata: list of key - value pairs
589 |
590 | **Results:**
591 |
592 | :rtype: A dictionary with the following keys
593 | :param job_id: An identifier for the job
594 | :type job_id: string
595 | :param job_key: A key that is required to view and administer the job
596 | :type job_key: string
597 |
598 | :statuscode 200: no error
599 | :statuscode 409: an error occurred
600 |
601 | """
602 | if not job_id:
603 | job_id = str(uuid.uuid4())
604 |
605 | # key required for job administration
606 | job_key = str(uuid.uuid4())
607 |
608 | ############# ERROR CHECKING ################
609 | try:
610 | input = flask.request.json
611 | except werkzeug.exceptions.BadRequest:
612 | return json.dumps({"error": "Malformed json"}), 409, headers
613 |
614 | # Idk why but this is needed for some libraries that
615 | # send malformed content types
616 | content_type = flask.request.content_type or ""
617 | if not input and "application/json" in content_type.lower():
618 | try:
619 | input = json.loads(flask.request.data)
620 | except ValueError:
621 | pass
622 | if not input:
623 | return (
624 | json.dumps(
625 | {
626 | "error": (
627 | "Not recognised as json, make "
628 | "sure content type is application/"
629 | "json"
630 | )
631 | }
632 | ),
633 | 409,
634 | headers,
635 | )
636 |
637 | ACCEPTED_ARGUMENTS = set(
638 | ["job_type", "data", "metadata", "result_url", "api_key", "metadata"]
639 | )
640 | extra_keys = set(input.keys()) - ACCEPTED_ARGUMENTS
641 | if extra_keys:
642 | return (
643 | json.dumps(
644 | {
645 | "error": (
646 | "Too many arguments. Extra keys are {}".format(
647 | ", ".join(extra_keys)
648 | )
649 | )
650 | }
651 | ),
652 | 409,
653 | headers,
654 | )
655 |
656 | # check result_url here as good to give warning early.
657 | result_url = input.get("result_url")
658 | if result_url and not result_url.startswith("http"):
659 | return json.dumps({"error": "result_url has to start with http"}), 409, headers
660 |
661 | job_type = input.get("job_type")
662 | if not job_type:
663 | return json.dumps({"error": "Please specify a job type"}), 409, headers
664 |
665 | job_types = list(async_types.keys()) + list(sync_types.keys())
666 |
667 | if job_type not in job_types:
668 | error_string = ("Job type {} not available. Available job types are {}").format(
669 | job_type, ", ".join(sorted(job_types))
670 | )
671 | return json.dumps({"error": error_string}), 409, headers
672 |
673 | api_key = input.get("api_key")
674 | if not api_key:
675 | return json.dumps({"error": "Please provide your API key."}), 409, headers
676 |
677 | metadata = input.get("metadata", {})
678 | if not isinstance(metadata, dict):
679 | return json.dumps({"error": "metadata has to be a json object"}), 409, headers
680 | ############# END CHECKING ################
681 |
682 | synchronous_job = sync_types.get(job_type)
683 | if synchronous_job:
684 | return run_synchronous_job(synchronous_job, job_id, job_key, input)
685 | else:
686 | asynchronous_job = async_types.get(job_type)
687 | return run_asynchronous_job(asynchronous_job, job_id, job_key, input)
688 |
689 |
690 | def run_synchronous_job(job, job_id, job_key, input):
691 | try:
692 | db.add_pending_job(job_id, job_key, **input)
693 | except sa.exc.IntegrityError as e:
694 | error_string = "job_id {} already exists".format(job_id)
695 | return json.dumps({"error": error_string}), 409, headers
696 |
697 | try:
698 | result = job(job_id, input)
699 |
700 | if hasattr(result, "__call__"):
701 | db.mark_job_as_completed(job_id)
702 | return flask.Response(result(), mimetype="application/json")
703 | else:
704 | db.mark_job_as_completed(job_id, result)
705 |
706 | except util.JobError as e:
707 | db.mark_job_as_errored(job_id, e.as_dict())
708 | except Exception as e:
709 | db.mark_job_as_errored(
710 | job_id, traceback.format_tb(sys.exc_info()[2])[-1] + repr(e)
711 | )
712 |
713 | api_key = db.get_job(job_id)["api_key"]
714 | result_ok = send_result(job_id, api_key)
715 |
716 | if not result_ok:
717 | db.mark_job_as_failed_to_post_result(job_id)
718 |
719 | return job_status(job_id=job_id, show_job_key=True, ignore_auth=True)
720 |
721 |
722 | def run_asynchronous_job(job, job_id, job_key, input):
723 | if not scheduler.running:
724 | scheduler.start()
725 | try:
726 | db.add_pending_job(job_id, job_key, **input)
727 | except sa.exc.IntegrityError:
728 | error_string = "job_id {} already exists".format(job_id)
729 | return json.dumps({"error": error_string}), 409, headers
730 | trigger = DateTrigger()
731 | aps_job = scheduler.add_job(job, trigger, [job_id, input], None)
732 |
733 | db.set_aps_job_id(job_id, aps_job.id)
734 |
735 | return job_status(job_id=job_id, show_job_key=True, ignore_auth=True)
736 |
737 |
738 | def is_authorized(job=None):
739 | """Returns true if the request is authorized for the job
740 | if provided. If no job is provided, the user has to be admin
741 | to be authorized.
742 | """
743 | if flogin.current_user.is_authenticated:
744 | return True
745 | if job:
746 | job_key = flask.request.headers.get("Authorization")
747 | if job_key == app.config.get("SECRET_KEY"):
748 | return True
749 | return job["job_key"] == job_key
750 | return False
751 |
752 |
753 | def send_result(job_id, api_key=None):
754 | """Send results to where requested.
755 |
756 | If api_key is provided, it is used, otherwiese
757 | the key from the job will be used.
758 | """
759 | job_dict = db.get_job(job_id)
760 | result_url = job_dict.get("result_url")
761 |
762 | if not result_url:
763 |
764 | # A job with an API key (for using when posting to the callback URL)
765 | # but no callback URL is weird, but it can happen.
766 | db.delete_api_key(job_id)
767 |
768 | return True
769 |
770 | api_key_from_job = job_dict.pop("api_key", None)
771 | if not api_key:
772 | api_key = api_key_from_job
773 | headers = {"Content-Type": "application/json"}
774 | if api_key:
775 | if ":" in api_key:
776 | header, key = api_key.split(":")
777 | else:
778 | header, key = "Authorization", api_key
779 | headers[header] = key
780 |
781 | try:
782 | result = requests.post(
783 | result_url,
784 | data=json.dumps(job_dict, cls=DatetimeJsonEncoder),
785 | headers=headers,
786 | verify=SSL_VERIFY,
787 | )
788 |
789 | db.delete_api_key(job_id)
790 |
791 | except requests.ConnectionError:
792 | return False
793 |
794 | return result.status_code == requests.codes.ok
795 |
796 |
797 | def main():
798 | init()
799 | app.run(app.config.get("HOST"), app.config.get("PORT"))
800 |
801 |
802 | if __name__ == "__main__":
803 | main()
804 |
--------------------------------------------------------------------------------
/doc/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = _build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/messytables.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/messytables.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/messytables"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/messytables"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | make -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/doc/_themes/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2010 by Armin Ronacher.
2 |
3 | Some rights reserved.
4 |
5 | Redistribution and use in source and binary forms of the theme, with or
6 | without modification, are permitted provided that the following conditions
7 | are met:
8 |
9 | * Redistributions of source code must retain the above copyright
10 | notice, this list of conditions and the following disclaimer.
11 |
12 | * Redistributions in binary form must reproduce the above
13 | copyright notice, this list of conditions and the following
14 | disclaimer in the documentation and/or other materials provided
15 | with the distribution.
16 |
17 | * The names of the contributors may not be used to endorse or
18 | promote products derived from this software without specific
19 | prior written permission.
20 |
21 | We kindly ask you to only use these themes in an unmodified manner just
22 | for Flask and Flask-related products, not for unrelated projects. If you
23 | like the visual style and want to use it for your own projects, please
24 | consider making some larger changes to the themes (such as changing
25 | font faces, sizes, colors or margins).
26 |
27 | THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
28 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 | ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE
37 | POSSIBILITY OF SUCH DAMAGE.
38 |
--------------------------------------------------------------------------------
/doc/_themes/flask_small/layout.html:
--------------------------------------------------------------------------------
1 | {% extends "basic/layout.html" %}
2 | {% block header %}
3 | {{ super() }}
4 | {% if pagename == 'index' %}
5 |