migrator.py 11 KB

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