ckanext-xloader 2.3.0__tar.gz → 2.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/CHANGELOG +11 -0
  2. {ckanext_xloader-2.3.0/ckanext_xloader.egg-info → ckanext_xloader-2.3.1}/PKG-INFO +30 -2
  3. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/README.md +29 -1
  4. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/action.py +11 -36
  5. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/auth.py +3 -2
  6. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/config_declaration.yaml +7 -0
  7. ckanext_xloader-2.3.1/ckanext/xloader/interfaces.py +93 -0
  8. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/jobs.py +110 -94
  9. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/loader.py +114 -75
  10. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/parser.py +1 -1
  11. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/plugin.py +2 -0
  12. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_action.py +14 -0
  13. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_chunks.py +33 -34
  14. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_jobs.py +20 -14
  15. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_loader.py +113 -0
  16. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_parser.py +29 -0
  17. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/utils.py +9 -0
  18. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1/ckanext_xloader.egg-info}/PKG-INFO +30 -2
  19. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/pyproject.toml +2 -2
  20. ckanext_xloader-2.3.0/ckanext/xloader/interfaces.py +0 -49
  21. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/LICENSE +0 -0
  22. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/MANIFEST.in +0 -0
  23. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/__init__.py +0 -0
  24. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/__init__.py +0 -0
  25. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/cli.py +0 -0
  26. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/command.py +0 -0
  27. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/db.py +0 -0
  28. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/helpers.py +0 -0
  29. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/job_exceptions.py +0 -0
  30. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/schema.py +0 -0
  31. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/datastore/snippets/dictionary_form.html +0 -0
  32. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/package/resource_edit_base.html +0 -0
  33. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/package/resource_read.html +0 -0
  34. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/package/snippets/resource_info.html +0 -0
  35. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/package/snippets/resource_item.html +0 -0
  36. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/package/snippets/resources.html +0 -0
  37. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/xloader/confirm_datastore_delete.html +0 -0
  38. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/templates/xloader/resource_data.html +0 -0
  39. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/__init__.py +0 -0
  40. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/ckan_setup.py +0 -0
  41. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/fixtures.py +0 -0
  42. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_plugin.py +0 -0
  43. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/tests/test_utils.py +0 -0
  44. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/views.py +0 -0
  45. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/webassets/css/xloader.css +0 -0
  46. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext/xloader/webassets/webassets.yml +0 -0
  47. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext_xloader.egg-info/SOURCES.txt +0 -0
  48. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext_xloader.egg-info/dependency_links.txt +0 -0
  49. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext_xloader.egg-info/entry_points.txt +0 -0
  50. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext_xloader.egg-info/requires.txt +0 -0
  51. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/ckanext_xloader.egg-info/top_level.txt +0 -0
  52. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/dev-requirements.txt +0 -0
  53. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/requirements.txt +0 -0
  54. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/setup.cfg +0 -0
  55. {ckanext_xloader-2.3.0 → ckanext_xloader-2.3.1}/setup.py +0 -0
@@ -2,6 +2,17 @@ CHANGELOG
2
2
  =========
3
3
  See: https://github.com/ckan/ckanext-xloader/releases if this file has drifted.
4
4
 
5
+ 2.3.1 2025-04-30
6
+ ================
7
+
8
+ ## Feat:
9
+
10
+ * #275 Implement a new Interface function for datastore_before_update
11
+
12
+ ## Fix
13
+
14
+ * #274 Qld gov au GitHub 272 extra cells, multiple queues
15
+
5
16
  2.0.1 2025-03-04
6
17
  ================
7
18
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckanext-xloader
3
- Version: 2.3.0
3
+ Version: 2.3.1
4
4
  Summary: Express Loader - quickly load data into CKAN DataStore
5
5
  Author: David Read (davidread), Patricio Del Boca (pdelboca)
6
6
  Author-email: ThrawnCA <carl.antuar@smartservice.qld.gov.au>, "Jesse Vickery (JVickery-TBS)" <jesse.vickery@tbs-sct.gc.ca>, "Adrià Mercader (amercader)" <amercadero@gmail.com>, "Brett Jones (kowh-ai)" <datashades@linkdigital.com.au>, "William Dutton (duttonw)" <william.dutton@qld.gov.au>
