tasks_2.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. def save_archival(resource, status_id, reason, url_redirected_to,
  2. download_result, archive_result, log):
  3. '''Writes to the archival table the result of an attempt to download
  4. the resource.
  5. May propagate a CkanError.
  6. '''
  7. now = datetime.datetime.now()
  8. from ckanext.archiver.model import Archival, Status
  9. from ckan import model
  10. archival = Archival.get_for_resource(resource['id'])
  11. first_archival = not archival
  12. previous_archival_was_broken = None
  13. if not archival:
  14. archival = Archival.create(resource['id'])
  15. model.Session.add(archival)
  16. else:
  17. log.info('Archival from before: %r', archival)
  18. previous_archival_was_broken = archival.is_broken
  19. try:
  20. revision = model.Session.query(model.Revision) \
  21. .get(resource['revision_id'])
  22. archival.resource_timestamp = revision.timestamp
  23. except AttributeError:
  24. # CKAN 2.9 doesn't have revisions, so we can't get a timestamp
  25. pass
  26. # Details of the latest archival attempt
  27. archival.status_id = status_id
  28. archival.is_broken = Status.is_status_broken(status_id)
  29. archival.reason = reason
  30. archival.url_redirected_to = url_redirected_to
  31. # Details of successful archival
  32. if archival.is_broken is False:
  33. archival.cache_filepath = archive_result['cache_filepath']
  34. archival.cache_url = archive_result['cache_url']
  35. archival.size = download_result['size']
  36. archival.mimetype = download_result['mimetype']
  37. archival.hash = download_result['hash']
  38. archival.etag = download_result['headers'].get('etag')
  39. archival.last_modified = download_result['headers'].get('last-modified')
  40. # History
  41. if archival.is_broken is False:
  42. archival.last_success = now
  43. archival.first_failure = None
  44. archival.failure_count = 0
  45. else:
  46. log.info('First_archival=%r Previous_broken=%r Failure_count=%r' %
  47. (first_archival, previous_archival_was_broken,
  48. archival.failure_count))
  49. if first_archival or previous_archival_was_broken is False:
  50. # i.e. this is the first failure (or the first archival)
  51. archival.first_failure = now
  52. archival.failure_count = 1
  53. else:
  54. archival.failure_count += 1
  55. archival.updated = now
  56. log.info('Archival saved: %r', archival)
  57. model.repo.commit_and_remove()