rsrc_centric_layout.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. import logging
  2. from collections import defaultdict
  3. from itertools import chain
  4. from string import Template
  5. from urllib.parse import urldefrag
  6. import arrow
  7. from rdflib import Dataset, Graph, Literal, URIRef, plugin
  8. from rdflib.namespace import RDF
  9. from rdflib.query import ResultException
  10. from rdflib.resource import Resource
  11. from rdflib.store import Store
  12. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  13. from lakesuperior.dictionaries.namespaces import ns_mgr as nsm
  14. from lakesuperior.dictionaries.srv_mgd_terms import srv_mgd_subjects, \
  15. srv_mgd_predicates, srv_mgd_types
  16. from lakesuperior.exceptions import (InvalidResourceError,
  17. ResourceNotExistsError, TombstoneError, PathSegmentError)
  18. from lakesuperior.env import env
  19. from lakesuperior.store.ldp_rs.lmdb_store import TxnManager
  20. META_GR_URI = nsc['fcsystem']['meta']
  21. HIST_GR_URI = nsc['fcsystem']['histmeta']
  22. PTREE_GR_URI = nsc['fcsystem']['pairtree']
  23. VERS_CONT_LABEL = 'fcr:versions'
  24. Lmdb = plugin.register('Lmdb', Store,
  25. 'lakesuperior.store.ldp_rs.lmdb_store', 'LmdbStore')
  26. logger = logging.getLogger(__name__)
  27. class RsrcCentricLayout:
  28. """
  29. This class exposes an interface to build graph store layouts. It also
  30. provides the basics of the triplestore connection.
  31. Some store layouts are provided. New ones aimed at specific uses
  32. and optimizations of the repository may be developed by extending this
  33. class and implementing all its abstract methods.
  34. A layout is implemented via application configuration. However, once
  35. contents are ingested in a repository, changing a layout will most likely
  36. require a migration.
  37. The custom layout must be in the lakesuperior.store.rdf
  38. package and the class implementing the layout must be called
  39. `StoreLayout`. The module name is the one defined in the app
  40. configuration.
  41. E.g. if the configuration indicates `simple_layout` the application will
  42. look for
  43. `lakesuperior.store.rdf.simple_layout.SimpleLayout`.
  44. """
  45. _graph_uids = ('fcadmin', 'fcmain', 'fcstruct')
  46. # @TODO Move to a config file?
  47. attr_map = {
  48. nsc['fcadmin']: {
  49. # List of server-managed predicates. Triples bearing one of these
  50. # predicates will go in the metadata graph.
  51. 'p': {
  52. nsc['ebucore'].hasMimeType,
  53. nsc['fcrepo'].created,
  54. nsc['fcrepo'].createdBy,
  55. nsc['fcrepo'].hasParent,
  56. nsc['fcrepo'].hasVersion,
  57. nsc['fcrepo'].lastModified,
  58. nsc['fcrepo'].lastModifiedBy,
  59. nsc['fcsystem'].tombstone,
  60. # The following 3 are set by the user but still in this group
  61. # for convenience.
  62. nsc['ldp'].membershipResource,
  63. nsc['ldp'].hasMemberRelation,
  64. nsc['ldp'].insertedContentRelation,
  65. nsc['iana'].describedBy,
  66. nsc['premis'].hasMessageDigest,
  67. nsc['premis'].hasSize,
  68. },
  69. # List of metadata RDF types. Triples bearing one of these types in
  70. # the object will go in the metadata graph.
  71. 't': {
  72. nsc['fcrepo'].Binary,
  73. nsc['fcrepo'].Container,
  74. nsc['fcrepo'].Pairtree,
  75. nsc['fcrepo'].Resource,
  76. nsc['fcsystem'].Tombstone,
  77. nsc['ldp'].BasicContainer,
  78. nsc['ldp'].Container,
  79. nsc['ldp'].DirectContainer,
  80. nsc['ldp'].IndirectContainer,
  81. nsc['ldp'].NonRDFSource,
  82. nsc['ldp'].RDFSource,
  83. nsc['ldp'].Resource,
  84. },
  85. },
  86. nsc['fcstruct']: {
  87. # These are placed in a separate graph for optimization purposes.
  88. 'p': {
  89. nsc['ldp'].contains,
  90. nsc['pcdm'].hasMember,
  91. }
  92. },
  93. }
  94. # RDF types of graphs by prefix.
  95. graph_ns_types = {
  96. nsc['fcadmin']: nsc['fcsystem'].AdminGraph,
  97. nsc['fcmain']: nsc['fcsystem'].UserProvidedGraph,
  98. nsc['fcstruct']: nsc['fcsystem'].StructureGraph,
  99. }
  100. ## MAGIC METHODS ##
  101. def __init__(self, config):
  102. """Initialize the graph store and a layout.
  103. NOTE: `rdflib.Dataset` requires a RDF 1.1 compliant store with support
  104. for Graph Store HTTP protocol
  105. (https://www.w3.org/TR/sparql11-http-rdf-update/). Blazegraph supports
  106. this only in the (currently unreleased) 2.2 branch. It works with Jena,
  107. which is currently the reference implementation.
  108. """
  109. self.config = config
  110. self.store = plugin.get('Lmdb', Store)(config['location'])
  111. self.ds = Dataset(self.store, default_union=True)
  112. self.ds.namespace_manager = nsm
  113. @property
  114. def attr_routes(self):
  115. """
  116. This is a map that allows specific triples to go to certain graphs.
  117. It is a machine-friendly version of the static attribute `attr_map`
  118. which is formatted for human readability and to avoid repetition.
  119. The attributes not mapped here (usually user-provided triples with no
  120. special meaning to the application) go to the `fcmain:` graph.
  121. The output of this is a dict with a similar structure::
  122. {
  123. 'p': {
  124. <Predicate P1>: <destination graph G1>,
  125. <Predicate P2>: <destination graph G1>,
  126. <Predicate P3>: <destination graph G1>,
  127. <Predicate P4>: <destination graph G2>,
  128. [...]
  129. },
  130. 't': {
  131. <RDF Type T1>: <destination graph G1>,
  132. <RDF Type T2>: <destination graph G3>,
  133. [...]
  134. }
  135. }
  136. """
  137. if not hasattr(self, '_attr_routes'):
  138. self._attr_routes = {'p': {}, 't': {}}
  139. for dest in self.attr_map.keys():
  140. for term_k, terms in self.attr_map[dest].items():
  141. self._attr_routes[term_k].update(
  142. {term: dest for term in terms})
  143. return self._attr_routes
  144. def bootstrap(self):
  145. """
  146. Delete all graphs and insert the basic triples.
  147. """
  148. logger.info('Deleting all data from the graph store.')
  149. store = self.ds.store
  150. if getattr(store, 'is_txn_open', False):
  151. store.rollback()
  152. store.destroy(store.path)
  153. logger.info('Initializing the graph store with system data.')
  154. store.open()
  155. with TxnManager(store, True):
  156. with open('data/bootstrap/rsrc_centric_layout.sparql', 'r') as f:
  157. data = Template(f.read())
  158. self.ds.update(data.substitute(timestamp=arrow.utcnow()))
  159. def get_raw(self, uri, ctx=None):
  160. """
  161. Get a raw graph of a non-LDP resource.
  162. The graph is queried across all contexts or within a specific one.
  163. :param rdflib.term.URIRef s: URI of the subject.
  164. :param rdflib.term.URIRef ctx: URI of the optional context. If None,
  165. all named graphs are queried.
  166. :rtype: rdflib.Graph
  167. """
  168. return self.store.triples((nsc['fcres'][uid], None, None), ctx)
  169. def count_rsrc(self):
  170. """
  171. Return a count of first-class resources, subdivided in "live" and
  172. historic snapshots.
  173. """
  174. with TxnManager(self.ds.store) as txn:
  175. main = set(
  176. self.ds.graph(META_GR_URI)[ : nsc['foaf'].primaryTopic : ])
  177. hist = set(
  178. self.ds.graph(HIST_GR_URI)[ : nsc['foaf'].primaryTopic : ])
  179. return {'main': len(main), 'hist': len(hist)}
  180. def raw_query(self, qry_str):
  181. """
  182. Perform a straight query to the graph store.
  183. """
  184. return self.ds.query(qry_str)
  185. def get_imr(
  186. self, uid, ver_uid=None, strict=True, incl_inbound=False,
  187. incl_children=True, embed_children=False, **kwargs):
  188. """
  189. See base_rdf_layout.get_imr.
  190. """
  191. if ver_uid:
  192. uid = self.snapshot_uid(uid, ver_uid)
  193. graphs = {pfx[uid] for pfx in self.graph_ns_types.keys()}
  194. # Exclude children: remove containment graphs.
  195. if not incl_children:
  196. graphs.remove(nsc['fcstruct'][uid])
  197. rsrc_graphs = [
  198. self.ds.graph(gr)
  199. for gr in graphs]
  200. resultset = set(chain.from_iterable(rsrc_graphs))
  201. imr = Graph(identifier=nsc['fcres'][uid])
  202. imr += resultset
  203. # Include inbound relationships.
  204. if incl_inbound and len(imr):
  205. imr += self.get_inbound_rel(nsc['fcres'][uid])
  206. #logger.debug('Found resource: {}'.format(
  207. # imr.serialize(format='turtle').decode('utf-8')))
  208. if strict:
  209. self._check_rsrc_status(imr)
  210. return imr
  211. def ask_rsrc_exists(self, uid):
  212. """
  213. See base_rdf_layout.ask_rsrc_exists.
  214. """
  215. logger.debug('Checking if resource exists: {}'.format(uid))
  216. meta_gr = self.ds.graph(nsc['fcadmin'][uid])
  217. return bool(
  218. meta_gr[nsc['fcres'][uid] : RDF.type : nsc['fcrepo'].Resource])
  219. def get_metadata(self, uid, ver_uid=None, strict=True):
  220. """
  221. This is an optimized query to get only the administrative metadata.
  222. """
  223. logger.debug('Getting metadata for: {}'.format(uid))
  224. if ver_uid:
  225. uid = self.snapshot_uid(uid, ver_uid)
  226. uri = nsc['fcres'][uid]
  227. gr = Graph(identifier=uri)
  228. gr += self.ds.graph(nsc['fcadmin'][uid])
  229. if strict:
  230. self._check_rsrc_status(gr)
  231. return gr
  232. def get_user_data(self, uid):
  233. """
  234. Get all the user-provided data.
  235. :param string uid: Resource UID.
  236. """
  237. # *TODO* This only works as long as there is only one user-provided
  238. # graph. If multiple user-provided graphs will be supported, this
  239. # should use another query to get all of them.
  240. userdata_gr = Graph(identifier=nsc['fcres'][uid])
  241. userdata_gr += self.ds.graph(nsc['fcmain'][uid])
  242. return userdata_gr
  243. def get_version_info(self, uid, strict=True):
  244. """
  245. Get all metadata about a resource's versions.
  246. """
  247. # **Note:** This pretty much bends the ontology—it replaces the graph URI
  248. # with the subject URI. But the concepts of data and metadata in Fedora
  249. # are quite fluid anyways...
  250. # WIP—Is it worth to replace SPARQL here?
  251. #versions = self.ds.graph(nsc['fcadmin'][uid]).triples(
  252. # (nsc['fcres'][uid], nsc['fcrepo'].hasVersion, None))
  253. #for version in versions:
  254. # version_meta = self.ds.graph(HIST_GRAPH_URI).triples(
  255. qry = """
  256. CONSTRUCT {
  257. ?s fcrepo:hasVersion ?v .
  258. ?v ?p ?o .
  259. } {
  260. GRAPH ?ag {
  261. ?s fcrepo:hasVersion ?v .
  262. }
  263. GRAPH ?hg {
  264. ?vm foaf:primaryTopic ?v .
  265. ?vm ?p ?o .
  266. FILTER (?o != ?v)
  267. }
  268. }"""
  269. gr = self._parse_construct(qry, init_bindings={
  270. 'ag': nsc['fcadmin'][uid],
  271. 'hg': HIST_GR_URI,
  272. 's': nsc['fcres'][uid]})
  273. ver_info_gr = Graph(identifier=nsc['fcres'][uid])
  274. ver_info_gr += gr
  275. if strict:
  276. self._check_rsrc_status(ver_info_gr)
  277. return ver_info_gr
  278. def get_inbound_rel(self, subj_uri, full_triple=True):
  279. """
  280. Query inbound relationships for a subject.
  281. This can be a list of either complete triples, or of subjects referring
  282. to the given URI. It excludes historic version snapshots.
  283. :param rdflib.URIRef subj_uri: Subject URI.
  284. :param boolean full_triple: Whether to return the full triples found
  285. or only the subjects. By default, full triples are returned.
  286. :rtype: Iterator(tuple(rdflib.term.Identifier) or rdflib.URIRef)
  287. :return: Inbound triples or subjects.
  288. """
  289. # Only return non-historic graphs.
  290. meta_gr = self.ds.graph(META_GR_URI)
  291. ptopic_uri = nsc['foaf'].primaryTopic
  292. yield from (
  293. (match[:3] if full_triple else match[0])
  294. for match in self.ds.quads((None, None, subj_uri, None))
  295. if set(meta_gr[ : ptopic_uri : match[0]])
  296. )
  297. def get_descendants(self, uid, recurse=True):
  298. """
  299. Get descendants (recursive children) of a resource.
  300. :param str uid: Resource UID.
  301. :rtype: Iterator(rdflib.URIRef)
  302. :return: Subjects of descendant resources.
  303. """
  304. ds = self.ds
  305. subj_uri = nsc['fcres'][uid]
  306. ctx_uri = nsc['fcstruct'][uid]
  307. def _recurse(dset, s, p, c):
  308. new_dset = set(ds.graph(c)[s : p])
  309. for ss in new_dset:
  310. dset.add(ss)
  311. cc = URIRef(ss.replace(nsc['fcres'], nsc['fcstruct']))
  312. if set(ds.graph(cc)[ss : p]):
  313. _recurse(dset, ss, p, cc)
  314. return dset
  315. return (
  316. _recurse(set(), subj_uri, nsc['ldp'].contains, ctx_uri)
  317. if recurse
  318. else ds.graph(ctx_uri)[subj_uri : nsc['ldp'].contains : ])
  319. def patch_rsrc(self, uid, qry):
  320. """
  321. Patch a resource with SPARQL-Update statements.
  322. The statement(s) is/are executed on the user-provided graph only
  323. to ensure that the scope is limited to the resource.
  324. :param str uid: UID of the resource to be patched.
  325. :param dict qry: Parsed and translated query, or query string.
  326. """
  327. # Add meta graph for user-defined triples. This may not be used but
  328. # it's simple and harmless to add here.
  329. self.ds.graph(META_GR_URI).add(
  330. (nsc['fcmain'][uid], nsc['foaf'].primaryTopic,
  331. nsc['fcres'][uid]))
  332. gr = self.ds.graph(nsc['fcmain'][uid])
  333. logger.debug('Updating graph {} with statements: {}'.format(
  334. nsc['fcmain'][uid], qry))
  335. return gr.update(qry)
  336. def forget_rsrc(self, uid, inbound=True, children=True):
  337. """
  338. Completely delete a resource and (optionally) its children and inbound
  339. references.
  340. NOTE: inbound references in historic versions are not affected.
  341. """
  342. # Localize variables to be used in loops.
  343. uri = nsc['fcres'][uid]
  344. topic_uri = nsc['foaf'].primaryTopic
  345. uid_fn = self.uri_to_uid
  346. # remove children.
  347. if children:
  348. logger.debug('Purging children for /{}'.format(uid))
  349. for rsrc_uri in self.get_descendants(uid, False):
  350. self.forget_rsrc(uid_fn(rsrc_uri), inbound, False)
  351. # Remove structure graph.
  352. self.ds.remove_graph(nsc['fcstruct'][uid])
  353. # Remove inbound references.
  354. if inbound:
  355. for ibs in self.get_inbound_rel(uri):
  356. self.ds.remove(ibs)
  357. # Remove versions.
  358. for ver_uri in self.ds.graph(nsc['fcadmin'][uid])[
  359. uri : nsc['fcrepo'].hasVersion : None]:
  360. self.delete_rsrc(uid_fn(ver_uri), True)
  361. # Remove resource itself.
  362. self.delete_rsrc(uid)
  363. def truncate_rsrc(self, uid):
  364. """
  365. Remove all user-provided data from a resource and only leave admin and
  366. structure data.
  367. """
  368. userdata = set(self.get_user_data(uid))
  369. return self.modify_rsrc(uid, remove_trp=userdata)
  370. def modify_rsrc(self, uid, remove_trp=set(), add_trp=set()):
  371. """
  372. Modify triples about a subject.
  373. This method adds and removes triple sets from specific graphs,
  374. indicated by the term router. It also adds metadata about the changed
  375. graphs.
  376. """
  377. remove_routes = defaultdict(set)
  378. add_routes = defaultdict(set)
  379. historic = VERS_CONT_LABEL in uid
  380. graph_types = set() # Graphs that need RDF type metadata added.
  381. # Create add and remove sets for each graph.
  382. for t in remove_trp:
  383. map_graph = self._map_graph_uri(t, uid)
  384. target_gr_uri = map_graph[0]
  385. remove_routes[target_gr_uri].add(t)
  386. graph_types.add(map_graph)
  387. for t in add_trp:
  388. map_graph = self._map_graph_uri(t, uid)
  389. target_gr_uri = map_graph[0]
  390. add_routes[target_gr_uri].add(t)
  391. graph_types.add(map_graph)
  392. # Decide if metadata go into historic or current graph.
  393. meta_gr_uri = HIST_GR_URI if historic else META_GR_URI
  394. meta_gr = self.ds.graph(meta_gr_uri)
  395. # Remove and add triple sets from each graph.
  396. for gr_uri, trp in remove_routes.items():
  397. gr = self.ds.graph(gr_uri)
  398. gr -= trp
  399. for gr_uri, trp in add_routes.items():
  400. gr = self.ds.graph(gr_uri)
  401. gr += trp
  402. # Add metadata.
  403. meta_gr.set(
  404. (gr_uri, nsc['foaf'].primaryTopic, nsc['fcres'][uid]))
  405. ts = getattr(env, 'timestamp_term', Literal(arrow.utcnow()))
  406. meta_gr.set((gr_uri, nsc['fcrepo'].created, ts))
  407. if historic:
  408. # @FIXME Ugly reverse engineering.
  409. ver_uid = uid.split(VERS_CONT_LABEL)[1].lstrip('/')
  410. meta_gr.set((
  411. gr_uri, nsc['fcrepo'].hasVersionLabel, Literal(ver_uid)))
  412. # *TODO* More provenance metadata can be added here.
  413. # Add graph RDF types.
  414. for gr_uri, gr_type in graph_types:
  415. meta_gr.add((gr_uri, RDF.type, gr_type))
  416. def delete_rsrc(self, uid, historic=False):
  417. """
  418. Delete all aspect graphs of an individual resource.
  419. :param uid: Resource UID.
  420. :param bool historic: Whether the UID is of a historic version.
  421. """
  422. meta_gr_uri = HIST_GR_URI if historic else META_GR_URI
  423. for gr_uri in self.ds.graph(meta_gr_uri)[
  424. : nsc['foaf'].primaryTopic : nsc['fcres'][uid]]:
  425. self.ds.remove_context(gr_uri)
  426. self.ds.graph(meta_gr_uri).remove((gr_uri, None, None))
  427. def snapshot_uid(self, uid, ver_uid):
  428. """
  429. Create a versioned UID string from a main UID and a version UID.
  430. """
  431. if VERS_CONT_LABEL in uid:
  432. raise InvalidResourceError(uid,
  433. 'Resource \'{}\' is already a version.')
  434. return '{}/{}/{}'.format(uid, VERS_CONT_LABEL, ver_uid)
  435. def uri_to_uid(self, uri):
  436. """
  437. Convert an internal URI to a UID.
  438. """
  439. return str(uri).replace(nsc['fcres'], '')
  440. def find_refint_violations(self):
  441. """
  442. Find all referential integrity violations.
  443. This method looks for dangling relationships within a repository by
  444. checking the objects of each triple; if the object is an in-repo
  445. resource reference, and no resource with that URI results to be in the
  446. repo, that triple is reported.
  447. :rtype: set
  448. :return: Triples referencing a repository URI that is not a resource.
  449. """
  450. for i, obj in enumerate(self.store.all_terms('o'), start=1):
  451. if (
  452. isinstance(obj, URIRef)
  453. and obj.startswith(nsc['fcres'])
  454. and not obj.endswith('fcr:fixity')
  455. and not obj.endswith('fcr:versions')
  456. and not self.ask_rsrc_exists(self.uri_to_uid(
  457. urldefrag(obj).url))):
  458. logger.warn('Object not found: {}'.format(obj))
  459. for trp in self.store.triples((None, None, obj)):
  460. yield trp
  461. if i % 100 == 0:
  462. logger.info('{} terms processed.'.format(i))
  463. ## PROTECTED MEMBERS ##
  464. def _check_rsrc_status(self, gr):
  465. """
  466. Check if a resource is not existing or if it is a tombstone.
  467. """
  468. uid = self.uri_to_uid(gr.identifier)
  469. if not len(gr):
  470. raise ResourceNotExistsError(uid)
  471. # Check if resource is a tombstone.
  472. if gr[gr.identifier : RDF.type : nsc['fcsystem'].Tombstone]:
  473. raise TombstoneError(
  474. uid, gr.value(gr.identifier, nsc['fcrepo'].created))
  475. elif gr.value(gr.identifier, nsc['fcsystem'].tombstone):
  476. raise TombstoneError(
  477. self.uri_to_uid(
  478. gr.value(gr.identifier, nsc['fcsystem'].tombstone)),
  479. gr.value(gr.identifier, nsc['fcrepo'].created))
  480. def _parse_construct(self, qry, init_bindings={}):
  481. """
  482. Parse a CONSTRUCT query.
  483. :rtype: rdflib.Graph
  484. """
  485. try:
  486. qres = self.ds.query(qry, initBindings=init_bindings)
  487. except ResultException:
  488. # RDFlib bug: https://github.com/RDFLib/rdflib/issues/775
  489. return Graph()
  490. else:
  491. return qres.graph
  492. def _map_graph_uri(self, t, uid):
  493. """
  494. Map a triple to a namespace prefix corresponding to a graph.
  495. :rtype: tuple
  496. :return: 2-tuple with a graph URI and an associated RDF type.
  497. """
  498. if t[1] in self.attr_routes['p'].keys():
  499. pfx = self.attr_routes['p'][t[1]]
  500. elif t[1] == RDF.type and t[2] in self.attr_routes['t'].keys():
  501. pfx = self.attr_routes['t'][t[2]]
  502. else:
  503. pfx = nsc['fcmain']
  504. return (pfx[uid], self.graph_ns_types[pfx])