@@ -277,6 +277,20 @@ Default value: `1000000000`
277
277
 
278
278
  The maximum file size that XLoader will attempt to load.
279
279
 
280
+ #### ckanext.xloader.queue_names
281
+
282
+ Example:
283
+
284
+ ```
285
+ ckanext.xloader.queue_names = foo baz
286
+ ```
287
+
288
+ Default value: `default`
289
+
290
+ A whitespace-separated list of worker queues that XLoader jobs can be sent to.
291
+
292
+ By default, jobs for the same package will be sent to the same queue,
293
+ to reduce database lock contention.
280
294
 
281
295
  #### ckanext.xloader.use_type_guessing
282
296
 
@@ -433,6 +447,20 @@ Controls whether or not the status badges display all of the statuses. By defaul
433
447
  the badges will display "pending", "running", and "error". With debug_badges enabled,
434
448
  they will also display "complete", "active", "inactive", and "unknown".
435
449
 
450
+ #### ckanext.xloader.queue_names
451
+
452
+ Example:
453
+
454
+ ```
455
+ ckanext.xloader.queue_names = foo,baz
456
+ ```
457
+
458
+ Default value: 'default'
459
+
460
+ Defines the queue(s) available to use for XLoader jobs.
461
+ Jobs for the same package will be sent to the same queue,
462
+ to reduce lock contention.
463
+
436
464
  #### ckanext.xloader.validation.requires_successful_report
437
465
 
438
466
  Supports: __ckanext-validation__
@@ -464,7 +492,7 @@ Controls whether or not a resource requires a Validation Schema to be present fr
464
492
  #### ckanext.xloader.site_url
465
493
  Provide an alternate site URL for the xloader_submit action.
466
494
  This is useful, for example, when the site is running within a docker network.
467
-
495
+
468
496
  Note: This setting will not alter path. i.e ckan.root_path
469
497
 
470
498
  Example:
@@ -253,6 +253,20 @@ Default value: `1000000000`
253
253
 
254
254
  The maximum file size that XLoader will attempt to load.
255
255
 
256
+ #### ckanext.xloader.queue_names
257
+
258
+ Example:
259
+
260
+ ```
261
+ ckanext.xloader.queue_names = foo baz
262
+ ```
263
+
264
+ Default value: `default`
265
+
266
+ A whitespace-separated list of worker queues that XLoader jobs can be sent to.
267
+
268
+ By default, jobs for the same package will be sent to the same queue,
269
+ to reduce database lock contention.
256
270
 
257
271
  #### ckanext.xloader.use_type_guessing
258
272
 
@@ -409,6 +423,20 @@ Controls whether or not the status badges display all of the statuses. By defaul
409
423
  the badges will display "pending", "running", and "error". With debug_badges enabled,
410
424
  they will also display "complete", "active", "inactive", and "unknown".
411
425
 
426
+ #### ckanext.xloader.queue_names
427
+
428
+ Example:
429
+
430
+ ```
431
+ ckanext.xloader.queue_names = foo,baz
432
+ ```
433
+
434
+ Default value: 'default'
435
+
436
+ Defines the queue(s) available to use for XLoader jobs.
437
+ Jobs for the same package will be sent to the same queue,
438
+ to reduce lock contention.
439
+
412
440
  #### ckanext.xloader.validation.requires_successful_report
413
441
 
414
442
  Supports: __ckanext-validation__
@@ -440,7 +468,7 @@ Controls whether or not a resource requires a Validation Schema to be present fr
440
468
  #### ckanext.xloader.site_url
441
469
  Provide an alternate site URL for the xloader_submit action.
442
470
  This is useful, for example, when the site is running within a docker network.
443
-
471
+
444
472
  Note: This setting will not alter path. i.e ckan.root_path
445
473
 
446
474
  Example:
@@ -5,10 +5,11 @@ import datetime
5
5
  import json
6
6
  import logging
7
7
 
