template_objects.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. from collections.abc import Mapping
  2. from copy import deepcopy
  3. from datetime import date, datetime, time, timedelta
  4. from decimal import Decimal
  5. from importlib import import_module
  6. from types import SimpleNamespace
  7. from django.apps import apps
  8. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  9. from django.contrib.contenttypes.models import ContentType
  10. from django.core.exceptions import FieldDoesNotExist
  11. from django.db import models
  12. from django.db.models import prefetch_related_objects
  13. from django.utils.datastructures import MultiValueDict
  14. from jinja2.exceptions import TemplateRuntimeError
  15. from netaddr import IPAddress, IPNetwork
  16. from rest_framework.fields import SkipField
  17. from rest_framework.relations import PKOnlyObject
  18. from rest_framework.serializers import Serializer
  19. from netbox.api.exceptions import SerializerNotFound
  20. from netbox.api.fields import RelatedObjectsField
  21. from netbox.api.filters import OrderingFilter
  22. from netbox.api.gfk_fields import GFKSerializerField
  23. from netbox.models.features import model_is_public
  24. from netbox.registry import registry
  25. from utilities.api import (
  26. _get_base_queryset,
  27. _get_declared_prefetches,
  28. _get_nested_serializer,
  29. get_annotations_for_serializer,
  30. get_fields_for_serializer,
  31. get_prefetches_for_serializer,
  32. get_serializer_for_model,
  33. )
  34. from utilities.json import render_native_values
  35. __all__ = (
  36. 'NATIVE_VALUE_TYPES',
  37. 'TemplateObject',
  38. 'TemplateObjectList',
  39. 'get_query_function',
  40. 'get_template_context_data',
  41. 'get_template_object',
  42. 'get_template_objects',
  43. 'template_json_default',
  44. 'to_template_data',
  45. )
  46. # Native values which templates receive as they are (e.g. an IPAddress' address), matched by exact type
  47. NATIVE_VALUE_TYPES = (IPAddress, IPNetwork, date, datetime, time, timedelta)
  48. # Values which to_template_data() passes through unchanged, matched by exact type
  49. _PLAIN_VALUE_TYPES = (str, int, float, Decimal, bool, *NATIVE_VALUE_TYPES)
  50. # The number of objects a TemplateObjectList loads at a time
  51. TEMPLATE_OBJECTS_CHUNK_SIZE = 1000
  52. # The related objects represented by each model's serializer (see _get_relations()), keyed by model
  53. _relations = {}
  54. # Marks a field holding generic object references ({object_type, object_id, object}), e.g. cable terminations
  55. _GENERIC_OBJECTS = object()
  56. # Marks a field for which an object has no value (e.g. an object the rendering user may not view)
  57. _MISSING = object()
  58. def get_template_object(instance, state):
  59. """
  60. Return a TemplateObject representing the given instance. The caller is responsible for ensuring that the rendering
  61. user is permitted to view it.
  62. """
  63. _check_state(state)
  64. model = type(instance)
  65. if _get_serializer_class(model) is None:
  66. raise ValueError(f"{model._meta.label} has no REST API serializer.")
  67. batch = _Batch(model, [instance.pk], state, state.cache, instance=instance)
  68. state.cache[(model, instance.pk)] = batch
  69. return TemplateObject({'id': instance.pk}, model, state, batch=batch)
  70. def get_template_objects(queryset, state):
  71. """
  72. Return a lazy TemplateObjectList representing the objects in the given queryset which the rendering user is
  73. permitted to view. A sliced queryset is represented by the same slice of those objects.
  74. """
  75. _check_state(state)
  76. if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
  77. raise ValueError(f"{queryset.model._meta.label} does not support restricted rendering.")
  78. if queryset.query.is_sliced:
  79. # A sliced queryset (e.g. interfaces[:5]) can't be restricted, so take the same slice of the permitted objects
  80. start, stop = queryset.query.low_mark, queryset.query.high_mark
  81. queryset = queryset.all()
  82. queryset.query.clear_limits()
  83. return TemplateObjectList(queryset, state)[start:stop]
  84. return TemplateObjectList(queryset, state)
  85. def get_query_function(state):
  86. """
  87. Return the query() function for restricted rendering, which returns the objects of a model matching the given REST
  88. API filters, limited to those the rendering user is permitted to view.
  89. """
  90. _check_state(state)
  91. def query(model, /, ordering=None, limit=None, **filters):
  92. return _query(state, model, ordering, limit, filters)
  93. return query
  94. def get_template_context_data(value):
  95. """
  96. Return a copy of a restricted rendering context for display, with each TemplateObject replaced by its full
  97. representation and each TemplateObjectList by its description.
  98. """
  99. if isinstance(value, TemplateObject):
  100. return deepcopy(value._get_full_data())
  101. if isinstance(value, TemplateObjectList):
  102. return repr(value)
  103. if isinstance(value, dict):
  104. return {key: get_template_context_data(item) for key, item in value.items()}
  105. if isinstance(value, list):
  106. return [get_template_context_data(item) for item in value]
  107. return value
  108. def template_json_default(obj):
  109. """
  110. JSON encoder hook for restricted rendering: TemplateObjects serialize to their full representation.
  111. """
  112. if isinstance(obj, TemplateObject):
  113. return obj._get_full_data()
  114. if isinstance(obj, TemplateObjectList):
  115. return [item._get_full_data() for item in obj]
  116. if isinstance(obj, Decimal):
  117. return float(obj)
  118. if type(obj) is timedelta:
  119. # As REST framework's JSON encoder renders it
  120. return str(obj.total_seconds())
  121. if type(obj) in NATIVE_VALUE_TYPES:
  122. # Rendered as in REST API responses
  123. return render_native_values(obj)
  124. raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
  125. class TemplateObject(Mapping):
  126. """
  127. A read-only representation of a NetBox object for restricted template rendering. Behaves as a dict holding the
  128. object's REST API representation. Fields are loaded on demand, as are related objects not fully represented,
  129. limited to those the rendering user is permitted to view.
  130. """
  131. def __init__(self, data, model, state, batch=None, batches=None):
  132. # The fields known without loading the object (e.g. its brief representation as a related object)
  133. self._data = data
  134. self._model = model
  135. self._state = state
  136. self._batch = batch
  137. self._batches = batches
  138. self._wrapped = {}
  139. def __getitem__(self, key):
  140. if key in self._wrapped:
  141. return self._wrapped[key]
  142. if key in self._data:
  143. value = self._data[key]
  144. else:
  145. value = self._load(key)
  146. if isinstance(value, TemplateObjectList):
  147. self._wrapped[key] = value
  148. return value
  149. if key not in _get_relations(self._model) and isinstance(value, (dict, list)):
  150. # Return a copy, so that a template can't alter the retained representation
  151. return deepcopy(value)
  152. self._wrapped[key] = self._wrap(key, value)
  153. return self._wrapped[key]
  154. def __iter__(self):
  155. return iter(self._get_full_data())
  156. def __len__(self):
  157. return len(self._get_full_data())
  158. def __bool__(self):
  159. # Always represents an object, so avoid loading it (via __len__) just to test truthiness
  160. return True
  161. def __eq__(self, other):
  162. if isinstance(other, TemplateObject):
  163. return (self._model, self._data.get('id')) == (other._model, other._data.get('id'))
  164. return NotImplemented
  165. def __hash__(self):
  166. return hash((self._model, self._data.get('id')))
  167. def __str__(self):
  168. return str(self.get('display', ''))
  169. def __repr__(self):
  170. # Avoid loading the object (e.g. while formatting an error message)
  171. label = self._model._meta.label if self._model is not None else None
  172. return f'<TemplateObject {label} id={self._data.get("id")!r}>'
  173. def _get_batch(self):
  174. if self._batch is None and self._model is not None and (pk := self._data.get('id')) is not None:
  175. self._batch = _get_batch(self._model, pk, self._state, self._batches)
  176. return self._batch
  177. def _get_full_data(self):
  178. """
  179. Return the object's full representation, or the fields it was created with if the rendering user isn't
  180. permitted to view it.
  181. """
  182. if (batch := self._get_batch()) is not None and (data := batch.get_row(self._data['id'])) is not None:
  183. return data
  184. return self._data
  185. def _load(self, key):
  186. """
  187. Return a field the object wasn't created with (loaded for every object in its batch), or the list of objects
  188. related through an optional reverse relation (e.g. a device's interfaces).
  189. """
  190. if (batch := self._get_batch()) is None:
  191. raise KeyError(key)
  192. pk = self._data['id']
  193. if (value := batch.get(pk, key)) is _MISSING:
  194. if pk is None or (value := batch.get_related(pk, key)) is None:
  195. raise KeyError(key)
  196. return value
  197. def _wrap(self, key, value):
  198. relation = _get_relations(self._model).get(key)
  199. if relation is None or value is None:
  200. return deepcopy(value)
  201. if relation is _GENERIC_OBJECTS:
  202. if isinstance(value, list):
  203. return [self._wrap_generic_object(item) for item in value]
  204. return deepcopy(value)
  205. if isinstance(relation, str):
  206. # A generic foreign key: the related model is given by its content type field
  207. model = _get_model(self.get(relation))
  208. else:
  209. model = relation
  210. if model is not None and isinstance(value, list):
  211. return [self._wrap_object(item, model) for item in value]
  212. if model is not None and isinstance(value, dict):
  213. return self._wrap_object(value, model)
  214. return deepcopy(value)
  215. def _wrap_generic_object(self, item):
  216. if not isinstance(item, dict) or not isinstance(item.get('object'), dict):
  217. return deepcopy(item)
  218. if (model := _get_model(item.get('object_type'))) is None:
  219. return deepcopy(item)
  220. return {**deepcopy(item), 'object': self._wrap_object(item['object'], model)}
  221. def _wrap_object(self, data, model):
  222. # A related object is retained for as long as this one
  223. batches = self._batches if self._batch is None else self._batch.batches
  224. return TemplateObject(data, model, self._state, batches=batches)
  225. class TemplateObjectList:
  226. """
  227. A lazy, read-only list of TemplateObjects, limited to the objects the rendering user is permitted to view. Objects
  228. are loaded in chunks as the list is iterated, so a long list is never held in memory as a whole.
  229. """
  230. def __init__(self, queryset, state, limit=None, max_results=None, pks=None, batches=None):
  231. # Given the keys of its objects, the list never evaluates the queryset
  232. if pks is None:
  233. queryset = queryset.restrict(state.user, 'view')
  234. # Order an unordered queryset, so that the objects returned are deterministic
  235. queryset = queryset if queryset.ordered else queryset.order_by('pk')
  236. self._queryset = queryset
  237. self._state = state
  238. self._limit = limit
  239. self._max_results = max_results
  240. self._pks = pks
  241. self._batches = batches
  242. # The loaded objects, retained only for a list which fits in one chunk
  243. self._items = None
  244. self._first = None
  245. def __iter__(self):
  246. if self._items is not None:
  247. return iter(self._items)
  248. return self._iter_objects()
  249. def __reversed__(self):
  250. if self._items is not None:
  251. return reversed(self._items)
  252. return self._iter_objects(reverse=True)
  253. def __len__(self):
  254. if self._items is not None:
  255. return len(self._items)
  256. if self._pks is not None:
  257. return len(self._pks)
  258. count = self._queryset.count()
  259. return min(count, self._limit) if self._limit is not None else count
  260. def __bool__(self):
  261. if self._items is not None:
  262. return bool(self._items)
  263. if self._pks is not None:
  264. return bool(self._pks)
  265. return self._queryset.exists()
  266. def __getitem__(self, index):
  267. if self._items is not None:
  268. if isinstance(index, slice):
  269. items = self._items[index]
  270. sliced = self._slice([item['id'] for item in items])
  271. sliced._items = items
  272. return sliced
  273. return self._items[index]
  274. if not isinstance(index, (int, slice)):
  275. raise TypeError(f'list indices must be integers or slices, not {type(index).__name__}')
  276. # Read only the keys an index or slice needs (e.g. interfaces[:5]), where it can be determined
  277. if isinstance(index, int):
  278. stop = index + 1 if index >= 0 else None
  279. elif index.step in (None, 1) and (index.start or 0) >= 0 and index.stop is not None and index.stop >= 0:
  280. stop = index.stop
  281. else:
  282. stop = None
  283. if self._max_results is not None and (stop is None or stop > self._max_results):
  284. self._check_max_results()
  285. pks = self._get_pks(stop)
  286. if isinstance(index, slice):
  287. return self._slice(pks[index])
  288. return self._load([pks[index]], cache=True)[0]
  289. def __repr__(self):
  290. return f'<TemplateObjectList {self._queryset.model._meta.label}>'
  291. def all(self):
  292. return self
  293. def count(self):
  294. if self._pks is not None:
  295. return len(self._pks)
  296. if self._items is not None and self._limit is None:
  297. return len(self._items)
  298. return self._queryset.count()
  299. def first(self):
  300. if self._items is not None:
  301. return self._items[0] if self._items else None
  302. if self._first is None:
  303. self._first = self._load(self._get_pks(1), cache=True)
  304. return self._first[0] if self._first else None
  305. def _iter_objects(self, reverse=False):
  306. self._check_max_results()
  307. pks = self._get_pks()
  308. if len(pks) <= TEMPLATE_OBJECTS_CHUNK_SIZE:
  309. self._items = self._load(pks, cache=True)
  310. yield from reversed(self._items) if reverse else self._items
  311. return
  312. # Load a longer list one chunk at a time, without retaining or caching its objects
  313. starts = range(0, len(pks), TEMPLATE_OBJECTS_CHUNK_SIZE)
  314. for start in reversed(starts) if reverse else starts:
  315. items = self._load(pks[start:start + TEMPLATE_OBJECTS_CHUNK_SIZE])
  316. yield from reversed(items) if reverse else items
  317. def _check_max_results(self):
  318. if self._max_results is None or self._limit is not None or self._pks is not None:
  319. return
  320. if self._queryset[:self._max_results + 1].count() > self._max_results:
  321. raise TemplateRuntimeError(
  322. f"query() matched more than {self._max_results} objects. Narrow the filters, or pass a limit."
  323. )
  324. def _get_pks(self, stop=None):
  325. """
  326. Return the primary keys of the objects in the list, in order, up to the given position.
  327. """
  328. if self._pks is not None:
  329. return self._pks[:stop]
  330. stops = [value for value in (stop, self._limit) if value is not None]
  331. queryset = self._queryset.values_list('pk', flat=True)
  332. if stops:
  333. queryset = queryset[:min(stops)]
  334. # Remove any duplicates (e.g. from a distinct queryset ordered by a related field)
  335. return list(dict.fromkeys(queryset))
  336. def _load(self, pks, cache=False):
  337. return _load_objects(self._queryset.model, pks, self._state, cache=cache, batches=self._batches)
  338. def _slice(self, pks):
  339. return TemplateObjectList(self._queryset, self._state, pks=pks, batches=self._batches)
  340. class _Batch:
  341. """
  342. A group of objects of one model which are loaded together. Each field of their REST API representations is
  343. serialized for all of the objects at once, when a template first reads it from any of them.
  344. """
  345. def __init__(self, model, pks, state, batches, instance=None):
  346. self.model = model
  347. self.pks = pks
  348. self.state = state
  349. # Maps (model, pk) to the batch of each object retained for as long as these
  350. self.batches = batches
  351. # An object which the caller has ensured the user may view, used as is if the viewset's queryset omits it
  352. self.instance = instance
  353. self._instances = None
  354. self._columns = {}
  355. self._rows = None
  356. self._related = {}
  357. def get(self, pk, name):
  358. """
  359. Return the value of a field for the object with the given primary key, or _MISSING if it has none.
  360. """
  361. fields = _get_serializer(self.model, self.state)[1]
  362. if self._rows is None and fields is None:
  363. self._load_rows()
  364. if self._rows is not None:
  365. return self._rows[pk].get(name, _MISSING) if pk in self._rows else _MISSING
  366. if name not in fields:
  367. return _MISSING
  368. if name not in self._columns:
  369. self._load_column(name, fields[name])
  370. return self._columns[name].get(pk, _MISSING)
  371. def get_row(self, pk):
  372. """
  373. Return the full representation of the object with the given primary key, or None if the user may not view it.
  374. """
  375. if self._rows is None:
  376. self._load_rows()
  377. return self._rows.get(pk)
  378. def get_related(self, pk, name):
  379. """
  380. Return the list of objects related to an object through an optional reverse relation, or None if the name
  381. isn't one.
  382. """
  383. if name not in self._related:
  384. self._related[name] = self._load_related(name)
  385. if self._related[name] is None:
  386. return None
  387. queryset, pks, pending = self._related[name]
  388. if pk in pending:
  389. # Group the objects of this list with those of the lists which follow, so that they are loaded together
  390. parent_pks, count = [pk], len(pks[pk])
  391. for parent_pk in pending:
  392. if parent_pk != pk:
  393. if (count := count + len(pks[parent_pk])) > TEMPLATE_OBJECTS_CHUNK_SIZE:
  394. break
  395. parent_pks.append(parent_pk)
  396. for parent_pk in parent_pks:
  397. del pending[parent_pk]
  398. related = [related_pk for parent_pk in parent_pks for related_pk in pks[parent_pk]]
  399. _register(queryset.model, related, self.state, self.batches)
  400. return TemplateObjectList(queryset, self.state, pks=pks.get(pk, []), batches=self.batches)
  401. def get_instances(self):
  402. """
  403. Return the objects which the rendering user is permitted to view, by primary key.
  404. """
  405. if self._instances is None:
  406. queryset = self._get_queryset()
  407. if hasattr(queryset, 'annotate_config_context_data'):
  408. # Config context data is loaded only where it's rendered, as by the model's viewset
  409. queryset = queryset.defer('_config_context_data')
  410. self._instances = self._fetch(queryset)
  411. return self._instances
  412. def _get_queryset(self):
  413. # Start from the REST API viewset's queryset, which may annotate fields the serializer renders
  414. queryset = _get_base_queryset(self.model).filter(pk__in=self.pks)
  415. if self.instance is not None:
  416. return queryset
  417. return queryset.restrict(self.state.user, 'view') if hasattr(queryset, 'restrict') else queryset.none()
  418. def _fetch(self, queryset):
  419. instances = {instance.pk: instance for instance in queryset}
  420. if self.instance is not None and not instances:
  421. # Keyed as requested, since deleting an object clears its primary key
  422. instances[self.pks[0]] = self.instance
  423. return instances
  424. def _prepare(self, fields=None):
  425. """
  426. Return the objects by primary key, with the annotations and prefetches which the REST API uses to serialize
  427. the given fields (by default, all of them).
  428. """
  429. serializer_class = _get_serializer_class(self.model)
  430. names = set(get_fields_for_serializer(serializer_class, fields))
  431. base_queryset = _get_base_queryset(self.model)
  432. annotations = get_annotations_for_serializer(serializer_class, fields)
  433. if 'config_context' in names and hasattr(base_queryset, 'get_config_context_data_expression'):
  434. annotations['config_context_data'] = base_queryset.get_config_context_data_expression(
  435. only_invalidated=True
  436. )
  437. prefetches = [
  438. *_get_declared_prefetches(self.model, names),
  439. *get_prefetches_for_serializer(serializer_class, fields),
  440. ]
  441. # Skip any annotations the viewset's queryset already carries
  442. if annotations := {
  443. name: annotation for name, annotation in annotations.items()
  444. if name not in base_queryset.query.annotations
  445. }:
  446. # Annotated fields are serialized from objects of their own
  447. return self._fetch(self._get_queryset().annotate(**annotations).prefetch_related(*prefetches))
  448. instances = self.get_instances()
  449. if prefetches and instances:
  450. prefetch_related_objects(list(instances.values()), *prefetches)
  451. return instances
  452. def _load_column(self, name, field):
  453. column = {}
  454. instances = self._prepare((name,))
  455. _preload_custom_field_objects(field, instances.values())
  456. for pk, instance in instances.items():
  457. if (value := _serialize_field(field, instance)) is not _MISSING:
  458. column[pk] = to_template_data(value)
  459. self._columns[name] = column
  460. # Group the related objects which this field represents, so that they too are loaded together
  461. if (relation := _get_relations(self.model).get(name)) is not None:
  462. found = {}
  463. for pk, value in column.items():
  464. data = {name: value}
  465. if isinstance(relation, str):
  466. data[relation] = self.get(pk, relation)
  467. _find_related_objects(self.model, data, found)
  468. self._register_related(found)
  469. def _load_rows(self):
  470. serializer = _get_serializer(self.model, self.state)[0]
  471. instances = self._prepare()
  472. _preload_custom_field_objects(serializer.fields.get('custom_fields'), instances.values())
  473. self._rows = {
  474. pk: to_template_data(serializer.to_representation(instance))
  475. for pk, instance in instances.items()
  476. }
  477. found = {}
  478. for row in self._rows.values():
  479. _find_related_objects(self.model, row, found)
  480. self._register_related(found)
  481. def _register_related(self, found):
  482. for model, pks in found.items():
  483. _register(model, pks, self.state, self.batches)
  484. def _load_related(self, name):
  485. """
  486. Return the queryset of an optional reverse relation (e.g. a device's interfaces), the primary keys of the
  487. related objects the user may view for each object in the batch, and the objects whose lists are short enough
  488. to be retained but have yet to be read. Return None if the name isn't one.
  489. """
  490. serializer_class = _get_serializer_class(self.model)
  491. field = serializer_class._declared_fields.get(name)
  492. if name not in getattr(serializer_class.Meta, 'optional_fields', ()) or not isinstance(
  493. field, RelatedObjectsField
  494. ):
  495. return None
  496. queryset, parent = _get_related_objects(self.model, self.pks, field.relation)
  497. if _get_serializer_class(queryset.model) is None or not hasattr(queryset, 'restrict'):
  498. return None
  499. queryset = queryset.restrict(self.state.user, 'view')
  500. # Order an unordered queryset, so that the objects returned are deterministic
  501. queryset = queryset if queryset.ordered else queryset.order_by('pk')
  502. pks = {}
  503. for parent_pk, pk in queryset.values_list(parent, 'pk'):
  504. # A dict removes any duplicates (e.g. from a distinct queryset ordered by a related field)
  505. pks.setdefault(parent_pk, {})[pk] = None
  506. pks = {parent_pk: list(related) for parent_pk, related in pks.items()}
  507. pending = dict.fromkeys(
  508. parent_pk for parent_pk in self.pks
  509. if parent_pk in pks and len(pks[parent_pk]) <= TEMPLATE_OBJECTS_CHUNK_SIZE
  510. )
  511. return queryset, pks, pending
  512. #
  513. # Helpers
  514. #
  515. def _check_state(state):
  516. if state.user is None:
  517. raise ValueError("Restricted rendering of NetBox objects requires a user.")
  518. def _get_serializer_class(model):
  519. if model is None:
  520. return None
  521. try:
  522. return get_serializer_for_model(model)
  523. except SerializerNotFound:
  524. return None
  525. def _get_model(label):
  526. if not isinstance(label, str):
  527. return None
  528. try:
  529. return apps.get_model(label)
  530. except (LookupError, ValueError):
  531. return None
  532. def _query(state, label, ordering, limit, filters):
  533. model = _get_model(label.lower()) if isinstance(label, str) else None
  534. if model is None or not model_is_public(model):
  535. raise TemplateRuntimeError(f"query(): {label!r} is not a model which can be queried.")
  536. # FilterSets are registered when their module is imported, which may not have happened yet (e.g. in a worker)
  537. module_name = f'{model._meta.app_config.name}.filtersets'
  538. try:
  539. import_module(module_name)
  540. except ModuleNotFoundError as e:
  541. if e.name != module_name:
  542. raise
  543. filterset_class = registry['filtersets'].get(model._meta.label_lower)
  544. serializer_class = _get_serializer_class(model)
  545. queryset = _get_base_queryset(model).all()
  546. if filterset_class is None or serializer_class is None or not hasattr(queryset, 'restrict'):
  547. raise TemplateRuntimeError(f"query(): {label!r} is not a model which can be queried.")
  548. # Apply the filters
  549. data = MultiValueDict()
  550. no_results = False
  551. for name, value in filters.items():
  552. values = value if isinstance(value, (list, tuple)) else [value]
  553. # An empty list matches nothing (rather than being ignored, which would match everything)
  554. no_results = no_results or not values
  555. data.setlist(name, [_get_filter_value(name, item) for item in values])
  556. # Some filters (e.g. SavedFilter's "usable") depend on the requesting user
  557. filterset = filterset_class(data, queryset, request=SimpleNamespace(user=state.user))
  558. if unknown := [name for name in data if name not in filterset.filters]:
  559. raise TemplateRuntimeError(f"query(): unknown filters for {model._meta.label_lower}: {', '.join(unknown)}")
  560. if not filterset.is_valid():
  561. errors = '; '.join(f'{name}: {" ".join(messages)}' for name, messages in filterset.errors.items())
  562. raise TemplateRuntimeError(f"query(): invalid filters for {model._meta.label_lower}: {errors}")
  563. queryset = filterset.queryset.none() if no_results else filterset.qs
  564. # Apply the ordering, as the REST API does
  565. if ordering is not None:
  566. terms = ordering.split(',') if isinstance(ordering, str) else ordering
  567. terms = [str(term).strip() for term in terms]
  568. view = SimpleNamespace(serializer_class=serializer_class)
  569. ordering_filter = OrderingFilter()
  570. valid_terms = ordering_filter.remove_invalid_fields(queryset, terms, view, None)
  571. if invalid := [term for term in terms if term not in valid_terms]:
  572. raise TemplateRuntimeError(f"query(): invalid ordering for {model._meta.label_lower}: {', '.join(invalid)}")
  573. request = SimpleNamespace(query_params={ordering_filter.ordering_param: ','.join(terms)})
  574. queryset = ordering_filter.filter_queryset(request, queryset, view)
  575. max_results = state.max_results
  576. if limit is None:
  577. return TemplateObjectList(queryset, state, max_results=max_results)
  578. if type(limit) is not int or limit < 1 or (max_results is not None and limit > max_results):
  579. maximum = f' no greater than {max_results}' if max_results is not None else ''
  580. raise TemplateRuntimeError(f"query(): limit must be a positive integer{maximum}.")
  581. return TemplateObjectList(queryset, state, limit=limit)
  582. def _get_filter_value(name, value):
  583. """
  584. Return a filter value as it would appear in a REST API query string.
  585. """
  586. if value is None:
  587. return 'null'
  588. if isinstance(value, bool):
  589. return 'true' if value else 'false'
  590. if isinstance(value, str) and not value:
  591. raise TemplateRuntimeError(f"query(): the {name} filter was given an empty string.")
  592. if isinstance(value, (str, int, float, Decimal)):
  593. return str(value)
  594. if type(value) in NATIVE_VALUE_TYPES and type(value) is not timedelta:
  595. # Rendered as in REST API responses (e.g. a prefix as 192.0.2.0/24)
  596. return render_native_values(value)
  597. raise TemplateRuntimeError(
  598. f"query(): the {name} filter takes strings, numbers, IP addresses, dates and times (found "
  599. f"{type(value).__name__}). For a related object, pass its ID or slug."
  600. )
  601. def _get_related_objects(model, pks, relation):
  602. """
  603. Return a queryset of the objects related to any of the given objects through a reverse relation, a many-to-many
  604. field, or a GenericRelation, and the name of the field which holds the primary key of the object each relates to.
  605. """
  606. field = getattr(model, relation).field
  607. if isinstance(field, GenericRelation):
  608. return _get_base_queryset(field.related_model).filter(**{
  609. field.content_type_field_name: ContentType.objects.get_for_model(model),
  610. f'{field.object_id_field_name}__in': pks,
  611. }), field.object_id_field_name
  612. if field.model is model and field.many_to_many:
  613. # A many-to-many field declared on this model
  614. name = field.related_query_name()
  615. return _get_base_queryset(field.related_model).filter(**{f'{name}__in': pks}), name
  616. return _get_base_queryset(field.model).filter(**{f'{field.name}__in': pks}), field.attname
  617. def _get_relations(model):
  618. """
  619. Return the related models of the serializer fields which represent related objects, keyed by field name. A generic
  620. foreign key maps to the name of its content type field.
  621. """
  622. if model in _relations:
  623. return _relations[model]
  624. # Imported here to avoid a circular import (netbox.api.serializers imports extras.models)
  625. from netbox.api.serializers.generic import GenericObjectSerializer
  626. relations = {}
  627. if serializer_class := _get_serializer_class(model):
  628. for name, field in serializer_class._declared_fields.items():
  629. if isinstance(field, GFKSerializerField):
  630. try:
  631. model_field = model._meta.get_field(field.source or name)
  632. except FieldDoesNotExist:
  633. continue
  634. if isinstance(model_field, GenericForeignKey):
  635. relations[name] = model_field.ct_field
  636. elif isinstance(getattr(field, 'child', field), GenericObjectSerializer):
  637. relations[name] = _GENERIC_OBJECTS
  638. elif nested_serializer := _get_nested_serializer(field):
  639. relations[name] = type(nested_serializer).Meta.model
  640. _relations[model] = relations
  641. return relations
  642. def _find_related_objects(model, data, found):
  643. """
  644. Add the primary keys of the related objects represented within an object's (possibly partial) representation to
  645. found, by model.
  646. """
  647. for key, relation in _get_relations(model).items():
  648. if (value := data.get(key)) is None:
  649. continue
  650. values = value if isinstance(value, list) else [value]
  651. if relation is _GENERIC_OBJECTS:
  652. items = [
  653. (_get_model(item.get('object_type')), item.get('object')) for item in values if isinstance(item, dict)
  654. ]
  655. else:
  656. # A generic foreign key gives the related model by its content type field
  657. related_model = _get_model(data.get(relation)) if isinstance(relation, str) else relation
  658. items = [(related_model, item) for item in values]
  659. for related_model, item in items:
  660. if related_model is not None and isinstance(item, dict) and item.get('id') is not None:
  661. found.setdefault(related_model, {})[item['id']] = None
  662. _find_related_objects(related_model, item, found)
  663. def _find_batch(model, pk, state, batches):
  664. batch = batches.get((model, pk))
  665. if batch is None and batches is not state.cache:
  666. batch = state.cache.get((model, pk))
  667. return batch
  668. def _register(model, pks, state, batches):
  669. """
  670. Group any of the given objects not yet in a batch into batches, to be loaded together.
  671. """
  672. if _get_serializer_class(model) is None:
  673. return
  674. pks = [pk for pk in pks if _find_batch(model, pk, state, batches) is None]
  675. for start in range(0, len(pks), TEMPLATE_OBJECTS_CHUNK_SIZE):
  676. batch = _Batch(model, pks[start:start + TEMPLATE_OBJECTS_CHUNK_SIZE], state, batches)
  677. for pk in batch.pks:
  678. batches[(model, pk)] = batch
  679. def _get_batch(model, pk, state, batches=None):
  680. """
  681. Return the batch of the given object, or None if its model has no REST API serializer.
  682. """
  683. if batches is None:
  684. batches = state.cache
  685. if (batch := _find_batch(model, pk, state, batches)) is None:
  686. _register(model, [pk], state, batches)
  687. batch = batches.get((model, pk))
  688. return batch
  689. def _get_serializer(model, state):
  690. """
  691. Return the serializer used for the model's objects throughout a render, and its readable fields by name. The
  692. fields are None for a serializer which customizes its representation, which can only be rendered as a whole.
  693. """
  694. if model not in state.serializers:
  695. serializer = _get_serializer_class(model)(context={'request': None})
  696. fields = None
  697. if type(serializer).to_representation is Serializer.to_representation:
  698. fields = {name: field for name, field in serializer.fields.items() if not field.write_only}
  699. state.serializers[model] = (serializer, fields)
  700. return state.serializers[model]
  701. def _preload_custom_field_objects(field, instances):
  702. """
  703. Load the targets of the given objects' object and multi-object custom fields together, as the REST API does when
  704. serializing a list. The serializer is shared by every batch of its model, so the targets are added to its cache.
  705. """
  706. from extras.api.customfields import CustomFieldsDataField
  707. if isinstance(field, CustomFieldsDataField):
  708. field.parent.context.setdefault('cf_object_cache', {}).update(field.get_object_cache(instances))
  709. def _serialize_field(field, instance):
  710. """
  711. Return a serializer field's representation of an object, as Serializer.to_representation() derives it.
  712. """
  713. try:
  714. attribute = field.get_attribute(instance)
  715. except SkipField:
  716. return _MISSING
  717. if (attribute.pk if isinstance(attribute, PKOnlyObject) else attribute) is None:
  718. return None
  719. return field.to_representation(attribute)
  720. def _load_objects(model, pks, state, cache=False, batches=None):
  721. """
  722. Return TemplateObjects for the objects with the given primary keys which the rendering user is permitted to view,
  723. in the order of the keys. The objects are loaded together. If cache is True, they are retained in the given
  724. batches (by default, for the rest of the render); otherwise, only for as long as they are referenced.
  725. """
  726. if not pks or _get_serializer_class(model) is None:
  727. return []
  728. if not cache:
  729. batches = {}
  730. elif batches is None:
  731. batches = state.cache
  732. _register(model, pks, state, batches)
  733. objects = []
  734. for pk in pks:
  735. batch = _find_batch(model, pk, state, batches)
  736. if pk in batch.get_instances():
  737. objects.append(TemplateObject({'id': pk}, model, state, batch=batch))
  738. return objects
  739. def to_template_data(value, state=None):
  740. """
  741. Convert a value for restricted rendering to plain dicts, lists, strings, numbers, booleans, and None, keeping IP
  742. addresses, dates and times as they are. Given a render state, model instances are represented by TemplateObjects,
  743. and querysets and related managers by TemplateObjectLists.
  744. """
  745. if isinstance(value, (TemplateObject, TemplateObjectList)):
  746. return value
  747. if state is not None:
  748. if isinstance(value, models.Model):
  749. return get_template_object(value, state)
  750. if isinstance(value, models.Manager):
  751. # A related manager (e.g. device.interfaces) is represented by its objects
  752. value = value.all()
  753. if isinstance(value, models.QuerySet):
  754. return get_template_objects(value, state)
  755. if isinstance(value, dict):
  756. return {key: to_template_data(item, state) for key, item in value.items()}
  757. if isinstance(value, (list, tuple, set, frozenset)):
  758. return [to_template_data(item, state) for item in value]
  759. if value is None or type(value) in _PLAIN_VALUE_TYPES:
  760. return value
  761. if isinstance(value, str):
  762. # A str subclass (e.g. a SafeString) may return itself from str()
  763. return str.__str__(value)
  764. # Anything else (e.g. a lazy translation string) is represented by its string value
  765. return str(value)