2015-10-27 18:33:22 +01:00
|
|
|
import urllib
|
2011-04-19 15:54:59 +02:00
|
|
|
import urllib2
|
2015-11-23 22:26:32 +01:00
|
|
|
import httplib
|
2016-02-12 19:00:00 +01:00
|
|
|
import datetime
|
2016-02-15 13:10:44 +01:00
|
|
|
import socket
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-11-02 17:59:19 +01:00
|
|
|
from sqlalchemy import exists
|
|
|
|
|
2011-11-18 14:20:41 +01:00
|
|
|
from ckan.lib.base import c
|
|
|
|
from ckan import model
|
|
|
|
from ckan.logic import ValidationError, NotFound, get_action
|
2011-04-19 15:54:59 +02:00
|
|
|
from ckan.lib.helpers import json
|
2015-01-15 00:09:43 +01:00
|
|
|
from ckan.lib.munge import munge_name
|
2015-10-23 19:30:28 +02:00
|
|
|
from ckan.plugins import toolkit
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-11-02 17:59:19 +01:00
|
|
|
from ckanext.harvest.model import HarvestJob, HarvestObject, HarvestGatherError
|
2011-04-19 15:54:59 +02:00
|
|
|
|
|
|
|
import logging
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2011-06-02 12:07:07 +02:00
|
|
|
from base import HarvesterBase
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-10-23 19:30:28 +02:00
|
|
|
|
2011-06-02 12:07:07 +02:00
|
|
|
class CKANHarvester(HarvesterBase):
|
2011-04-19 15:54:59 +02:00
|
|
|
'''
|
|
|
|
A Harvester for CKAN instances
|
|
|
|
'''
|
2011-06-07 14:35:11 +02:00
|
|
|
config = None
|
2011-05-17 18:26:42 +02:00
|
|
|
|
2013-05-22 16:46:14 +02:00
|
|
|
api_version = 2
|
2015-01-13 14:46:14 +01:00
|
|
|
action_api_version = 3
|
2011-05-17 18:26:42 +02:00
|
|
|
|
2015-01-13 14:46:14 +01:00
|
|
|
def _get_action_api_offset(self):
|
|
|
|
return '/api/%d/action' % self.action_api_version
|
|
|
|
|
2011-05-17 18:26:42 +02:00
|
|
|
def _get_search_api_offset(self):
|
2015-10-27 18:43:11 +01:00
|
|
|
return '%s/package_search' % self._get_action_api_offset()
|
2011-04-19 15:54:59 +02:00
|
|
|
|
|
|
|
def _get_content(self, url):
|
2015-10-27 18:33:22 +01:00
|
|
|
http_request = urllib2.Request(url=url)
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-11-23 22:26:32 +01:00
|
|
|
api_key = self.config.get('api_key')
|
2013-02-28 20:06:21 +01:00
|
|
|
if api_key:
|
2015-10-27 18:33:22 +01:00
|
|
|
http_request.add_header('Authorization', api_key)
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-01-15 00:07:26 +01:00
|
|
|
try:
|
|
|
|
http_response = urllib2.urlopen(http_request)
|
2015-11-23 22:26:32 +01:00
|
|
|
except urllib2.HTTPError, e:
|
2015-11-23 22:36:45 +01:00
|
|
|
if e.getcode() == 404:
|
|
|
|
raise ContentNotFoundError('HTTP error: %s' % e.code)
|
|
|
|
else:
|
|
|
|
raise ContentFetchError('HTTP error: %s' % e.code)
|
2015-01-15 10:57:24 +01:00
|
|
|
except urllib2.URLError, e:
|
2015-11-23 22:26:32 +01:00
|
|
|
raise ContentFetchError('URL error: %s' % e.reason)
|
|
|
|
except httplib.HTTPException, e:
|
|
|
|
raise ContentFetchError('HTTP Exception: %s' % e)
|
2016-02-15 13:10:44 +01:00
|
|
|
except socket.error, e:
|
|
|
|
raise ContentFetchError('HTTP socket error: %s' % e)
|
|
|
|
except Exception, e:
|
|
|
|
raise ContentFetchError('HTTP general exception: %s' % e)
|
2013-02-28 20:06:21 +01:00
|
|
|
return http_response.read()
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2016-05-20 16:38:48 +02:00
|
|
|
def _get_group(self, base_url, group):
|
2015-10-27 18:43:11 +01:00
|
|
|
url = base_url + self._get_action_api_offset() + '/group_show?id=' + \
|
2016-05-20 16:38:48 +02:00
|
|
|
group['id']
|
2013-05-24 17:55:05 +02:00
|
|
|
try:
|
|
|
|
content = self._get_content(url)
|
2016-05-20 16:38:48 +02:00
|
|
|
data = json.loads(content)
|
|
|
|
if self.action_api_version == 3:
|
|
|
|
return data.pop('result')
|
|
|
|
|
|
|
|
return data
|
|
|
|
|
2015-01-15 00:07:26 +01:00
|
|
|
except (ContentFetchError, ValueError):
|
2015-10-27 18:43:11 +01:00
|
|
|
log.debug('Could not fetch/decode remote group')
|
2015-01-15 00:07:26 +01:00
|
|
|
raise RemoteResourceError('Could not fetch/decode remote group')
|
2013-05-24 17:55:05 +02:00
|
|
|
|
2015-01-13 14:46:14 +01:00
|
|
|
def _get_organization(self, base_url, org_name):
|
2015-10-27 18:43:11 +01:00
|
|
|
url = base_url + self._get_action_api_offset() + \
|
|
|
|
'/organization_show?id=' + org_name
|
2015-01-13 14:46:14 +01:00
|
|
|
try:
|
|
|
|
content = self._get_content(url)
|
|
|
|
content_dict = json.loads(content)
|
|
|
|
return content_dict['result']
|
2015-01-15 00:07:26 +01:00
|
|
|
except (ContentFetchError, ValueError, KeyError):
|
2015-10-27 18:43:11 +01:00
|
|
|
log.debug('Could not fetch/decode remote group')
|
|
|
|
raise RemoteResourceError(
|
|
|
|
'Could not fetch/decode remote organization')
|
2015-01-13 14:46:14 +01:00
|
|
|
|
2015-10-27 18:43:11 +01:00
|
|
|
def _set_config(self, config_str):
|
2011-06-07 14:35:11 +02:00
|
|
|
if config_str:
|
|
|
|
self.config = json.loads(config_str)
|
2013-08-15 15:37:55 +02:00
|
|
|
if 'api_version' in self.config:
|
|
|
|
self.api_version = int(self.config['api_version'])
|
2011-07-18 18:35:32 +02:00
|
|
|
|
2011-06-07 14:35:11 +02:00
|
|
|
log.debug('Using config: %r', self.config)
|
|
|
|
else:
|
|
|
|
self.config = {}
|
|
|
|
|
2011-05-13 19:39:36 +02:00
|
|
|
def info(self):
|
|
|
|
return {
|
|
|
|
'name': 'ckan',
|
|
|
|
'title': 'CKAN',
|
2011-06-07 13:07:53 +02:00
|
|
|
'description': 'Harvests remote CKAN instances',
|
2015-10-27 18:43:11 +01:00
|
|
|
'form_config_interface': 'Text'
|
2011-05-13 19:39:36 +02:00
|
|
|
}
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-10-27 18:43:11 +01:00
|
|
|
def validate_config(self, config):
|
2011-06-28 16:04:40 +02:00
|
|
|
if not config:
|
|
|
|
return config
|
|
|
|
|
2011-06-07 13:07:53 +02:00
|
|
|
try:
|
|
|
|
config_obj = json.loads(config)
|
2011-11-18 14:20:41 +01:00
|
|
|
|
2013-05-31 18:23:40 +02:00
|
|
|
if 'api_version' in config_obj:
|
|
|
|
try:
|
|
|
|
int(config_obj['api_version'])
|
|
|
|
except ValueError:
|
|
|
|
raise ValueError('api_version must be an integer')
|
|
|
|
|
2012-01-10 18:07:19 +01:00
|
|
|
if 'default_tags' in config_obj:
|
2015-10-27 18:43:11 +01:00
|
|
|
if not isinstance(config_obj['default_tags'], list):
|
2012-01-10 18:07:19 +01:00
|
|
|
raise ValueError('default_tags must be a list')
|
|
|
|
|
2011-11-18 14:20:41 +01:00
|
|
|
if 'default_groups' in config_obj:
|
2015-10-27 18:43:11 +01:00
|
|
|
if not isinstance(config_obj['default_groups'], list):
|
2012-01-10 18:07:19 +01:00
|
|
|
raise ValueError('default_groups must be a list')
|
|
|
|
|
2011-11-18 14:20:41 +01:00
|
|
|
# Check if default groups exist
|
2015-10-27 18:43:11 +01:00
|
|
|
context = {'model': model, 'user': c.user}
|
2016-05-20 20:15:54 +02:00
|
|
|
for group_name in config_obj['default_groups']:
|
2011-11-18 14:20:41 +01:00
|
|
|
try:
|
2015-10-27 18:43:11 +01:00
|
|
|
group = get_action('group_show')(
|
2016-05-20 20:15:54 +02:00
|
|
|
context, {'id': group_name})
|
2015-10-27 18:43:11 +01:00
|
|
|
except NotFound, e:
|
2011-11-18 14:20:41 +01:00
|
|
|
raise ValueError('Default group not found')
|
2011-11-18 15:12:30 +01:00
|
|
|
|
2012-01-10 18:07:19 +01:00
|
|
|
if 'default_extras' in config_obj:
|
2015-10-27 18:43:11 +01:00
|
|
|
if not isinstance(config_obj['default_extras'], dict):
|
2012-01-10 18:07:19 +01:00
|
|
|
raise ValueError('default_extras must be a dictionary')
|
|
|
|
|
2011-11-18 15:12:30 +01:00
|
|
|
if 'user' in config_obj:
|
|
|
|
# Check if user exists
|
2015-10-27 18:43:11 +01:00
|
|
|
context = {'model': model, 'user': c.user}
|
2011-11-18 15:12:30 +01:00
|
|
|
try:
|
2015-10-27 18:43:11 +01:00
|
|
|
user = get_action('user_show')(
|
|
|
|
context, {'id': config_obj.get('user')})
|
2016-02-15 14:50:18 +01:00
|
|
|
except NotFound:
|
2011-11-18 15:12:30 +01:00
|
|
|
raise ValueError('User not found')
|
2011-11-18 14:20:41 +01:00
|
|
|
|
2015-10-27 18:43:11 +01:00
|
|
|
for key in ('read_only', 'force_all'):
|
2012-02-03 18:54:34 +01:00
|
|
|
if key in config_obj:
|
2015-10-27 18:43:11 +01:00
|
|
|
if not isinstance(config_obj[key], bool):
|
2012-02-03 18:54:34 +01:00
|
|
|
raise ValueError('%s must be boolean' % key)
|
|
|
|
|
2015-10-27 18:43:11 +01:00
|
|
|
except ValueError, e:
|
2011-06-07 13:07:53 +02:00
|
|
|
raise e
|
|
|
|
|
|
|
|
return config
|
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
def gather_stage(self, harvest_job):
|
|
|
|
log.debug('In CKANHarvester gather_stage (%s)',
|
|
|
|
harvest_job.source.url)
|
2015-10-23 19:30:28 +02:00
|
|
|
toolkit.requires_ckan_version(min_version='2.0')
|
2011-05-17 18:26:42 +02:00
|
|
|
get_all_packages = True
|
|
|
|
|
2011-06-14 16:59:13 +02:00
|
|
|
self._set_config(harvest_job.source.config)
|
2011-06-07 14:35:11 +02:00
|
|
|
|
2011-04-19 15:54:59 +02:00
|
|
|
# Get source URL
|
2015-10-27 18:33:22 +01:00
|
|
|
remote_ckan_base_url = harvest_job.source.url.rstrip('/')
|
2011-06-07 13:07:53 +02:00
|
|
|
|
2015-10-21 18:33:16 +02:00
|
|
|
# Filter in/out datasets from particular organizations
|
2015-10-28 15:34:27 +01:00
|
|
|
fq_terms = []
|
2015-10-21 18:33:16 +02:00
|
|
|
org_filter_include = self.config.get('organizations_filter_include', [])
|
|
|
|
org_filter_exclude = self.config.get('organizations_filter_exclude', [])
|
2015-10-28 15:34:27 +01:00
|
|
|
if org_filter_include:
|
|
|
|
fq_terms.append(' OR '.join(
|
|
|
|
'organization:%s' % org_name for org_name in org_filter_include))
|
|
|
|
elif org_filter_exclude:
|
|
|
|
fq_terms.extend(
|
|
|
|
'-organization:%s' % org_name for org_name in org_filter_exclude)
|
|
|
|
|
2015-10-23 19:30:28 +02:00
|
|
|
# Ideally we can request from the remote CKAN only those datasets
|
2015-11-02 17:59:19 +01:00
|
|
|
# modified since the last completely successful harvest.
|
|
|
|
last_error_free_job = self._last_error_free_job(harvest_job)
|
|
|
|
log.debug('Last error-free job: %r', last_error_free_job)
|
|
|
|
if (last_error_free_job and
|
2015-10-27 18:33:22 +01:00
|
|
|
not self.config.get('force_all', False)):
|
|
|
|
get_all_packages = False
|
|
|
|
|
2015-11-02 17:59:19 +01:00
|
|
|
# Request only the datasets modified since
|
2016-02-12 19:00:00 +01:00
|
|
|
last_time = last_error_free_job.gather_started
|
2015-10-27 18:33:22 +01:00
|
|
|
# Note: SOLR works in UTC, and gather_started is also UTC, so
|
|
|
|
# this should work as long as local and remote clocks are
|
2016-02-12 19:00:00 +01:00
|
|
|
# relatively accurate. Going back a little earlier, just in case.
|
2016-02-15 14:16:23 +01:00
|
|
|
get_changes_since = \
|
|
|
|
(last_time - datetime.timedelta(hours=1)).isoformat()
|
2015-10-27 18:33:22 +01:00
|
|
|
log.info('Searching for datasets modified since: %s UTC',
|
2016-02-15 14:16:23 +01:00
|
|
|
get_changes_since)
|
2015-10-27 18:33:22 +01:00
|
|
|
|
2016-02-15 16:36:02 +01:00
|
|
|
fq_since_last_time = 'metadata_modified:[{since}Z TO *]' \
|
|
|
|
.format(since=get_changes_since)
|
2012-03-15 12:31:12 +01:00
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
try:
|
2015-10-28 15:34:27 +01:00
|
|
|
pkg_dicts = self._search_for_datasets(
|
|
|
|
remote_ckan_base_url,
|
|
|
|
fq_terms + [fq_since_last_time])
|
2015-10-27 18:33:22 +01:00
|
|
|
except SearchError, e:
|
|
|
|
log.info('Searching for datasets changed since last time '
|
2016-02-15 13:10:44 +01:00
|
|
|
'gave an error: %s', e)
|
2015-10-27 18:33:22 +01:00
|
|
|
get_all_packages = True
|
|
|
|
|
2016-02-15 13:28:46 +01:00
|
|
|
if not get_all_packages and not pkg_dicts:
|
2015-10-27 18:33:22 +01:00
|
|
|
log.info('No datasets have been updated on the remote '
|
|
|
|
'CKAN instance since the last harvest job %s',
|
|
|
|
last_time)
|
|
|
|
return None
|
2011-05-17 18:26:42 +02:00
|
|
|
|
2015-10-23 19:30:28 +02:00
|
|
|
# Fall-back option - request all the datasets from the remote CKAN
|
2011-05-17 18:26:42 +02:00
|
|
|
if get_all_packages:
|
|
|
|
# Request all remote packages
|
|
|
|
try:
|
2015-10-28 15:34:27 +01:00
|
|
|
pkg_dicts = self._search_for_datasets(remote_ckan_base_url,
|
|
|
|
fq_terms)
|
2015-10-27 18:33:22 +01:00
|
|
|
except SearchError, e:
|
2016-02-15 13:10:44 +01:00
|
|
|
log.info('Searching for all datasets gave an error: %s', e)
|
2015-10-27 18:33:22 +01:00
|
|
|
self._save_gather_error(
|
2016-02-15 13:10:44 +01:00
|
|
|
'Unable to search remote CKAN for datasets:%s url:%s'
|
|
|
|
'terms:%s' % (e, remote_ckan_base_url, fq_terms),
|
2015-10-27 18:33:22 +01:00
|
|
|
harvest_job)
|
2016-02-15 13:10:44 +01:00
|
|
|
return None
|
2015-10-27 18:33:22 +01:00
|
|
|
if not pkg_dicts:
|
|
|
|
self._save_gather_error(
|
|
|
|
'No datasets found at CKAN: %s' % remote_ckan_base_url,
|
|
|
|
harvest_job)
|
|
|
|
return None
|
2011-05-17 18:26:42 +02:00
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
# Create harvest objects for each dataset
|
2011-05-17 18:26:42 +02:00
|
|
|
try:
|
2015-10-27 18:33:22 +01:00
|
|
|
package_ids = set()
|
2011-04-19 15:54:59 +02:00
|
|
|
object_ids = []
|
2015-10-27 18:33:22 +01:00
|
|
|
for pkg_dict in pkg_dicts:
|
|
|
|
if pkg_dict['id'] in package_ids:
|
|
|
|
log.info('Discarding duplicate dataset %s - probably due '
|
|
|
|
'to datasets being changed at the same time as '
|
|
|
|
'when the harvester was paging through',
|
|
|
|
pkg_dict['id'])
|
|
|
|
continue
|
|
|
|
package_ids.add(pkg_dict['id'])
|
|
|
|
|
2016-02-17 11:05:57 +01:00
|
|
|
log.debug('Creating HarvestObject for %s %s',
|
|
|
|
pkg_dict['name'], pkg_dict['id'])
|
2015-10-27 18:33:22 +01:00
|
|
|
obj = HarvestObject(guid=pkg_dict['id'],
|
|
|
|
job=harvest_job,
|
|
|
|
content=json.dumps(pkg_dict))
|
|
|
|
obj.save()
|
|
|
|
object_ids.append(obj.id)
|
|
|
|
|
|
|
|
return object_ids
|
2011-04-19 15:54:59 +02:00
|
|
|
except Exception, e:
|
2015-10-27 18:33:22 +01:00
|
|
|
self._save_gather_error('%r' % e.message, harvest_job)
|
|
|
|
|
2015-10-28 15:34:27 +01:00
|
|
|
def _search_for_datasets(self, remote_ckan_base_url, fq_terms=None):
|
2015-10-27 18:33:22 +01:00
|
|
|
'''Does a dataset search on a remote CKAN and returns the results.
|
|
|
|
|
|
|
|
Deals with paging to return all the results, not just the first page.
|
|
|
|
'''
|
|
|
|
base_search_url = remote_ckan_base_url + self._get_search_api_offset()
|
|
|
|
params = {'rows': '100', 'start': '0'}
|
2016-02-12 19:00:00 +01:00
|
|
|
# There is the worry that datasets will be changed whilst we are paging
|
|
|
|
# through them.
|
|
|
|
# * In SOLR 4.7 there is a cursor, but not using that yet
|
|
|
|
# because few CKANs are running that version yet.
|
|
|
|
# * However we sort, then new names added or removed before the current
|
|
|
|
# page would cause existing names on the next page to be missed or
|
|
|
|
# double counted.
|
|
|
|
# * Another approach might be to sort by metadata_modified and always
|
|
|
|
# ask for changes since (and including) the date of the last item of
|
|
|
|
# the day before. However if the entire page is of the exact same
|
|
|
|
# time, then you end up in an infinite loop asking for the same page.
|
|
|
|
# * We choose a balanced approach of sorting by ID, which means
|
|
|
|
# datasets are only missed if some are removed, which is far less
|
|
|
|
# likely than any being added. If some are missed then it is assumed
|
|
|
|
# they will harvested the next time anyway. When datasets are added,
|
|
|
|
# we are at risk of seeing datasets twice in the paging, so we detect
|
|
|
|
# and remove any duplicates.
|
|
|
|
params['sort'] = 'id asc'
|
2015-10-28 15:34:27 +01:00
|
|
|
if fq_terms:
|
|
|
|
params['fq'] = ' '.join(fq_terms)
|
2015-10-27 18:33:22 +01:00
|
|
|
|
|
|
|
pkg_dicts = []
|
2016-02-12 19:00:00 +01:00
|
|
|
pkg_ids = set()
|
2015-10-27 18:33:22 +01:00
|
|
|
previous_content = None
|
|
|
|
while True:
|
|
|
|
url = base_search_url + '?' + urllib.urlencode(params)
|
|
|
|
log.debug('Searching for CKAN datasets: %s', url)
|
|
|
|
try:
|
|
|
|
content = self._get_content(url)
|
2016-02-15 13:10:44 +01:00
|
|
|
except ContentFetchError, e:
|
|
|
|
raise SearchError(
|
|
|
|
'Error sending request to search remote '
|
|
|
|
'CKAN instance %s using URL %r. Error: %s' %
|
|
|
|
(remote_ckan_base_url, url, e))
|
2015-10-27 18:33:22 +01:00
|
|
|
|
|
|
|
if previous_content and content == previous_content:
|
|
|
|
raise SearchError('The paging doesn\'t seem to work. URL: %s' %
|
|
|
|
url)
|
|
|
|
try:
|
|
|
|
response_dict = json.loads(content)
|
|
|
|
except ValueError:
|
|
|
|
raise SearchError('Response from remote CKAN was not JSON: %r'
|
|
|
|
% content)
|
|
|
|
try:
|
|
|
|
pkg_dicts_page = response_dict.get('result', {}).get('results',
|
|
|
|
[])
|
|
|
|
except ValueError:
|
|
|
|
raise SearchError('Response JSON did not contain '
|
|
|
|
'result/results: %r' % response_dict)
|
2016-02-12 19:00:00 +01:00
|
|
|
|
|
|
|
# Weed out any datasets found on previous pages (should datasets be
|
|
|
|
# changing while we page)
|
|
|
|
ids_in_page = set(p['id'] for p in pkg_dicts_page)
|
|
|
|
duplicate_ids = ids_in_page & pkg_ids
|
|
|
|
if duplicate_ids:
|
|
|
|
pkg_dicts_page = [p for p in pkg_dicts_page
|
|
|
|
if p['id'] not in duplicate_ids]
|
|
|
|
pkg_ids |= ids_in_page
|
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
pkg_dicts.extend(pkg_dicts_page)
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
if len(pkg_dicts_page) == 0:
|
|
|
|
break
|
2011-06-07 14:35:11 +02:00
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
params['start'] = str(int(params['start']) + int(params['rows']))
|
2011-06-07 14:35:11 +02:00
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
return pkg_dicts
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-11-02 17:59:19 +01:00
|
|
|
@classmethod
|
|
|
|
def _last_error_free_job(cls, harvest_job):
|
|
|
|
# TODO weed out cancelled jobs somehow.
|
|
|
|
# look for jobs with no gather errors
|
|
|
|
jobs = \
|
|
|
|
model.Session.query(HarvestJob) \
|
|
|
|
.filter(HarvestJob.source == harvest_job.source) \
|
|
|
|
.filter(HarvestJob.gather_started != None) \
|
|
|
|
.filter(HarvestJob.status == 'Finished') \
|
|
|
|
.filter(HarvestJob.id != harvest_job.id) \
|
|
|
|
.filter(
|
|
|
|
~exists().where(
|
|
|
|
HarvestGatherError.harvest_job_id == HarvestJob.id)) \
|
|
|
|
.order_by(HarvestJob.gather_started.desc())
|
|
|
|
# now check them until we find one with no fetch/import errors
|
|
|
|
# (looping rather than doing sql, in case there are lots of objects
|
|
|
|
# and lots of jobs)
|
|
|
|
for job in jobs:
|
|
|
|
for obj in job.objects:
|
2016-02-15 14:16:23 +01:00
|
|
|
if obj.current is False and \
|
|
|
|
obj.report_status != 'not modified':
|
2015-11-02 17:59:19 +01:00
|
|
|
# unsuccessful, so go onto the next job
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
return job
|
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
def fetch_stage(self, harvest_object):
|
|
|
|
# Nothing to do here - we got the package dict in the search in the
|
|
|
|
# gather stage
|
2011-04-19 15:54:59 +02:00
|
|
|
return True
|
|
|
|
|
2015-10-27 18:33:22 +01:00
|
|
|
def import_stage(self, harvest_object):
|
2011-04-19 15:54:59 +02:00
|
|
|
log.debug('In CKANHarvester import_stage')
|
2015-06-11 11:38:33 +02:00
|
|
|
|
2016-05-23 13:20:08 +02:00
|
|
|
base_context = {'model': model, 'session': model.Session,
|
|
|
|
'user': self._get_user_name()}
|
2011-04-19 15:54:59 +02:00
|
|
|
if not harvest_object:
|
|
|
|
log.error('No harvest object received')
|
|
|
|
return False
|
|
|
|
|
|
|
|
if harvest_object.content is None:
|
2015-10-27 18:33:22 +01:00
|
|
|
self._save_object_error('Empty content for object %s' %
|
|
|
|
harvest_object.id,
|
|
|
|
harvest_object, 'Import')
|
2011-04-19 15:54:59 +02:00
|
|
|
return False
|
|
|
|
|
2011-06-14 16:59:13 +02:00
|
|
|
self._set_config(harvest_object.job.source.config)
|
2011-06-07 14:35:11 +02:00
|
|
|
|
2011-06-02 12:07:07 +02:00
|
|
|
try:
|
2011-04-19 15:54:59 +02:00
|
|
|
package_dict = json.loads(harvest_object.content)
|
2011-11-18 14:20:41 +01:00
|
|
|
|
2013-08-15 15:38:33 +02:00
|
|
|
if package_dict.get('type') == 'harvest':
|
|
|
|
log.warn('Remote dataset is a harvest source, ignoring...')
|
2013-10-23 07:40:55 +02:00
|
|
|
return True
|
2013-08-15 15:38:33 +02:00
|
|
|
|
2011-11-18 14:20:41 +01:00
|
|
|
# Set default tags if needed
|
2015-10-27 18:33:22 +01:00
|
|
|
default_tags = self.config.get('default_tags', [])
|
2011-11-18 14:20:41 +01:00
|
|
|
if default_tags:
|
|
|
|
if not 'tags' in package_dict:
|
|
|
|
package_dict['tags'] = []
|
2015-10-27 18:33:22 +01:00
|
|
|
package_dict['tags'].extend(
|
|
|
|
[t for t in default_tags if t not in package_dict['tags']])
|
2011-11-18 14:20:41 +01:00
|
|
|
|
2013-05-24 17:55:05 +02:00
|
|
|
remote_groups = self.config.get('remote_groups', None)
|
2013-05-30 19:06:15 +02:00
|
|
|
if not remote_groups in ('only_local', 'create'):
|
|
|
|
# Ignore remote groups
|
|
|
|
package_dict.pop('groups', None)
|
|
|
|
else:
|
|
|
|
if not 'groups' in package_dict:
|
|
|
|
package_dict['groups'] = []
|
|
|
|
|
2013-05-24 17:55:05 +02:00
|
|
|
# check if remote groups exist locally, otherwise remove
|
|
|
|
validated_groups = []
|
|
|
|
|
2016-05-20 16:38:48 +02:00
|
|
|
for group_ in package_dict['groups']:
|
2013-05-24 17:55:05 +02:00
|
|
|
try:
|
2016-05-20 16:38:48 +02:00
|
|
|
data_dict = {'id': group_['id']}
|
2016-05-23 13:20:08 +02:00
|
|
|
group = get_action('group_show')(base_context.copy(), data_dict)
|
2016-05-20 16:38:48 +02:00
|
|
|
validated_groups.append({'id': group['id'], 'name': group['name']})
|
|
|
|
|
2013-05-24 17:55:05 +02:00
|
|
|
except NotFound, e:
|
2016-05-20 16:38:48 +02:00
|
|
|
log.info('Group %s is not available', group_)
|
2013-05-24 17:55:05 +02:00
|
|
|
if remote_groups == 'create':
|
|
|
|
try:
|
2016-05-20 16:38:48 +02:00
|
|
|
group = self._get_group(harvest_object.source.url, group_)
|
2015-01-15 00:07:26 +01:00
|
|
|
except RemoteResourceError:
|
2016-05-20 16:38:48 +02:00
|
|
|
log.error('Could not get remote group %s', group_)
|
2013-05-24 17:55:05 +02:00
|
|
|
continue
|
|
|
|
|
|
|
|
for key in ['packages', 'created', 'users', 'groups', 'tags', 'extras', 'display_name']:
|
|
|
|
group.pop(key, None)
|
2015-06-11 11:38:33 +02:00
|
|
|
|
2016-05-23 13:20:08 +02:00
|
|
|
get_action('group_create')(base_context.copy(), group)
|
2016-05-20 16:38:48 +02:00
|
|
|
log.info('Group %s has been newly created', group_)
|
|
|
|
validated_groups.append({'id': group['id'], 'name': group['name']})
|
2013-05-24 17:55:05 +02:00
|
|
|
|
|
|
|
package_dict['groups'] = validated_groups
|
2013-05-16 18:30:54 +02:00
|
|
|
|
2013-10-22 17:24:43 +02:00
|
|
|
# Local harvest source organization
|
2016-05-23 13:20:08 +02:00
|
|
|
source_dataset = get_action('package_show')(base_context.copy(), {'id': harvest_object.source.id})
|
2013-10-22 17:24:43 +02:00
|
|
|
local_org = source_dataset.get('owner_org')
|
|
|
|
|
2013-10-04 15:34:22 +02:00
|
|
|
remote_orgs = self.config.get('remote_orgs', None)
|
2013-10-22 17:24:43 +02:00
|
|
|
|
2013-10-07 11:22:19 +02:00
|
|
|
if not remote_orgs in ('only_local', 'create'):
|
2013-10-22 17:24:43 +02:00
|
|
|
# Assign dataset to the source organization
|
|
|
|
package_dict['owner_org'] = local_org
|
2013-10-04 15:34:22 +02:00
|
|
|
else:
|
|
|
|
if not 'owner_org' in package_dict:
|
|
|
|
package_dict['owner_org'] = None
|
|
|
|
|
|
|
|
# check if remote org exist locally, otherwise remove
|
|
|
|
validated_org = None
|
|
|
|
remote_org = package_dict['owner_org']
|
2013-10-22 17:24:43 +02:00
|
|
|
|
2013-10-11 18:08:32 +02:00
|
|
|
if remote_org:
|
|
|
|
try:
|
|
|
|
data_dict = {'id': remote_org}
|
2016-05-23 13:20:08 +02:00
|
|
|
org = get_action('organization_show')(base_context.copy(), data_dict)
|
2013-10-11 18:08:32 +02:00
|
|
|
validated_org = org['id']
|
|
|
|
except NotFound, e:
|
2015-10-27 18:43:11 +01:00
|
|
|
log.info('Organization %s is not available', remote_org)
|
2013-10-11 18:08:32 +02:00
|
|
|
if remote_orgs == 'create':
|
|
|
|
try:
|
2015-01-14 00:10:27 +01:00
|
|
|
try:
|
|
|
|
org = self._get_organization(harvest_object.source.url, remote_org)
|
2015-01-15 00:07:26 +01:00
|
|
|
except RemoteResourceError:
|
2015-01-14 00:10:27 +01:00
|
|
|
# fallback if remote CKAN exposes organizations as groups
|
|
|
|
# this especially targets older versions of CKAN
|
|
|
|
org = self._get_group(harvest_object.source.url, remote_org)
|
|
|
|
|
2013-10-11 18:08:32 +02:00
|
|
|
for key in ['packages', 'created', 'users', 'groups', 'tags', 'extras', 'display_name', 'type']:
|
|
|
|
org.pop(key, None)
|
2016-05-23 13:20:08 +02:00
|
|
|
get_action('organization_create')(base_context.copy(), org)
|
2015-10-27 18:43:11 +01:00
|
|
|
log.info('Organization %s has been newly created', remote_org)
|
2013-10-11 18:08:32 +02:00
|
|
|
validated_org = org['id']
|
2015-01-15 00:07:26 +01:00
|
|
|
except (RemoteResourceError, ValidationError):
|
2015-10-27 18:43:11 +01:00
|
|
|
log.error('Could not get remote org %s', remote_org)
|
2013-10-04 15:34:22 +02:00
|
|
|
|
2013-10-22 17:24:43 +02:00
|
|
|
package_dict['owner_org'] = validated_org or local_org
|
2011-11-18 14:20:41 +01:00
|
|
|
|
|
|
|
# Set default groups if needed
|
2013-05-24 17:55:05 +02:00
|
|
|
default_groups = self.config.get('default_groups', [])
|
2011-11-18 14:20:41 +01:00
|
|
|
if default_groups:
|
2014-02-10 14:16:58 +01:00
|
|
|
if not 'groups' in package_dict:
|
|
|
|
package_dict['groups'] = []
|
2015-10-23 19:30:28 +02:00
|
|
|
package_dict['groups'].extend(
|
|
|
|
[g for g in default_groups
|
|
|
|
if g not in package_dict['groups']])
|
2013-05-31 14:56:53 +02:00
|
|
|
|
2012-01-10 18:07:19 +01:00
|
|
|
# Set default extras if needed
|
2015-10-23 19:30:28 +02:00
|
|
|
default_extras = self.config.get('default_extras', {})
|
|
|
|
def get_extra(key, package_dict):
|
|
|
|
for extra in package_dict.get('extras', []):
|
|
|
|
if extra['key'] == key:
|
|
|
|
return extra
|
2012-01-10 18:07:19 +01:00
|
|
|
if default_extras:
|
2015-10-23 19:30:28 +02:00
|
|
|
override_extras = self.config.get('override_extras', False)
|
2012-01-10 18:07:19 +01:00
|
|
|
if not 'extras' in package_dict:
|
|
|
|
package_dict['extras'] = {}
|
2015-10-23 19:30:28 +02:00
|
|
|
for key, value in default_extras.iteritems():
|
|
|
|
existing_extra = get_extra(key, package_dict)
|
|
|
|
if existing_extra and not override_extras:
|
|
|
|
continue # no need for the default
|
|
|
|
if existing_extra:
|
|
|
|
package_dict['extras'].remove(existing_extra)
|
|
|
|
# Look for replacement strings
|
|
|
|
if isinstance(value, basestring):
|
|
|
|
value = value.format(
|
|
|
|
harvest_source_id=harvest_object.job.source.id,
|
|
|
|
harvest_source_url=
|
|
|
|
harvest_object.job.source.url.strip('/'),
|
|
|
|
harvest_source_title=
|
|
|
|
harvest_object.job.source.title,
|
|
|
|
harvest_job_id=harvest_object.job.id,
|
|
|
|
harvest_object_id=harvest_object.id,
|
|
|
|
dataset_id=package_dict['id'])
|
|
|
|
|
|
|
|
package_dict['extras'].append({'key': key, 'value': value})
|
2012-01-10 18:07:19 +01:00
|
|
|
|
2014-02-11 18:27:19 +01:00
|
|
|
for resource in package_dict.get('resources', []):
|
2015-11-02 19:13:29 +01:00
|
|
|
# Clear remote url_type for resources (eg datastore, upload) as
|
|
|
|
# we are only creating normal resources with links to the
|
|
|
|
# remote ones
|
2014-02-11 18:27:19 +01:00
|
|
|
resource.pop('url_type', None)
|
|
|
|
|
2015-11-02 19:13:29 +01:00
|
|
|
# Clear revision_id as the revision won't exist on this CKAN
|
|
|
|
# and saving it will cause an IntegrityError with the foreign
|
|
|
|
# key.
|
|
|
|
resource.pop('revision_id', None)
|
|
|
|
|
2015-10-23 19:30:28 +02:00
|
|
|
result = self._create_or_update_package(
|
|
|
|
package_dict, harvest_object, package_dict_form='package_show')
|
2011-11-18 15:30:10 +01:00
|
|
|
|
2015-11-03 01:22:53 +01:00
|
|
|
return result
|
2015-10-23 19:30:28 +02:00
|
|
|
except ValidationError, e:
|
|
|
|
self._save_object_error('Invalid package with GUID %s: %r' %
|
|
|
|
(harvest_object.guid, e.error_dict),
|
|
|
|
harvest_object, 'Import')
|
2011-04-19 15:54:59 +02:00
|
|
|
except Exception, e:
|
2015-10-23 19:30:28 +02:00
|
|
|
self._save_object_error('%s' % e, harvest_object, 'Import')
|
|
|
|
|
2011-04-19 15:54:59 +02:00
|
|
|
|
2015-01-15 00:07:26 +01:00
|
|
|
class ContentFetchError(Exception):
|
|
|
|
pass
|
|
|
|
|
2015-11-23 22:36:45 +01:00
|
|
|
class ContentNotFoundError(ContentFetchError):
|
|
|
|
pass
|
2015-10-23 19:30:28 +02:00
|
|
|
|
2015-01-15 00:07:26 +01:00
|
|
|
class RemoteResourceError(Exception):
|
|
|
|
pass
|
2015-10-27 18:33:22 +01:00
|
|
|
|
|
|
|
|
|
|
|
class SearchError(Exception):
|
|
|
|
pass
|