8
- import ckan.lib.jobs as rq_jobs
8
+ from ckan.lib.jobs import get_queue
9
9
  import ckan.lib.navl.dictization_functions
10
10
  from ckan.logic import side_effect_free
11
11
  import ckan.plugins as p
12
+ from ckan.plugins.toolkit import config, enqueue_job, get_or_bust
12
13
  from dateutil.parser import parse as parse_date
13
14
  from dateutil.parser import isoparse as parse_iso_date
14
15
 
@@ -16,13 +17,8 @@ import ckanext.xloader.schema
16
17
 
17
18
  from . import interfaces as xloader_interfaces, jobs, db, utils
18
19
 
19
- enqueue_job = p.toolkit.enqueue_job
20
- get_queue = rq_jobs.get_queue
21
-
22
20
  log = logging.getLogger(__name__)
23
- config = p.toolkit.config
24
21
 
25
- _get_or_bust = p.toolkit.get_or_bust
26
22
  _validate = ckan.lib.navl.dictization_functions.validate
27
23
 
28
24
 
@@ -48,7 +44,6 @@ def xloader_submit(context, data_dict):
48
44
  '''
49
45
  p.toolkit.check_access('xloader_submit', context, data_dict)
50
46
  api_key = utils.get_xloader_user_apitoken()
51
- custom_queue = data_dict.pop('queue', rq_jobs.DEFAULT_QUEUE_NAME)
52
47
  schema = context.get('schema', ckanext.xloader.schema.xloader_submit_schema())
53
48
  data_dict, errors = _validate(data_dict, schema, context)
54
49
  if errors:
@@ -68,6 +63,8 @@ def xloader_submit(context, data_dict):
68
63
  })
69
64
  except p.toolkit.ObjectNotFound:
70
65
  return False
66
+ package_id = resource_dict.get('package_id')
67
+ custom_queue = data_dict.pop('queue', jobs.get_default_queue_name(package_id))
71
68
 
72
69
  for plugin in p.PluginImplementations(xloader_interfaces.IXloader):
73
70
  upload = plugin.can_upload(res_id)
@@ -158,11 +155,12 @@ def xloader_submit(context, data_dict):
158
155
  'set_url_type': data_dict.get('set_url_type', False),
159
156
  'task_created': task['last_updated'],
160
157
  'original_url': resource_dict.get('url'),
158
+ 'queue_name': custom_queue,
161
159
  }
162
160
  }
163
- if custom_queue != rq_jobs.DEFAULT_QUEUE_NAME:
161
+ if custom_queue not in jobs.default_queue_names:
164
162
  # Don't automatically retry if it's a custom run
165
- data['metadata']['tries'] = jobs.MAX_RETRIES
163
+ data['metadata']['tries'] = jobs.max_retries
166
164
 
167
165
  # Expand timeout for resources that have to be type-guessed
168
166
  timeout = config.get(
@@ -173,7 +171,7 @@ def xloader_submit(context, data_dict):
173
171
  try:
174
172
  job = enqueue_job(
175
173
  jobs.xloader_data_into_datastore, [data], queue=custom_queue,
176
- title="xloader_submit: package: {} resource: {}".format(resource_dict.get('package_id'), res_id),
174
+ title="xloader_submit: package: {} resource: {}".format(package_id, res_id),
177
175
  rq_kwargs=dict(timeout=timeout, at_front=sync)
178
176
  )
179
177
  except Exception:
@@ -200,29 +198,6 @@ def xloader_submit(context, data_dict):
200
198
  return True
201
199
 
202
200
 
203
- def _enqueue(fn, args=None, kwargs=None, title=None, queue='default',
204
- timeout=180):
205
- '''Same as latest ckan.lib.jobs.enqueue - earlier CKAN versions dont have
206
- the timeout param
207
-
208
- This function can be removed when dropping support for 2.7
209
- '''
210
- if args is None:
211
- args = []
212
- if kwargs is None:
213
- kwargs = {}
214
- job = get_queue(queue).enqueue_call(func=fn, args=args, kwargs=kwargs,
215
- timeout=timeout)
216
- job.meta[u'title'] = title
217
- job.save()
218
- msg = u'Added background job {}'.format(job.id)
219
- if title:
220
- msg = u'{} ("{}")'.format(msg, title)
221
- msg = u'{} to queue "{}"'.format(msg, queue)
222
- log.info(msg)
223
- return job
224
-
225
-
226
201
  def xloader_hook(context, data_dict):
227
202
  ''' Update xloader task. This action is typically called by ckanext-xloader
