ckanext-xloader 2.0.1__tar.gz → 2.2.0__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 (54) hide show
  1. {ckanext_xloader-2.0.1/ckanext_xloader.egg-info → ckanext_xloader-2.2.0}/PKG-INFO +28 -4
  2. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/README.md +25 -2
  3. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/action.py +2 -1
  4. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/command.py +2 -2
  5. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/config_declaration.yaml +38 -5
  6. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/helpers.py +1 -1
  7. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/job_exceptions.py +5 -0
  8. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/jobs.py +112 -66
  9. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/loader.py +313 -249
  10. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/plugin.py +4 -18
  11. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/schema.py +1 -7
  12. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/test_action.py +19 -4
  13. ckanext_xloader-2.2.0/ckanext/xloader/tests/test_jobs.py +305 -0
  14. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/test_loader.py +22 -17
  15. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/test_plugin.py +3 -3
  16. ckanext_xloader-2.2.0/ckanext/xloader/tests/test_utils.py +70 -0
  17. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/utils.py +97 -38
  18. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0/ckanext_xloader.egg-info}/PKG-INFO +28 -4
  19. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext_xloader.egg-info/SOURCES.txt +1 -0
  20. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/pyproject.toml +1 -1
  21. ckanext_xloader-2.0.1/ckanext/xloader/tests/test_jobs.py +0 -168
  22. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/CHANGELOG +0 -0
  23. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/LICENSE +0 -0
  24. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/MANIFEST.in +0 -0
  25. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/__init__.py +0 -0
  26. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/__init__.py +0 -0
  27. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/auth.py +0 -0
  28. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/cli.py +0 -0
  29. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/db.py +0 -0
  30. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/interfaces.py +0 -0
  31. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/parser.py +0 -0
  32. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/datastore/snippets/dictionary_form.html +0 -0
  33. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/package/resource_edit_base.html +0 -0
  34. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/package/resource_read.html +0 -0
  35. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/package/snippets/resource_info.html +0 -0
  36. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/package/snippets/resource_item.html +0 -0
  37. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/package/snippets/resources.html +0 -0
  38. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/xloader/confirm_datastore_delete.html +0 -0
  39. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/templates/xloader/resource_data.html +0 -0
  40. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/__init__.py +0 -0
  41. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/ckan_setup.py +0 -0
  42. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/fixtures.py +0 -0
  43. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/tests/test_parser.py +0 -0
  44. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/views.py +0 -0
  45. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/webassets/css/xloader.css +0 -0
  46. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext/xloader/webassets/webassets.yml +0 -0
  47. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext_xloader.egg-info/dependency_links.txt +0 -0
  48. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext_xloader.egg-info/entry_points.txt +0 -0
  49. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext_xloader.egg-info/requires.txt +0 -0
  50. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/ckanext_xloader.egg-info/top_level.txt +0 -0
  51. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/dev-requirements.txt +0 -0
  52. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/requirements.txt +0 -0
  53. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/setup.cfg +0 -0
  54. {ckanext_xloader-2.0.1 → ckanext_xloader-2.2.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: ckanext-xloader
3
- Version: 2.0.1
3
+ Version: 2.2.0
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>
@@ -20,6 +20,7 @@ License-File: LICENSE
20
20
  Requires-Dist: typing_extensions
21
21
  Provides-Extra: test
22
22
  Requires-Dist: pytest-factoryboy; extra == "test"
23
+ Dynamic: license-file
23
24
 
24
25
  # XLoader - ckanext-xloader
25
26
 
@@ -174,6 +175,7 @@ To install XLoader:
174
175
  execute jobs against the server:
175
176
 
176
177
  ckanext.xloader.api_token = <your-CKAN-generated-API-Token>
178
+ ckan config-tool test.ini "ckanext.xloader.api_token=$(ckan -c test.ini user token add ckan_admin xloader | tail -n 1 | tr -d '\t')"
177
179
 
178
180
  6. If it is a production server, you'll want to store jobs info in a
179
181
  more robust database than the default sqlite file. It can happily
@@ -243,8 +245,7 @@ ckanext.xloader.api_token = eyJ0eXAiOiJKV1QiLCJh.eyJqdGkiOiJ0M2VNUFlQWFg0VU.8QgV
243
245
 
244
246
  Default value: none
245
247
 
246
- Uses a specific API token for the xloader_submit action instead of the
247
- apikey of the site_user. It's mandatory starting from CKAN 2.10. You can get one
248
+ It's mandatory starting from CKAN 2.10. You can get one
248
249
  running the command `ckan user token add {USER_NAME} xloader -q`
249
250
 
250
251
 
@@ -460,6 +461,29 @@ Default value: `True`
460
461
 
461
462
  Controls whether or not a resource requires a Validation Schema to be present from the ckanext-validation plugin to be XLoadered.
462
463
 
464
+ #### ckanext.xloader.site_url
465
+ Provide an alternate site URL for the xloader_submit action.
466
+ This is useful, for example, when the site is running within a docker network.
467
+
468
+ Note: This setting will not alter path. i.e ckan.root_path
469
+
470
+ Example:
471
+
472
+ ```
473
+ ckanext.xloader.site_url = http://ckan-dev:5000
474
+ ```
475
+
476
+ ##### ckanext.xloader.site_url_ignore_path_regex
477
+ Provide the ability to ignore paths which can't be mapped to alternative site URL for resource access.
478
+ This is useful, for example, when the site is running within a docker network and the cdn front door has
479
+ Blob storage mapped to another path on the same domain.
480
+
481
+ Example:
482
+
483
+ ```
484
+ ckanext.xloader.site_url_ignore_path_regex = "(/PathToS3HostOriginIWantToGoDirectTo|/anotherPath)"
485
+ ```
486
+
463
487
  ## Data Dictionary Fields
464
488
 
465
489
  #### strip_extra_white
@@ -151,6 +151,7 @@ To install XLoader:
151
151
  execute jobs against the server:
152
152
 
153
153
  ckanext.xloader.api_token = <your-CKAN-generated-API-Token>
154
+ ckan config-tool test.ini "ckanext.xloader.api_token=$(ckan -c test.ini user token add ckan_admin xloader | tail -n 1 | tr -d '\t')"
154
155
 
155
156
  6. If it is a production server, you'll want to store jobs info in a
156
157
  more robust database than the default sqlite file. It can happily
@@ -220,8 +221,7 @@ ckanext.xloader.api_token = eyJ0eXAiOiJKV1QiLCJh.eyJqdGkiOiJ0M2VNUFlQWFg0VU.8QgV
220
221
 
221
222
  Default value: none
222
223
 
223
- Uses a specific API token for the xloader_submit action instead of the
224
- apikey of the site_user. It's mandatory starting from CKAN 2.10. You can get one
224
+ It's mandatory starting from CKAN 2.10. You can get one
225
225
  running the command `ckan user token add {USER_NAME} xloader -q`
226
226
 
227
227
 
@@ -437,6 +437,29 @@ Default value: `True`
437
437
 
438
438
  Controls whether or not a resource requires a Validation Schema to be present from the ckanext-validation plugin to be XLoadered.
439
439
 
440
+ #### ckanext.xloader.site_url
441
+ Provide an alternate site URL for the xloader_submit action.
442
+ This is useful, for example, when the site is running within a docker network.
443
+
444
+ Note: This setting will not alter path. i.e ckan.root_path
445
+
446
+ Example:
447
+
448
+ ```
449
+ ckanext.xloader.site_url = http://ckan-dev:5000
450
+ ```
451
+
452
+ ##### ckanext.xloader.site_url_ignore_path_regex
453
+ Provide the ability to ignore paths which can't be mapped to alternative site URL for resource access.
454
+ This is useful, for example, when the site is running within a docker network and the cdn front door has
455
+ Blob storage mapped to another path on the same domain.
456
+
457
+ Example:
458
+
459
+ ```
460
+ ckanext.xloader.site_url_ignore_path_regex = "(/PathToS3HostOriginIWantToGoDirectTo|/anotherPath)"
461
+ ```
462
+
440
463
  ## Data Dictionary Fields
441
464
 
442
465
  #### strip_extra_white
@@ -47,6 +47,7 @@ def xloader_submit(context, data_dict):
47
47
  :rtype: bool
48
48
  '''
49
49
  p.toolkit.check_access('xloader_submit', context, data_dict)
50
+ api_key = utils.get_xloader_user_apitoken()
50
51
  custom_queue = data_dict.pop('queue', rq_jobs.DEFAULT_QUEUE_NAME)
51
52
  schema = context.get('schema', ckanext.xloader.schema.xloader_submit_schema())
52
53
  data_dict, errors = _validate(data_dict, schema, context)
@@ -147,7 +148,7 @@ def xloader_submit(context, data_dict):
147
148
  qualified=True
148
149
  )
149
150
  data = {
150
- 'api_key': utils.get_xloader_user_apitoken(),
151
+ 'api_key': api_key,
151
152
  'job_type': 'xloader_to_datastore',
152
153
  'result_url': callback_url,
153
154
  'metadata': {
@@ -5,7 +5,7 @@ import logging
5
5
  import ckan.plugins.toolkit as tk
6
6
 
7
7
  from ckanext.xloader.jobs import xloader_data_into_datastore_
8
- from ckanext.xloader.utils import XLoaderFormats
8
+ from ckanext.xloader.utils import XLoaderFormats, get_xloader_user_apitoken
9
9
 
10
10
 
11
11
  class XloaderCmd:
@@ -117,7 +117,7 @@ class XloaderCmd:
117
117
  data_dict['ckan_url'] = tk.config.get('ckan.site_url')
118
118
  input_dict = {
119
119
  'metadata': data_dict,
120
- 'api_key': 'TODO'
120
+ 'api_key': get_xloader_user_apitoken()
121
121
  }
122
122
  logger = logging.getLogger('ckanext.xloader.cli')
123
123
  xloader_data_into_datastore_(input_dict, None, logger)
@@ -2,6 +2,22 @@ version: 1
2
2
  groups:
3
3
  - annotation: ckanext-xloader settings
4
4
  options:
5
+ - key: ckanext.xloader.site_url
6
+ example: http://ckan-dev:5000
7
+ default:
8
+ description: |
9
+ Provide an alternate site URL for the xloader_submit action.
10
+ This is useful, for example, when the site is running within a docker network.
11
+ Note: This setting will not alter path. i.e ckan.root_path
12
+ required: false
13
+ - key: ckanext.xloader.site_url_ignore_path_regex
14
+ example: "(/PathToS3HostOriginIWantToGoDirectTo|/anotherPath)"
15
+ default:
16
+ description: |
17
+ Provide the ability to ignore paths which can't be mapped to alternative site URL for resource access.
18
+ This is useful, for example, when the site is running within a docker network and the cdn front door has
19
+ Blob storage mapped to another path on the same domain.
20
+ required: false
5
21
  - key: ckanext.xloader.jobs_db.uri
6
22
  default: sqlite:////tmp/xloader_jobs.db
7
23
  description: |
@@ -14,9 +30,9 @@ groups:
14
30
  example: eyJ0eXAiOiJKV1QiLCJh.eyJqdGkiOiJ0M2VNUFlQWFg0VU.8QgV8em4RA
15
31
  description: |
16
32
  Uses a specific API token for the xloader_submit action instead of the
17
- apikey of the site_user. Will be mandatory when dropping support for
18
- CKAN 2.9.
19
- required: false
33
+ apikey of the site_user.
34
+ default: 'NOT_SET'
35
+ required: true
20
36
  - key: ckanext.xloader.formats
21
37
  example: csv application/csv xls application/vnd.ms-excel
22
38
  description: |
@@ -171,5 +187,22 @@ groups:
171
187
  they will also display "complete", "active", "inactive", and "unknown".
172
188
  type: bool
173
189
  required: false
174
-
175
-
190
+ - key: ckanext.xloader.search_update_chunks
191
+ default: 100000
192
+ example: 1000
193
+ description: |
194
+ The number of rows to process in each batch when populating the full-text
195
+ search index. Chunked processing prevents database timeouts and memory
196
+ exhaustion when indexing very large datasets (4GB+ files with millions of rows).
197
+ Smaller values reduce memory usage but increase processing time. Larger values
198
+ improve performance but may cause timeouts on very large tables.
199
+ type: int
200
+ required: false
201
+ - key: ckanext.xloader.max_retries
202
+ default: 1
203
+ example: 3
204
+ description: |
205
+ Maximum number of retry attempts for failed jobs due to temporary errors
206
+ like database deadlocks or network timeouts. Set to 0 to disable retries.
207
+ type: int
208
+ required: false
@@ -40,7 +40,7 @@ def is_resource_supported_by_xloader(res_dict, check_access=True):
40
40
  try:
41
41
  is_supported_url_type = url_type not in toolkit.h.datastore_rw_resource_url_types()
42
42
  except AttributeError:
43
- is_supported_url_type = (url_type == 'upload')
43
+ is_supported_url_type = (url_type in ['upload', 'None'])
44
44
  else:
45
45
  is_supported_url_type = True
46
46
  return (is_supported_format or is_datastore_active) and user_has_access and is_supported_url_type
@@ -52,3 +52,8 @@ class HTTPError(JobError):
52
52
  class LoaderError(JobError):
53
53
  '''Exception that's raised if a load fails'''
54
54
  pass
55
+
56
+
57
+ class XLoaderTimeoutError(JobError):
58
+ """Custom timeout exception that can be retried"""
59
+ pass
@@ -18,17 +18,14 @@ from rq import get_current_job
18
18
  from rq.timeouts import JobTimeoutException
19
19
  import sqlalchemy as sa
20
20
 
21
- from ckan import model
22
21
  from ckan.plugins.toolkit import get_action, asbool, enqueue_job, ObjectNotFound, config, h
23
22
 
24
23
  from . import db, loader
25
- from .job_exceptions import JobError, HTTPError, DataTooBigError, FileCouldNotBeLoadedError
26
- from .utils import datastore_resource_exists, set_resource_metadata
24
+ from .job_exceptions import JobError, HTTPError, DataTooBigError, FileCouldNotBeLoadedError, LoaderError, XLoaderTimeoutError
25
+ from .utils import datastore_resource_exists, set_resource_metadata, modify_input_url
27
26
 
28
- try:
29
- from ckan.lib.api_token import get_user_from_token
30
- except ImportError:
31
- get_user_from_token = None
27
+
28
+ from ckan.lib.api_token import get_user_from_token
32
29
 
33
30
  log = logging.getLogger(__name__)
34
31
 
@@ -43,11 +40,13 @@ MAX_EXCERPT_LINES = int(config.get('ckanext.xloader.max_excerpt_lines') or 0)
43
40
  CHUNK_SIZE = 16 * 1024 # 16kb
44
41
  DOWNLOAD_TIMEOUT = 30
45
42
 
46
- MAX_RETRIES = 1
43
+ MAX_RETRIES = int(config.get('ckanext.xloader.max_retries', 1))
47
44
  RETRYABLE_ERRORS = (
48
45
  errors.DeadlockDetected,
49
46
  errors.LockNotAvailable,
50
47
  errors.ObjectInUse,
48
+ HTTPError,
49
+ XLoaderTimeoutError
51
50
  )
52
51
  # Retries can only occur in cases where the datastore entry exists,
53
52
  # so use the standard timeout
@@ -55,6 +54,38 @@ RETRIED_JOB_TIMEOUT = config.get('ckanext.xloader.job_timeout', '3600')
55
54
  APITOKEN_HEADER_NAME = config.get('apitoken_header_name', 'Authorization')
56
55
 
57
56
 
57
+ def is_retryable_error(error):
58
+ """
59
+ Determine if an error should trigger a retry attempt.
60
+
61
+ Checks if the error is a temporary/transient condition that might
62
+ succeed on retry. Returns True for retryable HTTP status codes and
63
+ other temporary errors.
64
+
65
+ Retryable HTTP status codes:
66
+ - 408 Request Timeout
67
+ - 429 Too Many Requests
68
+ - 500 Internal Server Error
69
+ - 502 Bad Gateway
70
+ - 503 Service Unavailable
71
+ - 504 Gateway Timeout
72
+ - 507 Insufficient Storage
73
+ - 522 Connection Timed Out (Cloudflare)
74
+ - 524 A Timeout Occurred (Cloudflare)
75
+
76
+ :param error: Exception object to check
77
+ :type error: Exception
78
+ :return: True if error should be retried, False otherwise
79
+ :rtype: bool
80
+ """
81
+ if isinstance(error, HTTPError):
82
+ retryable_status_codes = {408, 429, 500, 502, 503, 504, 507, 522, 524}
83
+ return error.status_code in retryable_status_codes
84
+ else:
85
+ return True
86
+ return False
87
+
88
+
58
89
  # input = {
59
90
  # 'api_key': user['apikey'],
60
91
  # 'job_type': 'xloader_to_datastore',
@@ -114,36 +145,12 @@ def xloader_data_into_datastore(input):
114
145
  job_dict['error'] = str(e)
115
146
  log.error('xloader error: job_id %s already exists', job_id)
116
147
  errored = True
117
- except JobError as e:
118
- db.mark_job_as_errored(job_id, str(e))
119
- job_dict['status'] = 'error'
120
- job_dict['error'] = str(e)
121
- log.error('xloader error: %s, %s', e, traceback.format_exc())
122
- errored = True
123
148
  except Exception as e:
124
- if isinstance(e, RETRYABLE_ERRORS):
125
- tries = job_dict['metadata'].get('tries', 0)
126
- if tries < MAX_RETRIES:
127
- tries = tries + 1
128
- log.info("Job %s failed due to temporary error [%s], retrying", job_id, e)
129
- logger.info("Job failed due to temporary error [%s], retrying", e)
130
- job_dict['status'] = 'pending'
131
- job_dict['metadata']['tries'] = tries
132
- enqueue_job(
133
- xloader_data_into_datastore,
134
- [input],
135
- title="retry xloader_data_into_datastore: resource: {} attempt {}".format(
136
- job_dict['metadata']['resource_id'], tries),
137
- rq_kwargs=dict(timeout=RETRIED_JOB_TIMEOUT)
138
- )
139
- return None
140
-
141
- db.mark_job_as_errored(
142
- job_id, traceback.format_tb(sys.exc_info()[2])[-1] + repr(e))
143
- job_dict['status'] = 'error'
144
- job_dict['error'] = str(e)
145
- log.error('xloader error: %s, %s', e, traceback.format_exc())
146
- errored = True
149
+ error_state = {'errored': errored}
150
+ retry = handle_retryable_error(e, input, job_id, job_dict, logger, error_state)
151
+ if retry:
152
+ return None
153
+ errored = error_state['errored']
147
154
  finally:
148
155
  # job_dict is defined in xloader_hook's docstring
149
156
  is_saved_ok = callback_xloader_hook(result_url=input['result_url'],
@@ -153,6 +160,54 @@ def xloader_data_into_datastore(input):
153
160
  return 'error' if errored else None
154
161
 
155
162
 
163
+ def handle_retryable_error(e, input, job_id, job_dict, logger, error_state):
164
+ """
165
+ Handle retryable errors by attempting to retry the job or marking it as failed.
166
+
167
+ Checks if the error is retryable (database deadlocks, HTTP timeouts, etc.) and
168
+ within the retry limit. If so, enqueues a new job attempt. Otherwise, marks
169
+ the job as errored.
170
+
171
+ :param e: The exception that occurred
172
+ :type e: Exception
173
+ :param input: Job input data containing metadata and API key
174
+ :type input: dict
175
+ :param job_id: Unique identifier for the current job
176
+ :type job_id: str
177
+ :param job_dict: Job status dictionary with metadata and status
178
+ :type job_dict: dict
179
+ :param logger: Logger instance for the current job
180
+ :type logger: logging.Logger
181
+ :param error_state: Mutable dict to track error state {'errored': bool}
182
+ :type error_state: dict
183
+
184
+ :returns: True if job was retried, None otherwise
185
+ :rtype: bool or None
186
+ """
187
+ if isinstance(e, RETRYABLE_ERRORS) and is_retryable_error(e):
188
+ tries = job_dict['metadata'].get('tries', 0)
189
+ if tries < MAX_RETRIES:
190
+ tries = tries + 1
191
+ log.info("Job %s failed due to temporary error [%s], retrying", job_id, e)
192
+ logger.info("Job failed due to temporary error [%s], retrying", e)
193
+ job_dict['status'] = 'pending'
194
+ job_dict['metadata']['tries'] = tries
195
+ enqueue_job(
196
+ xloader_data_into_datastore,
197
+ [input],
198
+ title="retry xloader_data_into_datastore: resource: {} attempt {}".format(
199
+ job_dict['metadata']['resource_id'], tries),
200
+ rq_kwargs=dict(timeout=RETRIED_JOB_TIMEOUT)
201
+ )
202
+ return True
203
+ db.mark_job_as_errored(
204
+ job_id, traceback.format_tb(sys.exc_info()[2])[-1] + repr(e))
205
+ job_dict['status'] = 'error'
206
+ job_dict['error'] = str(e)
207
+ log.error('xloader error: %s, %s', e, traceback.format_exc())
208
+ error_state['errored'] = True
209
+
210
+
156
211
  def xloader_data_into_datastore_(input, job_dict, logger):
157
212
  '''This function:
158
213
  * downloads the resource (metadata) from CKAN
@@ -182,9 +237,9 @@ def xloader_data_into_datastore_(input, job_dict, logger):
182
237
  if hasattr(h, "datastore_rw_resource_url_types"):
183
238
  datastore_rw_resource_url_types = h.datastore_rw_resource_url_types()
184
239
  else:
185
- #fallback for 2.10.x or older.
240
+ # fallback for 2.10.x or older.
186
241
  datastore_rw_resource_url_types = ['datastore']
187
-
242
+
188
243
  if resource.get('url_type') in datastore_rw_resource_url_types:
189
244
  logger.info('Ignoring resource - R/W DataStore resources are '
190
245
  'managed with the Datastore API')
@@ -202,11 +257,12 @@ def xloader_data_into_datastore_(input, job_dict, logger):
202
257
  logger.info('File hash: %s', file_hash)
203
258
  resource['hash'] = file_hash
204
259
 
205
- def direct_load():
260
+ def direct_load(allow_type_guessing=False):
206
261
  fields = loader.load_csv(
207
262
  tmp_file.name,
208
263
  resource_id=resource['id'],
209
264
  mimetype=resource.get('format'),
265
+ allow_type_guessing=allow_type_guessing,
210
266
  logger=logger)
211
267
  loader.calculate_record_count(
212
268
  resource_id=resource['id'], logger=logger)
@@ -262,24 +318,24 @@ def xloader_data_into_datastore_(input, job_dict, logger):
262
318
  direct_load()
263
319
  else:
264
320
  try:
265
- direct_load()
266
- except JobError as e:
321
+ direct_load(allow_type_guessing=True)
322
+ except (JobError, LoaderError) as e:
267
323
  logger.warning('Load using COPY failed: %s', e)
268
324
  logger.info('Trying again with tabulator')
269
325
  tabulator_load()
270
- except JobTimeoutException as e:
271
- try:
272
- tmp_file.close()
273
- except FileNotFoundError:
274
- pass
326
+ except JobTimeoutException:
275
327
  logger.warning('Job timed out after %ss', RETRIED_JOB_TIMEOUT)
276
328
  raise JobError('Job timed out after {}s'.format(RETRIED_JOB_TIMEOUT))
277
329
  except FileCouldNotBeLoadedError as e:
278
330
  logger.warning('Loading excerpt for this format not supported.')
279
331
  logger.error('Loading file raised an error: %s', e)
280
332
  raise JobError('Loading file raised an error: {}'.format(e))
281
-
282
- tmp_file.close()
333
+ finally:
334
+ try:
335
+ tmp_file.close()
336
+ os.remove(tmp_file.name)
337
+ except FileNotFoundError:
338
+ pass
283
339
 
284
340
  logger.info('Express Load completed')
285
341
 
@@ -297,8 +353,9 @@ def _download_resource_data(resource, data, api_key, logger):
297
353
  data['datastore_contains_all_records_of_source_file'] = False
298
354
  which will be saved to the resource later on.
299
355
  '''
356
+ # update base url (for possible local loopback)
357
+ url = modify_input_url(resource.get('url'))
300
358
  # check scheme
301
- url = resource.get('url')
302
359
  url_parts = urlsplit(url)
303
360
  scheme = url_parts.scheme
304
361
  if scheme not in ('http', 'https', 'ftp'):
@@ -381,8 +438,8 @@ def _download_resource_data(resource, data, api_key, logger):
381
438
  request_url=url, response=error)
382
439
  except requests.exceptions.Timeout:
383
440
  logger.warning('URL time out after %ss', DOWNLOAD_TIMEOUT)
384
- raise JobError('Connection timed out after {}s'.format(
385
- DOWNLOAD_TIMEOUT))
441
+ raise XLoaderTimeoutError('Connection timed out after {}s'.format(
442
+ DOWNLOAD_TIMEOUT))
386
443
  except requests.exceptions.RequestException as e:
387
444
  tmp_file.close()
388
445
  try:
@@ -393,7 +450,7 @@ def _download_resource_data(resource, data, api_key, logger):
393
450
  raise HTTPError(
394
451
  message=err_message, status_code=None,
395
452
  request_url=url, response=None)
396
- except JobTimeoutException as e:
453
+ except JobTimeoutException:
397
454
  tmp_file.close()
398
455
  logger.warning('Job timed out after %ss', RETRIED_JOB_TIMEOUT)
399
456
  raise JobError('Job timed out after {}s'.format(RETRIED_JOB_TIMEOUT))
@@ -468,7 +525,7 @@ def callback_xloader_hook(result_url, api_key, job_dict):
468
525
 
469
526
  try:
470
527
  result = requests.post(
471
- result_url,
528
+ modify_input_url(result_url), # modify with local config
472
529
  data=json.dumps(job_dict, cls=DatetimeJsonEncoder),
473
530
  verify=SSL_VERIFY,
474
531
  headers=headers)
@@ -511,19 +568,8 @@ def update_resource(resource, patch_only=False):
511
568
 
512
569
  def _get_user_from_key(api_key_or_token):
513
570
  """ Gets the user using the API Token or API Key.
514
-
515
- This method provides backwards compatibility for CKAN 2.9 that
516
- supported both methods and previous CKAN versions supporting
517
- only API Keys.
518
571
  """
519
- user = None
520
- if get_user_from_token:
521
- user = get_user_from_token(api_key_or_token)
522
- if not user:
523
- user = model.Session.query(model.User).filter_by(
524
- apikey=api_key_or_token
525
- ).first()
526
- return user
572
+ return get_user_from_token(api_key_or_token)
527
573
 
528
574
 
529
575
  def get_resource_and_dataset(resource_id, api_key):