ldpr.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. import logging
  2. import re
  3. from abc import ABCMeta
  4. from collections import defaultdict
  5. from hashlib import sha256
  6. # The threading and multiprocessing options below can be toggled by commenting
  7. # either one.
  8. #from threading import Thread as _Defer
  9. from multiprocessing import Process as _Defer
  10. from urllib.parse import urldefrag
  11. from uuid import uuid4
  12. import arrow
  13. from rdflib import Graph, URIRef, Literal
  14. from rdflib.compare import to_isomorphic
  15. from rdflib.namespace import RDF
  16. from lakesuperior import env, thread_env
  17. from lakesuperior.globals import (
  18. RES_CREATED, RES_DELETED, RES_UPDATED, ROOT_UID)
  19. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  20. from lakesuperior.dictionaries.srv_mgd_terms import (
  21. srv_mgd_subjects, srv_mgd_predicates, srv_mgd_types)
  22. from lakesuperior.exceptions import (
  23. InvalidResourceError, RefIntViolationError, ResourceNotExistsError,
  24. ServerManagedTermError, TombstoneError)
  25. from lakesuperior.store.ldp_rs.lmdb_triplestore import SimpleGraph, Imr
  26. from lakesuperior.store.ldp_rs.rsrc_centric_layout import VERS_CONT_LABEL
  27. from lakesuperior.toolbox import Toolbox
  28. rdfly = env.app_globals.rdfly
  29. logger = logging.getLogger(__name__)
  30. class Ldpr(metaclass=ABCMeta):
  31. """
  32. LDPR (LDP Resource).
  33. This class and related subclasses contain the implementation pieces of
  34. the `LDP Resource <https://www.w3.org/TR/ldp/#ldpr-resource>`__
  35. specifications, according to their `inheritance graph
  36. <https://www.w3.org/TR/ldp/#fig-ldpc-types>`__.
  37. **Note**: Even though LdpNr (which is a subclass of Ldpr) handles binary
  38. files, it still has an RDF representation in the triplestore. Hence, some
  39. of the RDF-related methods are defined in this class rather than in
  40. :class:`~lakesuperior.model.ldp_rs.LdpRs`.
  41. **Note:** Only internal facing (``info:fcres``-prefixed) URIs are handled
  42. in this class. Public-facing URI conversion is handled in the
  43. :mod:`~lakesuperior.endpoints.ldp` module.
  44. """
  45. EMBED_CHILD_RES_URI = nsc['fcrepo'].EmbedResources
  46. FCREPO_PTREE_TYPE = nsc['fcrepo'].Pairtree
  47. INS_CNT_REL_URI = nsc['ldp'].insertedContentRelation
  48. MBR_RSRC_URI = nsc['ldp'].membershipResource
  49. MBR_REL_URI = nsc['ldp'].hasMemberRelation
  50. RETURN_CHILD_RES_URI = nsc['fcrepo'].Children
  51. RETURN_INBOUND_REF_URI = nsc['fcrepo'].InboundReferences
  52. RETURN_SRV_MGD_RES_URI = nsc['fcrepo'].ServerManaged
  53. # Workflow type. Inbound means that the resource is being written to the
  54. # store, outbounnd is being retrieved for output.
  55. WRKF_INBOUND = '_workflow:inbound_'
  56. WRKF_OUTBOUND = '_workflow:outbound_'
  57. DEFAULT_USER = Literal('BypassAdmin')
  58. """
  59. Default user to be used for the `createdBy` and `lastUpdatedBy` if a user
  60. is not provided.
  61. """
  62. base_types = {
  63. nsc['fcrepo'].Resource,
  64. nsc['ldp'].Resource,
  65. nsc['ldp'].RDFSource,
  66. }
  67. """RDF Types that populate a new resource."""
  68. protected_pred = (
  69. nsc['fcrepo'].created,
  70. nsc['fcrepo'].createdBy,
  71. nsc['ldp'].contains,
  72. )
  73. """Predicates that do not get removed when a resource is replaced."""
  74. smt_allow_on_create = {
  75. nsc['ldp'].DirectContainer,
  76. nsc['ldp'].IndirectContainer,
  77. }
  78. """
  79. Server-managed RDF types ignored in the RDF payload if the resource is
  80. being created. N.B. These still raise an error if the resource exists.
  81. """
  82. delete_preds_on_replace = {
  83. nsc['ebucore'].hasMimeType,
  84. nsc['fcrepo'].lastModified,
  85. nsc['fcrepo'].lastModifiedBy,
  86. nsc['premis'].hasSize,
  87. nsc['premis'].hasMessageDigest,
  88. }
  89. """Predicates to remove when a resource is replaced."""
  90. _ignore_version_preds = {
  91. nsc['fcrepo'].hasParent,
  92. nsc['fcrepo'].hasVersions,
  93. nsc['fcrepo'].hasVersion,
  94. nsc['premis'].hasMessageDigest,
  95. nsc['ldp'].contains,
  96. }
  97. """Predicates that don't get versioned."""
  98. _ignore_version_types = {
  99. nsc['fcrepo'].Binary,
  100. nsc['fcrepo'].Container,
  101. nsc['fcrepo'].Pairtree,
  102. nsc['fcrepo'].Resource,
  103. nsc['fcrepo'].Version,
  104. nsc['ldp'].BasicContainer,
  105. nsc['ldp'].Container,
  106. nsc['ldp'].DirectContainer,
  107. nsc['ldp'].Resource,
  108. nsc['ldp'].RDFSource,
  109. nsc['ldp'].NonRDFSource,
  110. }
  111. """RDF types that don't get versioned."""
  112. ## MAGIC METHODS ##
  113. def __init__(self, uid, repr_opts={}, provided_imr=None, **kwargs):
  114. """
  115. Instantiate an in-memory LDP resource.
  116. :param str uid: uid of the resource. If None (must be explicitly
  117. set) it refers to the root node. It can also be the full URI or URN,
  118. in which case it will be converted.
  119. :param dict repr_opts: Options used to retrieve the IMR. See
  120. `parse_rfc7240` for format details.
  121. :param str provd_rdf: RDF data provided by the client in
  122. operations such as `PUT` or `POST`, serialized as a string. This sets
  123. the `provided_imr` property.
  124. """
  125. self.uid = (
  126. rdfly.uri_to_uid(uid) if isinstance(uid, URIRef) else uid)
  127. self.uri = nsc['fcres'][uid]
  128. # @FIXME Not ideal, should separate app-context dependent functions in
  129. # a different toolbox.
  130. self.tbox = Toolbox()
  131. self.provided_imr = provided_imr
  132. # Disable all internal checks e.g. for raw I/O.
  133. #@property
  134. #def rsrc(self):
  135. # """
  136. # The RDFLib resource representing this LDPR. This is a live
  137. # representation of the stored data if present.
  138. # :rtype: rdflib.Resource
  139. # """
  140. # if not hasattr(self, '_rsrc'):
  141. # self._rsrc = rdfly.ds.resource(self.uri)
  142. # return self._rsrc
  143. @property
  144. def imr(self):
  145. """
  146. In-Memory Resource.
  147. This is a copy of the resource extracted from the graph store. It is a
  148. graph resource whose identifier is the URI of the resource.
  149. >>> rsrc = rsrc_api.get('/')
  150. >>> rsrc.imr.identifier
  151. rdflib.term.URIRef('info:fcres/')
  152. >>> rsrc.imr.value(nsc['fcrepo'].lastModified)
  153. rdflib.term.Literal(
  154. '2018-04-03T05:20:33.774746+00:00',
  155. datatype=rdflib.term.URIRef(
  156. 'http://www.w3.org/2001/XMLSchema#dateTime'))
  157. The IMR can be read and manipulated, as well as used to
  158. update the stored resource.
  159. :rtype: rdflib.Graph
  160. :raise lakesuperior.exceptions.ResourceNotExistsError: If the resource
  161. is not stored (yet).
  162. """
  163. if not hasattr(self, '_imr'):
  164. if hasattr(self, '_imr_options'):
  165. logger.debug(
  166. 'Getting RDF triples for resource {}'.format(self.uid))
  167. imr_options = self._imr_options
  168. else:
  169. imr_options = {}
  170. options = dict(imr_options, strict=True)
  171. self._imr = rdfly.get_imr(self.uid, **options)
  172. return self._imr
  173. @imr.setter
  174. def imr(self, data):
  175. """
  176. Replace in-memory buffered resource.
  177. :param v: New set of triples to populate the IMR with.
  178. :type v: set or rdflib.Graph
  179. """
  180. self._imr = Imr(self.uri, data=set(data))
  181. @imr.deleter
  182. def imr(self):
  183. """
  184. Delete in-memory buffered resource.
  185. """
  186. delattr(self, '_imr')
  187. @property
  188. def metadata(self):
  189. """
  190. Get resource metadata.
  191. """
  192. if not hasattr(self, '_metadata'):
  193. if hasattr(self, '_imr'):
  194. logger.info('Metadata is IMR.')
  195. self._metadata = self._imr
  196. else:
  197. logger.info(
  198. 'Getting metadata for resource {}'.format(self.uid))
  199. self._metadata = rdfly.get_metadata(self.uid)
  200. return self._metadata
  201. @metadata.setter
  202. def metadata(self, rsrc):
  203. """
  204. Set resource metadata.
  205. """
  206. if not isinstance(rsrc, Imr):
  207. raise TypeError('Provided metadata is not an Imr object.')
  208. self._metadata = rsrc
  209. @property
  210. def out_graph(self):
  211. """
  212. Retun a graph of the resource's IMR formatted for output.
  213. """
  214. out_gr = Graph(identifier=self.uri)
  215. for t in self.imr:
  216. if (
  217. # Exclude digest hash and version information.
  218. t[1] not in {
  219. #nsc['premis'].hasMessageDigest,
  220. nsc['fcrepo'].hasVersion,
  221. }
  222. ) and (
  223. # Only include server managed triples if requested.
  224. self._imr_options.get('incl_srv_mgd', True) or
  225. not self._is_trp_managed(t)
  226. ):
  227. out_gr.add(t)
  228. return out_gr
  229. @property
  230. def version_info(self):
  231. """
  232. Return version metadata (`fcr:versions`).
  233. """
  234. if not hasattr(self, '_version_info'):
  235. try:
  236. self._version_info = rdfly.get_version_info(self.uid)
  237. except ResourceNotExistsError as e:
  238. self._version_info = Imr(uri=self.uri)
  239. return self._version_info
  240. @property
  241. def version_uids(self):
  242. """
  243. Return a set of version UIDs relative to their parent resource.
  244. """
  245. uids = set()
  246. for vuri in self.version_info[nsc['fcrepo'].hasVersion]:
  247. for vlabel in self.version_info[
  248. vuri : nsc['fcrepo'].hasVersionLabel]:
  249. uids.add(str(vlabel))
  250. return uids
  251. @property
  252. def is_stored(self):
  253. if not hasattr(self, '_is_stored'):
  254. if hasattr(self, '_imr'):
  255. self._is_stored = len(self.imr) > 0
  256. else:
  257. self._is_stored = rdfly.ask_rsrc_exists(self.uid)
  258. return self._is_stored
  259. @property
  260. def types(self):
  261. """All RDF types.
  262. :rtype: set(rdflib.term.URIRef)
  263. """
  264. if not hasattr(self, '_types'):
  265. if len(self.metadata):
  266. metadata = self.metadata
  267. elif getattr(self, 'provided_imr', None) and \
  268. len(self.provided_imr):
  269. metadata = self.provided_imr
  270. else:
  271. return set()
  272. self._types = set(metadata[self.uri: RDF.type])
  273. return self._types
  274. @property
  275. def ldp_types(self):
  276. """The LDP types.
  277. :rtype: set(rdflib.term.URIRef)
  278. """
  279. if not hasattr(self, '_ldp_types'):
  280. self._ldp_types = {t for t in self.types if nsc['ldp'] in t}
  281. return self._ldp_types
  282. ## LDP METHODS ##
  283. def head(self):
  284. """
  285. Return values for the headers.
  286. """
  287. out_headers = defaultdict(list)
  288. digest = self.metadata.value(nsc['premis'].hasMessageDigest)
  289. if digest:
  290. etag = digest.identifier.split(':')[-1]
  291. out_headers['ETag'] = 'W/"{}"'.format(etag),
  292. last_updated_term = self.metadata.value(nsc['fcrepo'].lastModified)
  293. if last_updated_term:
  294. out_headers['Last-Modified'] = arrow.get(last_updated_term)\
  295. .format('ddd, D MMM YYYY HH:mm:ss Z')
  296. for t in self.ldp_types:
  297. out_headers['Link'].append(
  298. '{};rel="type"'.format(t.n3()))
  299. return out_headers
  300. def get_version(self, ver_uid, **kwargs):
  301. """
  302. Get a version by label.
  303. """
  304. return rdfly.get_imr(self.uid, ver_uid, **kwargs)
  305. def create_or_replace(self, create_only=False):
  306. """
  307. Create or update a resource. PUT and POST methods, which are almost
  308. identical, are wrappers for this method.
  309. :param boolean create_only: Whether this is a create-only operation.
  310. """
  311. create = create_only or not self.is_stored
  312. ev_type = RES_CREATED if create else RES_UPDATED
  313. self._add_srv_mgd_triples(create)
  314. ref_int = rdfly.config['referential_integrity']
  315. if ref_int:
  316. self._check_ref_int(ref_int)
  317. # Delete existing triples if replacing.
  318. if not create:
  319. rdfly.truncate_rsrc(self.uid)
  320. remove_trp = {
  321. (self.uri, pred, None) for pred in self.delete_preds_on_replace}
  322. add_trp = set(
  323. self.provided_imr | self._containment_rel(create))
  324. self.modify(ev_type, remove_trp, add_trp)
  325. self.imr = add_trp
  326. return ev_type
  327. def bury(self, inbound, tstone_pointer=None):
  328. """
  329. Delete a single resource and create a tombstone.
  330. :param bool inbound: Whether inbound relationships are
  331. removed. If ``False``, resources will keep referring
  332. to the deleted resource; their link will point to a tombstone
  333. (which will raise a ``TombstoneError`` in the Python API or a
  334. ``410 Gone`` in the LDP API).
  335. :param rdflib.URIRef tstone_pointer: If set to a URI, this creates a
  336. pointer to the tombstone of the resource that used to contain the
  337. deleted resource. Otherwise the deleted resource becomes a
  338. tombstone.
  339. """
  340. logger.info('Burying resource {}'.format(self.uid))
  341. # ldp:Resource is also used in rdfly.ask_rsrc_exists.
  342. remove_trp = {
  343. (nsc['fcrepo'].uid, nsc['rdf'].type, nsc['ldp'].Resource)
  344. }
  345. if tstone_pointer:
  346. add_trp = {
  347. (self.uri, nsc['fcsystem'].tombstone, tstone_pointer)}
  348. else:
  349. add_trp = {
  350. (self.uri, RDF.type, nsc['fcsystem'].Tombstone),
  351. (self.uri, nsc['fcsystem'].buried, thread_env.timestamp_term),
  352. }
  353. # Bury descendants.
  354. from lakesuperior.model.ldp_factory import LdpFactory
  355. for desc_uri in rdfly.get_descendants(self.uid):
  356. try:
  357. desc_rsrc = LdpFactory.from_stored(
  358. env.app_globals.rdfly.uri_to_uid(desc_uri),
  359. repr_opts={'incl_children' : False})
  360. except (TombstoneError, ResourceNotExistsError):
  361. continue
  362. desc_rsrc.bury(inbound, tstone_pointer=self.uri)
  363. # Cut inbound relationships
  364. if inbound:
  365. for ib_rsrc_uri in self.imr[ : : self.uri]:
  366. remove_trp = {(ib_rsrc_uri, None, self.uri)}
  367. ib_rsrc = Ldpr(ib_rsrc_uri)
  368. # To preserve inbound links in history, create a snapshot
  369. ib_rsrc.create_version()
  370. ib_rsrc.modify(RES_UPDATED, remove_trp)
  371. self.modify(RES_DELETED, remove_trp, add_trp)
  372. return RES_DELETED
  373. def forget(self, inbound=True):
  374. """
  375. Remove all traces of a resource and versions.
  376. """
  377. logger.info('Forgetting resource {}'.format(self.uid))
  378. rdfly.forget_rsrc(self.uid, inbound)
  379. return RES_DELETED
  380. def resurrect(self):
  381. """
  382. Resurrect a resource from a tombstone.
  383. """
  384. remove_trp = {
  385. (self.uri, nsc['rdf'].type, nsc['fcsystem'].Tombstone),
  386. (self.uri, nsc['fcsystem'].tombstone, None),
  387. (self.uri, nsc['fcsystem'].buried, None),
  388. }
  389. add_trp = {
  390. (self.uri, nsc['rdf'].type, nsc['ldp'].Resource),
  391. }
  392. self.modify(RES_CREATED, remove_trp, add_trp)
  393. # Resurrect descendants.
  394. from lakesuperior.model.ldp_factory import LdpFactory
  395. descendants = env.app_globals.rdfly.get_descendants(self.uid)
  396. for desc_uri in descendants:
  397. LdpFactory.from_stored(
  398. rdfly.uri_to_uid(desc_uri), strict=False).resurrect()
  399. return self.uri
  400. def create_version(self, ver_uid=None):
  401. """
  402. Create a new version of the resource.
  403. **Note:** This creates an event only for the resource being updated
  404. (due to the added `hasVersion` triple and possibly to the
  405. ``hasVersions`` one) but not for the version being created.
  406. :param str ver_uid: Version UID. If already existing, a new version UID
  407. is minted.
  408. """
  409. if not ver_uid or ver_uid in self.version_uids:
  410. ver_uid = str(uuid4())
  411. # Create version resource from copying the current state.
  412. logger.info(
  413. 'Creating version snapshot {} for resource {}.'.format(
  414. ver_uid, self.uid))
  415. ver_add_gr = set()
  416. vers_uid = '{}/{}'.format(self.uid, VERS_CONT_LABEL)
  417. ver_uid = '{}/{}'.format(vers_uid, ver_uid)
  418. ver_uri = nsc['fcres'][ver_uid]
  419. ver_add_gr.add((ver_uri, RDF.type, nsc['fcrepo'].Version))
  420. for t in self.imr:
  421. if (
  422. t[1] == RDF.type and t[2] in self._ignore_version_types
  423. ) or t[1] in self._ignore_version_preds:
  424. pass
  425. else:
  426. ver_add_gr.add((
  427. self.tbox.replace_term_domain(t[0], self.uri, ver_uri),
  428. t[1], t[2]))
  429. rdfly.modify_rsrc(ver_uid, add_trp=ver_add_gr)
  430. # Update resource admin data.
  431. rsrc_add_gr = {
  432. (self.uri, nsc['fcrepo'].hasVersion, ver_uri),
  433. (self.uri, nsc['fcrepo'].hasVersions, nsc['fcres'][vers_uid]),
  434. }
  435. self.modify(RES_UPDATED, add_trp=rsrc_add_gr)
  436. return ver_uid
  437. def revert_to_version(self, ver_uid, backup=True):
  438. """
  439. Revert to a previous version.
  440. :param str ver_uid: Version UID.
  441. :param boolean backup: Whether to create a backup snapshot. Default is
  442. True.
  443. """
  444. # Create a backup snapshot.
  445. if backup:
  446. self.create_version()
  447. ver_gr = rdfly.get_imr(
  448. self.uid, ver_uid=ver_uid, incl_children=False)
  449. self.provided_imr = Imr(uri=self.uri)
  450. for t in ver_gr:
  451. if not self._is_trp_managed(t):
  452. self.provided_imr.add((self.uri, t[1], t[2]))
  453. # @TODO Check individual objects: if they are repo-managed URIs
  454. # and not existing or tombstones, they are not added.
  455. return self.create_or_replace(create_only=False)
  456. def check_mgd_terms(self, gr):
  457. """
  458. Check whether server-managed terms are in a RDF payload.
  459. :param SimpleGraph gr: The graph to validate.
  460. """
  461. offending_subjects = gr.terms('s') & srv_mgd_subjects
  462. if offending_subjects:
  463. if self.handling == 'strict':
  464. raise ServerManagedTermError(offending_subjects, 's')
  465. else:
  466. gr_set = set(gr)
  467. for s in offending_subjects:
  468. logger.info('Removing offending subj: {}'.format(s))
  469. for t in gr_set:
  470. if t[0] == s:
  471. gr.remove(t)
  472. offending_predicates = gr.terms('p') & srv_mgd_predicates
  473. # Allow some predicates if the resource is being created.
  474. if offending_predicates:
  475. if self.handling == 'strict':
  476. raise ServerManagedTermError(offending_predicates, 'p')
  477. else:
  478. gr_set = set(gr)
  479. for p in offending_predicates:
  480. logger.info('Removing offending pred: {}'.format(p))
  481. for t in gr_set:
  482. if t[1] == p:
  483. gr.remove(t)
  484. types = {t[2] for t in gr if t[1] == RDF.type}
  485. offending_types = types & srv_mgd_types
  486. if not self.is_stored:
  487. offending_types -= self.smt_allow_on_create
  488. if offending_types:
  489. if self.handling == 'strict':
  490. raise ServerManagedTermError(offending_types, 't')
  491. else:
  492. for to in offending_types:
  493. logger.info('Removing offending type: {}'.format(to))
  494. gr.remove_triples((None, RDF.type, to))
  495. #logger.debug('Sanitized graph: {}'.format(gr.serialize(
  496. # format='turtle').decode('utf-8')))
  497. return gr
  498. def sparql_delta(self, qry_str):
  499. """
  500. Calculate the delta obtained by a SPARQL Update operation.
  501. This is a critical component of the SPARQL update prcess and does a
  502. couple of things:
  503. 1. It ensures that no resources outside of the subject of the request
  504. are modified (e.g. by variable subjects)
  505. 2. It verifies that none of the terms being modified is server managed.
  506. This method extracts an in-memory copy of the resource and performs the
  507. query on that once it has checked if any of the server managed terms is
  508. in the delta. If it is, it raises an exception.
  509. NOTE: This only checks if a server-managed term is effectively being
  510. modified. If a server-managed term is present in the query but does not
  511. cause any change in the updated resource, no error is raised.
  512. :rtype: tuple(rdflib.Graph)
  513. :return: Remove and add graphs. These can be used
  514. with ``BaseStoreLayout.update_resource`` and/or recorded as separate
  515. events in a provenance tracking system.
  516. """
  517. logger.debug('Provided SPARQL query: {}'.format(qry_str))
  518. # Workaround for RDFLib bug. See
  519. # https://github.com/RDFLib/rdflib/issues/824
  520. qry_str = (
  521. re.sub('<#([^>]+)>', '<{}#\\1>'.format(self.uri), qry_str)
  522. .replace('<>', '<{}>'.format(self.uri)))
  523. pre_gr = self.imr.graph
  524. post_rdfgr = Graph(identifier=self.uri)
  525. post_rdfgr += pre_gr
  526. post_rdfgr.update(qry_str)
  527. post_gr = SimpleGraph(data=set(post_rdfgr))
  528. # FIXME Fix and use SimpleGraph's native subtraction operation.
  529. remove_gr = self.check_mgd_terms(SimpleGraph(pre_gr.data - post_gr.data))
  530. add_gr = self.check_mgd_terms(SimpleGraph(post_gr.data - pre_gr.data))
  531. return remove_gr, add_gr
  532. ## PROTECTED METHODS ##
  533. def _is_trp_managed(self, t):
  534. """
  535. Whether a triple is server-managed.
  536. :param tuple t: Triple as a 3-tuple of terms.
  537. :rtype: boolean
  538. """
  539. return t[1] in srv_mgd_predicates or (
  540. t[1] == RDF.type and t[2] in srv_mgd_types)
  541. def modify(
  542. self, ev_type, remove_trp=set(), add_trp=set()):
  543. """
  544. Low-level method to modify a graph for a single resource.
  545. This is a crucial point for messaging. Any write operation on the RDF
  546. store that needs to be notified should be performed by invoking this
  547. method.
  548. :param ev_type: The type of event (create, update,
  549. delete) or None. In the latter case, no notification is sent.
  550. :type ev_type: str or None
  551. :param set remove_trp: Triples to be removed.
  552. # Add metadata.
  553. :param set add_trp: Triples to be added.
  554. """
  555. rdfly.modify_rsrc(self.uid, remove_trp, add_trp)
  556. # Reset IMR buffer.
  557. if hasattr(self, '_imr'):
  558. delattr(self, '_imr')
  559. try:
  560. self.imr
  561. except (ResourceNotExistsError, TombstoneError):
  562. pass
  563. if (
  564. ev_type is not None and
  565. env.app_globals.config['application'].get('messaging')):
  566. logger.debug('Enqueuing message for {}'.format(self.uid))
  567. self._enqueue_msg(ev_type, remove_trp, add_trp)
  568. def _enqueue_msg(self, ev_type, remove_trp=None, add_trp=None):
  569. """
  570. Compose a message about a resource change.
  571. The message is enqueued for asynchronous processing.
  572. :param str ev_type: The event type. See global constants.
  573. :param set remove_trp: Triples removed. Only used if the
  574. """
  575. try:
  576. rsrc_type = tuple(str(t) for t in self.types)
  577. actor = self.metadata.value(nsc['fcrepo'].createdBy)
  578. except (ResourceNotExistsError, TombstoneError):
  579. rsrc_type = ()
  580. actor = None
  581. for t in add_trp:
  582. if t[1] == RDF.type:
  583. rsrc_type.add(t[2])
  584. elif actor is None and t[1] == nsc['fcrepo'].createdBy:
  585. actor = t[2]
  586. env.app_globals.changelog.append((set(remove_trp), set(add_trp), {
  587. 'ev_type': ev_type,
  588. 'timestamp': thread_env.timestamp.format(),
  589. 'rsrc_type': rsrc_type,
  590. 'actor': actor,
  591. }))
  592. def _check_ref_int(self, config):
  593. """
  594. Check referential integrity of a resource.
  595. :param str config: If set to ``strict``, a
  596. :class:`lakesuperior.exceptions.RefIntViolationError` is raised.
  597. Otherwise, the violation is simply logged.
  598. """
  599. remove_set = set()
  600. for trp in self.provided_imr:
  601. o = trp[2]
  602. if(
  603. isinstance(o, URIRef) and
  604. str(o).startswith(nsc['fcres']) and
  605. urldefrag(o).url.rstrip('/') != str(self.uri)):
  606. obj_uid = rdfly.uri_to_uid(o)
  607. if not rdfly.ask_rsrc_exists(obj_uid):
  608. if config == 'strict':
  609. raise RefIntViolationError(obj_uid)
  610. else:
  611. # Gather invalid object to sanitize.
  612. remove_set.add(o)
  613. # Remove invalid triples.
  614. for obj in remove_set:
  615. logger.info(
  616. 'Removing link to non-existent repo resource: {}'
  617. .format(obj))
  618. self.provided_imr.remove_triples((None, None, obj))
  619. def _add_srv_mgd_triples(self, create=False):
  620. """
  621. Add server-managed triples to a provided IMR.
  622. :param create: Whether the resource is being created.
  623. """
  624. # Base LDP types.
  625. for t in self.base_types:
  626. self.provided_imr.add((self.uri, RDF.type, t))
  627. # Create and modify timestamp.
  628. if create:
  629. self.provided_imr.set((
  630. self.uri, nsc['fcrepo'].created, thread_env.timestamp_term))
  631. self.provided_imr.set((
  632. self.uri, nsc['fcrepo'].createdBy, self.DEFAULT_USER))
  633. else:
  634. self.provided_imr.set((
  635. self.uri, nsc['fcrepo'].created,
  636. self.metadata.value(nsc['fcrepo'].created)))
  637. self.provided_imr.set((
  638. self.uri, nsc['fcrepo'].createdBy,
  639. self.metadata.value(nsc['fcrepo'].createdBy)))
  640. self.provided_imr.set((
  641. self.uri, nsc['fcrepo'].lastModified, thread_env.timestamp_term))
  642. self.provided_imr.set((
  643. self.uri, nsc['fcrepo'].lastModifiedBy, self.DEFAULT_USER))
  644. def _containment_rel(self, create, ignore_type=True):
  645. """Find the closest parent in the path indicated by the uid and
  646. establish a containment triple.
  647. Check the path-wise parent of the new resource. If it exists, add the
  648. containment relationship with this UID. Otherwise, create a container
  649. resource as the parent.
  650. This function may recurse up the path tree until an existing container
  651. is found.
  652. E.g. if only fcres:/a exists:
  653. - If ``fcres:/a/b/c/d`` is being created, a becomes container of
  654. ``fcres:/a/b/c/d``. Also, containers are created for fcres:a/b and
  655. ``fcres:/a/b/c``.
  656. - If ``fcres:/e`` is being created, the root node becomes container of
  657. ``fcres:/e``.
  658. :param bool create: Whether the resource is being created. If false,
  659. the parent container is not updated.
  660. "param bool ignore_type: If False (the default), an exception is raised
  661. if trying to create a resource under a non-container. This can be
  662. overridden in special cases (e.g. when migrating a repository in which
  663. a LDP-NR has "children" under ``fcr:versions``) by setting this to
  664. True.
  665. """
  666. from lakesuperior.model.ldp_factory import LdpFactory
  667. if '/' in self.uid.lstrip('/'):
  668. # Traverse up the hierarchy to find the parent.
  669. path_components = self.uid.lstrip('/').split('/')
  670. cnd_parent_uid = '/' + '/'.join(path_components[:-1])
  671. if rdfly.ask_rsrc_exists(cnd_parent_uid):
  672. parent_rsrc = LdpFactory.from_stored(cnd_parent_uid)
  673. if (
  674. not ignore_type
  675. and nsc['ldp'].Container not in parent_rsrc.types):
  676. raise InvalidResourceError(
  677. cnd_parent_uid, 'Parent {} is not a container.')
  678. parent_uid = cnd_parent_uid
  679. else:
  680. parent_rsrc = LdpFactory.new_container(cnd_parent_uid)
  681. # This will trigger this method again and recurse until an
  682. # existing container or the root node is reached.
  683. parent_rsrc.create_or_replace()
  684. parent_uid = parent_rsrc.uid
  685. else:
  686. parent_uid = ROOT_UID
  687. parent_rsrc = LdpFactory.from_stored(
  688. parent_uid, repr_opts={'incl_children': False}, handling='none')
  689. # Only update parent if the resource is new.
  690. if create:
  691. add_gr = Graph()
  692. add_gr.add(
  693. (nsc['fcres'][parent_uid], nsc['ldp'].contains, self.uri))
  694. parent_rsrc.modify(RES_UPDATED, add_trp=add_gr)
  695. # Direct or indirect container relationship.
  696. return self._add_ldp_dc_ic_rel(parent_rsrc)
  697. def _add_ldp_dc_ic_rel(self, cont_rsrc):
  698. """
  699. Add relationship triples from a parent direct or indirect container.
  700. :param rdflib.resource.Resouce cont_rsrc: The container resource.
  701. """
  702. cont_p = cont_rsrc.metadata.terms('p')
  703. logger.info('Checking direct or indirect containment.')
  704. logger.debug('Parent predicates: {}'.format(cont_p))
  705. add_trp = {(self.uri, nsc['fcrepo'].hasParent, cont_rsrc.uri)}
  706. if self.MBR_RSRC_URI in cont_p and self.MBR_REL_URI in cont_p:
  707. from lakesuperior.model.ldp_factory import LdpFactory
  708. s = cont_rsrc.metadata.value(self.MBR_RSRC_URI)
  709. p = cont_rsrc.metadata.value(self.MBR_REL_URI)
  710. if nsc['ldp'].DirectContainer in cont_rsrc.ldp_types:
  711. logger.info('Parent is a direct container.')
  712. logger.debug('Creating DC triples.')
  713. o = self.uri
  714. elif nsc['ldp'].IndirectContainer in cont_rsrc.ldp_types:
  715. logger.info('Parent is an indirect container.')
  716. cont_rel_uri = cont_rsrc.metadata.value(self.INS_CNT_REL_URI)
  717. o = self.provided_imr.value(cont_rel_uri)
  718. logger.debug('Target URI: {}'.format(o))
  719. logger.debug('Creating IC triples.')
  720. target_rsrc = LdpFactory.from_stored(rdfly.uri_to_uid(s))
  721. target_rsrc.modify(RES_UPDATED, add_trp={(s, p, o)})
  722. return add_trp