228
203
  whenever the status of a job changes.
@@ -254,9 +229,9 @@ def xloader_hook(context, data_dict):
254
229
 
255
230
  '''
256
231
 
257
- metadata, status = _get_or_bust(data_dict, ['metadata', 'status'])
232
+ metadata, status = get_or_bust(data_dict, ['metadata', 'status'])
258
233
 
259
- res_id = _get_or_bust(metadata, 'resource_id')
234
+ res_id = get_or_bust(metadata, 'resource_id')
260
235
 
261
236
  # Pass metadata, not data_dict, as it contains the resource id needed
262
237
  # on the auth checks
@@ -338,7 +313,7 @@ def xloader_status(context, data_dict):
338
313
 
339
314
  if 'id' in data_dict:
340
315
  data_dict['resource_id'] = data_dict['id']
341
- res_id = _get_or_bust(data_dict, 'resource_id')
316
+ res_id = get_or_bust(data_dict, 'resource_id')
342
317
 
343
318
  task = p.toolkit.get_action('task_status_show')(context, {
344
319
  'entity_id': res_id,
@@ -1,5 +1,6 @@
1
1
  from ckan import authz
2
- from ckan.lib import jobs as rq_jobs
2
+
3
+ from .jobs import default_queue_names
3
4
 
4
5
  import ckanext.datastore.logic.auth as auth
5
6
 
@@ -7,7 +8,7 @@ import ckanext.datastore.logic.auth as auth
7
8
  def xloader_submit(context, data_dict):
8
9
  # only sysadmins can specify a custom processing queue
9
10
  custom_queue = data_dict.get('queue')
10
- if custom_queue and custom_queue != rq_jobs.DEFAULT_QUEUE_NAME:
11
+ if custom_queue and custom_queue not in default_queue_names:
11
12
  return authz.is_authorized('config_option_update', context, data_dict)
12
13
  return auth.datastore_auth(context, data_dict)
13
14
 
@@ -163,6 +163,13 @@ groups:
163
163
 
164
164
  See https://github.com/frictionlessdata/ckanext-validation?tab=readme-ov-file#data-schema
165
165
  for more details.
166
+ - key: ckanext.xloader.queue_names
167
+ default: default
168
+ example: foo baz
169
+ description: |
170
+ A whitespace-separated list of queues to enqueue XLoader jobs to.
171
+ Jobs for the same package will be sent to the same queue.
172
+ required: false
166
173
  - key: ckanext.xloader.clean_datastore_tables
167
174
  default: False
168
175
  example: True
@@ -0,0 +1,93 @@
1
+ from ckan.plugins.interfaces import Interface
2
+
3
+
4
+ class IXloader(Interface):
5
+ """
6
+ The IXloader interface allows plugin authors to receive notifications
7
+ before and after a resource is submitted to the xloader service, as
8
+ well as determining whether a resource should be submitted in can_upload
9
+
10
+ The before_submit function, when implemented
11
+ """
12
+
13
+ def can_upload(self, resource_id):
14
+ """ This call when implemented can be used to stop the processing of
15
+ the xloader submit function. This method will not be called if
16
+ the resource format does not match those defined in the
17
+ ckanext.xloader.formats config option or the default formats.
18
+
19
+ If this function returns False then processing will be aborted,
20
+ whilst returning True will submit the resource to the xloader
21
+ service
22
+
23
+ Note that before reaching this hook there is a prior check on the
24
+ resource format, which depends on the value of
25
+ the :ref:`ckanext.xloader.formats` configuration option (and requires
26
+ the resource to have a format defined).
27
+
28
+ :param resource_id: The ID of the resource that is to be
29
+ pushed to the xloader service.
30
+
31
+ Returns ``True`` if the job should be submitted and ``False`` if
32
+ the job should be aborted
33
+
34
+ :rtype: bool
35
+ """
36
+ return True
37
+
38
+ def after_upload(self, context, resource_dict, dataset_dict):
39
+ """ After a resource has been successfully upload to the datastore
40
+ this method will be called with the resource dictionary and the
41
+ package dictionary for this resource.
42
+
43
+ :param context: The context within which the upload happened
44
+ :param resource_dict: The dict represenstaion of the resource that was
45
+ successfully uploaded to the datastore
46
+ :param dataset_dict: The dict represenstation of the dataset containing
47
+ the resource that was uploaded
48
+ """
49
+ pass
50
+
51
+ def datastore_before_update(self, resource_id, existing_fields, new_headers):
52
+ """ Called by the loader just before it is about to modify the
53
+ DataStore table for a resource (truncate, drop+recreate, or create).
54
+ It allows plugins to inspect the difference between the current
55
+ DataStore columns and the ones detected in the incoming file, for
56
+ example to log an activity when columns are added, removed or
57
+ renamed.
58
+
59
+ Both ``existing_fields`` and ``new_headers`` are lists of field
60
+ dicts that contain at least an ``id`` key, so a plugin can compute
61
+ the diff symmetrically::
62
+
63
+ old_ids = {f['id'] for f in existing_fields or []}
64
+ new_ids = {h['id'] for h in new_headers}
65
+ added = new_ids - old_ids
66
+ removed = old_ids - new_ids
67
+
68
+ :param resource_id: the ID of the resource whose DataStore table is
69
+ about to be updated.
70
+ :type resource_id: string
71
+
72
+ :param existing_fields: the current columns of the DataStore table
73
+ (the internal ``_id`` column is excluded), or ``None`` if the
74
+ DataStore table does not yet exist. Each dict contains at least
75
+ ``id`` and ``type`` and may include ``info`` for fields with a
76
+ Data Dictionary entry.
77
+ :type existing_fields: list of dicts or None
78
+
79
+ :param new_headers: the list of field dicts that will be written to
80
+ the DataStore. Each dict has at least an ``id`` and ``type``
81
+ key, and may include an ``info`` dict for fields that already
82
+ existed.
83
+ :type new_headers: list of dicts
84
+
85
+ The ``new_headers`` param is the same list the loader will use after the
86
+ hook returns, so mutating it (adding, removing, renaming fields)
87
+ will affect the subsequent DataStore operation.
88
+ The ``existing_fields`` is a snapshot with the internal ``_id`` column
89
+ excluded and should be treated as read-only.
90
+
91
+ The return value is ignored.
92
+ """
93
+ pass
@@ -18,11 +18,12 @@ from rq import get_current_job
18
18
  from rq.timeouts import JobTimeoutException
19
19
  import sqlalchemy as sa
20
20
 
21
+ from ckan.lib.jobs import DEFAULT_QUEUE_NAME
21
22
  from ckan.plugins.toolkit import get_action, asbool, enqueue_job, ObjectNotFound, config, h
22
23
 
23
24
  from . import db, loader
24
25
  from .job_exceptions import JobError, HTTPError, DataTooBigError, FileCouldNotBeLoadedError, LoaderError, XLoaderTimeoutError
25
- from .utils import datastore_resource_exists, set_resource_metadata, modify_input_url
26
+ from .utils import cleanup_temp_file, datastore_resource_exists, set_resource_metadata, modify_input_url
26
27
 
27
28
 
28
29
  from ckan.lib.api_token import get_user_from_token
@@ -48,6 +49,7 @@ max_excerpt_lines = None
48
49
  max_retries = None
49
50
  retried_job_timeout = None
50
51
  apitoken_header_name = None
52
+ default_queue_names = DEFAULT_QUEUE_NAME.split()
51
53
 
52
54
 
53
55
  def is_retryable_error(error):
@@ -61,7 +63,6 @@ def is_retryable_error(error):
61
63
  Retryable HTTP status codes:
62
64
  - 408 Request Timeout
63
65
  - 429 Too Many Requests
64
- - 500 Internal Server Error
65
66
  - 502 Bad Gateway
66
67
  - 503 Service Unavailable
67
68
  - 504 Gateway Timeout
@@ -75,7 +76,7 @@ def is_retryable_error(error):
75
76
  :rtype: bool
76
77
  """
77
78
  if isinstance(error, HTTPError):
78
- retryable_status_codes = {408, 429, 500, 502, 503, 504, 507, 522, 524}
79
+ retryable_status_codes = {408, 429, 502, 503, 504, 507, 522, 524}
79
80
  return error.status_code in retryable_status_codes
80
81
  else:
81
82
  return True
@@ -96,6 +97,25 @@ def is_retryable_error(error):
96
97
  # }
97
98
  # }
98
99
 
100
+
101
+ def get_default_queue_name(package_id=None):
102
+ """ Retrieve the queue to be used in submitting jobs for the specified dataset.
103
+
104
+ By sending all jobs for a dataset to the same queue, lock conflicts are reduced.
105
+ """
106
+ if not default_queue_names:
107
+ return DEFAULT_QUEUE_NAME
108
+ if not package_id:
109
+ return default_queue_names[0]
110
+
111
+ # Pick a queue by taking the first character of the package name
112
+ # and converting it into a numeric index to the list of queue names.
113
+ # We don't want a proper hash function, because those tend to add
114
+ # complications for the sake of (unnecessary) cryptographic strength.
115
+ queue_index = ord(package_id[0]) % len(default_queue_names)
116
+ return default_queue_names[queue_index]
117
+
118
+
99
119
  def xloader_data_into_datastore(input):
100
120
  '''This is the func that is queued. It is a wrapper for
