rsrc_centric_layout.py 24 KB

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