admin.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import logging
  2. from flask import Blueprint, jsonify, render_template
  3. from lakesuperior.api import admin as admin_api
  4. from lakesuperior.exceptions import (
  5. ChecksumValidationError, ResourceNotExistsError, TombstoneError)
  6. # Admin interface and REST API.
  7. logger = logging.getLogger(__name__)
  8. admin = Blueprint('admin', __name__)
  9. @admin.route('/stats', methods=['GET'])
  10. def stats():
  11. """
  12. Get repository statistics.
  13. """
  14. def fsize_fmt(num, suffix='b'):
  15. """
  16. Format an integer into 1024-block file size format.
  17. Adapted from Python 2 code on
  18. https://stackoverflow.com/a/1094933/3758232
  19. :param int num: Size value in bytes.
  20. :param str suffix: Suffix label (defaults to ``b``).
  21. :rtype: str
  22. :return: Formatted size to largest fitting unit.
  23. """
  24. for unit in ['','K','M','G','T','P','E','Z']:
  25. if abs(num) < 1024.0:
  26. return f'{num:3.1f} {unit}{suffix}'
  27. num /= 1024.0
  28. return f'{num:.1f} Y{suffix}'
  29. repo_stats = admin_api.stats()
  30. return render_template(
  31. 'stats.html', fsize_fmt=fsize_fmt, **repo_stats)
  32. @admin.route('/tools', methods=['GET'])
  33. def admin_tools():
  34. """
  35. Admin tools.
  36. @TODO stub.
  37. """
  38. return render_template('admin_tools.html')
  39. @admin.route('/<path:uid>/fixity', methods=['GET'])
  40. def fixity_check(uid):
  41. """
  42. Check the fixity of a resource.
  43. """
  44. uid = '/' + uid.strip('/')
  45. try:
  46. admin_api.fixity_check(uid)
  47. except ResourceNotExistsError as e:
  48. return str(e), 404
  49. except TombstoneError as e:
  50. return str(e), 410
  51. except ChecksumValidationError as e:
  52. check_pass = False
  53. else:
  54. check_pass = True
  55. return (
  56. jsonify({
  57. 'uid': uid,
  58. 'pass': check_pass,
  59. }),
  60. 200,
  61. {'content-type': 'application/json'}
  62. )