101
121
  xloader_data_into_datastore_, and makes sure it finishes by calling
@@ -245,94 +265,90 @@ def xloader_data_into_datastore_(input, job_dict, logger):
245
265
  tmp_file, file_hash = _download_resource_data(resource, data, api_key,
246
266
  logger)
247
267
 
248
- if (resource.get('hash') == file_hash
249
- and not data.get('ignore_hash')):
250
- logger.info('Ignoring resource - the file hash hasn\'t changed: '
251
- '{hash}.'.format(hash=file_hash))
252
- return
253
- logger.info('File hash: %s', file_hash)
254
- resource['hash'] = file_hash
255
-
256
- def direct_load(allow_type_guessing=False):
257
- fields = loader.load_csv(
258
- tmp_file.name,
259
- resource_id=resource['id'],
260
- mimetype=resource.get('format'),
261
- allow_type_guessing=allow_type_guessing,
262
- logger=logger)
263
- loader.calculate_record_count(
264
- resource_id=resource['id'], logger=logger)
265
- set_datastore_active(data, resource, logger)
266
- if 'result_url' in input:
267
- job_dict['status'] = 'running_but_viewable'
268
- callback_xloader_hook(result_url=input['result_url'],
269
- api_key=api_key,
270
- job_dict=job_dict)
271
- logger.info('Data now available to users: %s', resource_ckan_url)
272
- loader.create_column_indexes(
273
- fields=fields,
274
- resource_id=resource['id'],
275
- logger=logger)
276
- update_resource(resource={'id': resource['id'], 'hash': resource['hash']},
277
- patch_only=True)
278
- logger.info('File Hash updated for resource: %s', resource['hash'])
279
-
280
- def tabulator_load():
281
- try:
282
- loader.load_table(tmp_file.name,
283
- resource_id=resource['id'],
284
- mimetype=resource.get('format'),
285
- logger=logger)
286
- except JobError as e:
287
- logger.error('Error during tabulator load: %s', e)
288
- raise
289
- loader.calculate_record_count(
290
- resource_id=resource['id'], logger=logger)
291
- set_datastore_active(data, resource, logger)
292
- logger.info('Finished loading with tabulator')
293
- update_resource(resource={'id': resource['id'], 'hash': resource['hash']},
294
- patch_only=True)
295
- logger.info('File Hash updated for resource: %s', resource['hash'])
296
-
297
- # Load it
298
- logger.info('Loading CSV')
299
- # If ckanext.xloader.use_type_guessing is not configured, fall back to
300
- # deprecated ckanext.xloader.just_load_with_messytables
301
- use_type_guessing = asbool(
302
- config.get('ckanext.xloader.use_type_guessing', config.get(
303
- 'ckanext.xloader.just_load_with_messytables', False))) \
304
- and not datastore_resource_exists(resource['id']) \
305
- and os.path.getsize(tmp_file.name) <= max_type_guessing_length
306
- logger.info("'use_type_guessing' mode is: %s", use_type_guessing)
307
-
308
268
  try:
