migrator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import logging
  2. import shutil
  3. from contextlib import ContextDecorator
  4. from os import makedirs, path
  5. from urllib.parse import urldefrag
  6. import requests
  7. import yaml
  8. from rdflib import Graph, URIRef
  9. from lakesuperior import env, basedir
  10. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  11. from lakesuperior.exceptions import InvalidResourceError
  12. from lakesuperior.globals import AppGlobals, ROOT_UID
  13. from lakesuperior.config_parser import parse_config
  14. logger = logging.getLogger(__name__)
  15. class StoreWrapper(ContextDecorator):
  16. """
  17. Open and close a store.
  18. """
  19. def __init__(self, store):
  20. self.store = store
  21. def __enter__(self):
  22. self.store.open(env.app_globals.rdfly.config)
  23. def __exit__(self, *exc):
  24. self.store.close()
  25. class Migrator:
  26. """
  27. Class to handle a database migration.
  28. This class holds state of progress and shared variables as it crawls
  29. through linked resources in an LDP server.
  30. Since a repository migration can be a very long operation but it is
  31. impossible to know the number of the resources to gather by LDP interaction
  32. alone, a progress ticker outputs the number of processed resources at
  33. regular intervals.
  34. """
  35. db_params = {
  36. 'map_size': 1024 ** 4,
  37. 'metasync': False,
  38. 'readahead': False,
  39. 'meminit': False,
  40. }
  41. """
  42. LMDB database parameters.
  43. See :meth:`lmdb.Environment.__init__`
  44. """
  45. ignored_preds = (
  46. nsc['fcrepo'].hasParent,
  47. nsc['fcrepo'].hasTransactionProvider,
  48. nsc['fcrepo'].hasFixityService,
  49. )
  50. """List of predicates to ignore when looking for links."""
  51. def __init__(
  52. self, src, dest, clear=False, zero_binaries=False,
  53. compact_uris=False, skip_errors=False):
  54. """
  55. Set up base paths and clean up existing directories.
  56. :param rdflib.URIRef src: Webroot of source repository. This must
  57. correspond to the LDP root node (for Fedora it can be e.g.
  58. ``http://localhost:8080fcrepo/rest/``) and is used to determine if
  59. URIs retrieved are managed by this repository.
  60. :param str dest: Destination repository path. If the location exists
  61. it must be a writable directory. It will be deleted and recreated.
  62. If it does not exist, it will be created along with its parents if
  63. missing.
  64. :param bool clear: Whether to clear any pre-existing data at the
  65. locations indicated.
  66. :param bool zero_binaries: Whether to create zero-byte binary files
  67. rather than copy the sources.
  68. :param bool compact_uris: NOT IMPLEMENTED. Whether the process should
  69. attempt to compact URIs generated with broken up path segments. If
  70. the UID matches a pattern such as ``/12/34/56/123456...`` it is
  71. converted to ``/123456...``. This would remove a lot of cruft
  72. caused by the pairtree segments. Note that this will change the
  73. publicly exposed URIs. If durability is a concern, a rewrite
  74. directive can be added to the HTTP server that proxies the WSGI
  75. endpoint.
  76. """
  77. # Set up repo folder structure and copy default configuration to
  78. # destination file.
  79. self.dbpath = '{}/data/ldprs_store'.format(dest)
  80. self.fpath = '{}/data/ldpnr_store'.format(dest)
  81. self.config_dir = '{}/etc'.format(dest)
  82. if clear:
  83. shutil.rmtree(dest, ignore_errors=True)
  84. if not path.isdir(self.config_dir):
  85. shutil.copytree(
  86. '{}/etc.defaults'.format(basedir), self.config_dir)
  87. # Modify and overwrite destination configuration.
  88. orig_config = parse_config(self.config_dir)
  89. orig_config['application']['store']['ldp_rs']['location'] = self.dbpath
  90. orig_config['application']['store']['ldp_nr']['path'] = self.fpath
  91. if clear:
  92. with open('{}/application.yml'.format(self.config_dir), 'w') \
  93. as config_file:
  94. config_file.write(yaml.dump(orig_config['application']))
  95. env.app_globals = AppGlobals(parse_config(self.config_dir))
  96. self.rdfly = env.app_globals.rdfly
  97. self.nonrdfly = env.app_globals.nonrdfly
  98. if clear:
  99. with env.app_globals.rdf_store.txn_mgr(True) as txn:
  100. self.rdfly.bootstrap()
  101. self.rdfly.store.close()
  102. env.app_globals.nonrdfly.bootstrap()
  103. self.src = src.rstrip('/')
  104. self.zero_binaries = zero_binaries
  105. self.skip_errors = skip_errors
  106. def migrate(self, start_pts=None, list_file=None):
  107. """
  108. Migrate the database.
  109. This method creates a fully functional and configured Lakesuperior
  110. data set contained in a folder from an LDP repository.
  111. :param start_pts: List of starting points to retrieve
  112. resources from. It would typically be the repository root in case
  113. of a full dump or one or more resources in the repository for a
  114. partial one.
  115. :type start_pts: tuple or list
  116. :param str list_file: path to a local file containing a list of URIs,
  117. one per line.
  118. """
  119. from lakesuperior.api import resource as rsrc_api
  120. self._ct = 0
  121. with StoreWrapper(self.rdfly.store):
  122. if start_pts:
  123. for start in start_pts:
  124. if not start.startswith('/'):
  125. raise ValueError(
  126. 'Starting point {} does not begin with a slash.'
  127. .format(start))
  128. if not rsrc_api.exists(start):
  129. # Create the full hierarchy with link to the parents.
  130. rsrc_api.create_or_replace(start)
  131. # Then populate the new resource and crawl for more
  132. # relationships.
  133. self._crawl(start)
  134. elif list_file:
  135. with open(list_file, 'r') as fp:
  136. for uri in fp:
  137. uid = uri.strip().replace(self.src, '')
  138. if not rsrc_api.exists(uid):
  139. try:
  140. rsrc_api.create_or_replace(uid)
  141. except InvalidResourceError:
  142. pass
  143. self._crawl(uid)
  144. logger.info('Dumped {} resources.'.format(self._ct))
  145. return self._ct
  146. def _crawl(self, uid):
  147. """
  148. Get the contents of a resource and its relationships recursively.
  149. This method recurses into itself each time a reference to a resource
  150. managed by the repository is encountered.
  151. :param str uid: The path relative to the source server webroot
  152. pointing to the resource to crawl, effectively the resource UID.
  153. """
  154. ibase = str(nsc['fcres'])
  155. # Public URI of source repo.
  156. uri = self.src + uid
  157. # Internal URI of destination.
  158. iuri = ibase + uid
  159. try:
  160. rsp = requests.head(uri)
  161. except:
  162. logger.warn('Error retrieving resource {}'.format(uri))
  163. return
  164. if rsp:
  165. if not self.skip_errors:
  166. rsp.raise_for_status()
  167. elif rsp.status_code > 399:
  168. print('Error retrieving resource {} headers: {} {}'.format(
  169. uri, rsp.status_code, rsp.text))
  170. # Determine LDP type.
  171. ldp_type = 'ldp_nr'
  172. try:
  173. for link in requests.utils.parse_header_links(
  174. rsp.headers.get('link')):
  175. if (
  176. link.get('rel') == 'type'
  177. and (
  178. link.get('url') == str(nsc['ldp'].RDFSource)
  179. or link.get('url') == str(nsc['ldp'].Container))
  180. ):
  181. # Resource is an LDP-RS.
  182. ldp_type = 'ldp_rs'
  183. break
  184. except TypeError:
  185. ldp_type = 'ldp_rs'
  186. #raise ValueError('URI {} is not an LDP resource.'.format(uri))
  187. # Get the whole RDF document now because we have to know all outbound
  188. # links.
  189. get_uri = (
  190. uri if ldp_type == 'ldp_rs' else '{}/fcr:metadata'.format(uri))
  191. try:
  192. get_rsp = requests.get(get_uri)
  193. except:
  194. logger.warn('Error retrieving resource {}'.format(get_uri))
  195. return
  196. if get_rsp:
  197. if not self.skip_errors:
  198. get_rsp.raise_for_status()
  199. elif get_rsp.status_code > 399:
  200. print('Error retrieving resource {} body: {} {}'.format(
  201. uri, get_rsp.status_code, get_rsp.text))
  202. data = get_rsp.content.replace(
  203. self.src.encode('utf-8'), ibase.encode('utf-8'))
  204. gr = Graph(identifier=iuri).parse(data=data, format='turtle')
  205. # Store raw graph data. No checks.
  206. with self.rdfly.store.txn_mgr(True):
  207. self.rdfly.modify_rsrc(uid, add_trp=set(gr))
  208. # Grab binary and set new resource parameters.
  209. if ldp_type == 'ldp_nr':
  210. provided_imr = gr.resource(URIRef(iuri))
  211. if self.zero_binaries:
  212. data = b''
  213. else:
  214. bin_rsp = requests.get(uri)
  215. if not self.skip_errors:
  216. bin_rsp.raise_for_status()
  217. elif bin_rsp.status_code > 399:
  218. print('Error retrieving resource {} body: {} {}'.format(
  219. uri, bin_rsp.status_code, bin_rsp.text))
  220. data = bin_rsp.content
  221. #import pdb; pdb.set_trace()
  222. uuid = str(gr.value(
  223. URIRef(iuri), nsc['premis'].hasMessageDigest)).split(':')[-1]
  224. fpath = self.nonrdfly.local_path(
  225. self.nonrdfly.config['path'], uuid)
  226. makedirs(path.dirname(fpath), exist_ok=True)
  227. with open(fpath, 'wb') as fh:
  228. fh.write(data)
  229. self._ct += 1
  230. if self._ct % 10 == 0:
  231. print('{} resources processed so far.'.format(self._ct))
  232. # Now, crawl through outbound links.
  233. # LDP-NR fcr:metadata must be checked too.
  234. for pred, obj in gr.predicate_objects():
  235. #import pdb; pdb.set_trace()
  236. obj_uid = obj.replace(ibase, '')
  237. with self.rdfly.store.txn_mgr(True):
  238. conditions = bool(
  239. isinstance(obj, URIRef)
  240. and obj.startswith(iuri)
  241. # Avoid ∞ loop with fragment URIs.
  242. and str(urldefrag(obj).url) != str(iuri)
  243. # Avoid ∞ loop with circular references.
  244. and not self.rdfly.ask_rsrc_exists(obj_uid)
  245. and pred not in self.ignored_preds
  246. )
  247. if conditions:
  248. print('Object {} will be crawled.'.format(obj_uid))
  249. self._crawl(urldefrag(obj_uid).url)