rsrc_centric_layout.py 24 KB

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