309
- if use_type_guessing:
269
+ if (resource.get('hash') == file_hash
270
+ and not data.get('ignore_hash')):
271
+ logger.info('Ignoring resource - the file hash hasn\'t changed: '
272
+ '{hash}.'.format(hash=file_hash))
273
+ return
274
+ logger.info('File hash: %s', file_hash)
275
+ resource['hash'] = file_hash
276
+
277
+ def direct_load(allow_type_guessing=False):
278
+ fields = loader.load_csv(
279
+ tmp_file.name,
280
+ resource_id=resource['id'],
281
+ mimetype=resource.get('format'),
282
+ allow_type_guessing=allow_type_guessing,
283
+ logger=logger)
284
+ loader.calculate_record_count(
285
+ resource_id=resource['id'], logger=logger)
286
+ set_datastore_active(data, resource, logger)
287
+ if 'result_url' in input:
288
+ job_dict['status'] = 'running_but_viewable'
289
+ callback_xloader_hook(result_url=input['result_url'],
290
+ api_key=api_key,
291
+ job_dict=job_dict)
292
+ logger.info('Data now available to users: %s', resource_ckan_url)
293
+ loader.create_column_indexes(
294
+ fields=fields,
295
+ resource_id=resource['id'],
296
+ logger=logger)
297
+ update_resource(resource={'id': resource['id'], 'hash': resource['hash']},
298
+ patch_only=True)
299
+ logger.info('File Hash updated for resource: %s', resource['hash'])
300
+
301
+ def tabulator_load():
310
302
  try:
