migrator.py 11 KB

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