311
- tabulator_load()
303
+ loader.load_table(tmp_file.name,
304
+ resource_id=resource['id'],
305
+ mimetype=resource.get('format'),
306
+ logger=logger)
312
307
  except JobError as e:
313
- logger.warning('Load using tabulator failed: %s', e)
314
- logger.info('Trying again with direct COPY')
315
- direct_load()
316
- else:
317
- try:
318
- direct_load(allow_type_guessing=True)
319
- except (JobError, LoaderError) as e:
320
- logger.warning('Load using COPY failed: %s', e)
321
- logger.info('Trying again with tabulator')
322
- tabulator_load()
323
- except JobTimeoutException:
324
- logger.warning('Job timed out after %ss', retried_job_timeout)
325
- raise JobError('Job timed out after {}s'.format(retried_job_timeout))
326
- except FileCouldNotBeLoadedError as e:
327
- logger.warning('Loading excerpt for this format not supported.')
328
- logger.error('Loading file raised an error: %s', e)
329
- raise JobError('Loading file raised an error: {}'.format(e))
330
- finally:
308
+ logger.error('Error during tabulator load: %s', e)
309
+ raise
310
+ loader.calculate_record_count(
311
+ resource_id=resource['id'], logger=logger)
312
+ set_datastore_active(data, resource, logger)
313
+ logger.info('Finished loading with tabulator')
314
+ update_resource(resource={'id': resource['id'], 'hash': resource['hash']},
315
+ patch_only=True)
316
+ logger.info('File Hash updated for resource: %s', resource['hash'])
317
+
318
+ # Load it
319
+ logger.info('Loading CSV')
320
+ # If ckanext.xloader.use_type_guessing is not configured, fall back to
321
+ # deprecated ckanext.xloader.just_load_with_messytables
322
+ use_type_guessing = asbool(
323
+ config.get('ckanext.xloader.use_type_guessing', config.get(
324
+ 'ckanext.xloader.just_load_with_messytables', False))) \
325
+ and not datastore_resource_exists(resource['id']) \
326
+ and os.path.getsize(tmp_file.name) <= max_type_guessing_length
327
+ logger.info("'use_type_guessing' mode is: %s", use_type_guessing)
331
328
  try:
332
- tmp_file.close()
333
- os.remove(tmp_file.name)
334
- except FileNotFoundError:
335
- pass
329
+ if use_type_guessing:
330
+ try:
331
+ tabulator_load()
332
+ except JobError as e:
333
+ logger.warning('Load using tabulator failed: %s', e)
334
+ logger.info('Trying again with direct COPY')
335
+ direct_load()
336
+ else:
337
+ try:
338
+ direct_load(allow_type_guessing=True)
339
+ except (JobError, LoaderError) as e:
340
+ logger.warning('Load using COPY failed: %s', e)
341
+ logger.info('Trying again with tabulator')
342
+ tabulator_load()
343
+ except JobTimeoutException:
344
+ logger.warning('Job timed out after %ss', retried_job_timeout)
345
+ raise JobError('Job timed out after {}s'.format(retried_job_timeout))
346
+ except FileCouldNotBeLoadedError as e:
347
+ logger.warning('Loading excerpt for this format not supported.')
348
+ logger.error('Loading file raised an error: %s', e)
349
+ raise JobError('Loading file raised an error: {}'.format(e))
350
+ finally:
351
+ cleanup_temp_file(tmp_file)
336
352
 
337
353
  logger.info('Express Load completed')
338
354
 
@@ -364,7 +380,7 @@ def _download_resource_data(resource, data, api_key, logger):
364
380
  logger.info('Fetching from: {0}'.format(url))
365
381
  tmp_file = get_tmp_file(url)
366
382
  length = 0
367
- m = hashlib.md5()
383
+ m = hashlib.md5(usedforsecurity=False)
368
384
  cl = None
369
385
  try:
370
386
  headers = {}
@@ -401,9 +417,9 @@ def _download_resource_data(resource, data, api_key, logger):
401
417
  data['datastore_contains_all_records_of_source_file'] = True
402
418
 
403
419
  except DataTooBigError:
404
- tmp_file.close()
420
+ cleanup_temp_file(tmp_file)
405
421
  message = 'Data too large to load into Datastore: ' \
406
- '{cl} bytes > max {max_cl} bytes.' \
422
+ '{cl} bytes > max {max_cl} bytes.' \
407
423
  .format(cl=cl or length, max_cl=max_content_length)
408
424
  logger.warning(message)
409
425
  if max_excerpt_lines <= 0:
@@ -426,7 +442,7 @@ def _download_resource_data(resource, data, api_key, logger):
426
442
  response.close()
427
443
  data['datastore_contains_all_records_of_source_file'] = False
428
444
  except requests.exceptions.HTTPError as error:
429
- tmp_file.close()
445
+ cleanup_temp_file(tmp_file)
430
446
  # status code error
431
447
  logger.debug('HTTP error: %s', error)
432
448
  raise HTTPError(
@@ -436,9 +452,9 @@ def _download_resource_data(resource, data, api_key, logger):
436
452
  except requests.exceptions.Timeout:
437
453
  logger.warning('URL time out after %ss', DOWNLOAD_TIMEOUT)
438
454
  raise XLoaderTimeoutError('Connection timed out after {}s'.format(
439
- DOWNLOAD_TIMEOUT))
455
+ DOWNLOAD_TIMEOUT))
440
456
  except requests.exceptions.RequestException as e:
441
- tmp_file.close()
457
+ cleanup_temp_file(tmp_file)
442
458
  try:
443
459
  err_message = str(e.reason)
444
460
  except AttributeError:
@@ -448,7 +464,7 @@ def _download_resource_data(resource, data, api_key, logger):
448
464
  message=err_message, status_code=None,
449
465
  request_url=url, response=None)
450
466
  except JobTimeoutException:
451
- tmp_file.close()
467
+ cleanup_temp_file(tmp_file)
452
468
  logger.warning('Job timed out after %ss', retried_job_timeout)
453
469
  raise JobError('Job timed out after {}s'.format(retried_job_timeout))
454
470