models.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. import json
  2. import re
  3. import urllib.parse
  4. from pathlib import Path
  5. from django.conf import settings
  6. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  7. from django.contrib.postgres.fields import ArrayField
  8. from django.core.exceptions import ValidationError
  9. from django.core.validators import MaxValueValidator, MinValueValidator
  10. from django.db import models
  11. from django.urls import reverse
  12. from django.utils import timezone
  13. from django.utils.html import escape
  14. from django.utils.safestring import mark_safe
  15. from django.utils.text import format_lazy
  16. from django.utils.translation import gettext_lazy as _
  17. from rest_framework.utils.encoders import JSONEncoder
  18. from extras.choices import *
  19. from extras.conditions import ConditionSet, InvalidCondition
  20. from extras.constants import *
  21. from extras.models.mixins import RenderTemplateMixin
  22. from extras.querysets import SharedObjectQuerySet
  23. from extras.utils import image_upload
  24. from netbox.config import get_config
  25. from netbox.event_rules import get_event_rule_action, get_event_rule_action_choices
  26. from netbox.events import get_event_type_choices
  27. from netbox.models import ChangeLoggedModel
  28. from netbox.models.features import (
  29. CloningMixin,
  30. CustomFieldsMixin,
  31. CustomLinksMixin,
  32. ExportTemplatesMixin,
  33. SyncedDataMixin,
  34. TagsMixin,
  35. has_feature,
  36. )
  37. from netbox.models.mixins import OwnerMixin
  38. from netbox.settings_utils import parse_job_timeout
  39. from utilities.html import clean_html
  40. from utilities.jinja2 import JINJA2_TEMPLATE_RE, render_jinja2, sanitize_http_header, validate_jinja2_syntax
  41. from utilities.querydict import dict_to_querydict
  42. from utilities.querysets import RestrictedQuerySet
  43. from utilities.tables import get_table_for_model
  44. __all__ = (
  45. 'Bookmark',
  46. 'CustomLink',
  47. 'EventRule',
  48. 'ExportTemplate',
  49. 'ImageAttachment',
  50. 'JournalEntry',
  51. 'SavedFilter',
  52. 'TableConfig',
  53. 'Webhook',
  54. )
  55. # Matches a literal URL scheme (RFC 3986), independent of urlsplit()'s netloc parsing -- which can
  56. # raise ValueError on a malformed host -- so a payload_url's scheme can always be read even when
  57. # its host is templated or malformed.
  58. LITERAL_SCHEME_RE = re.compile(r'^([a-zA-Z][a-zA-Z0-9+.-]*):')
  59. class EventRule(CustomFieldsMixin, ExportTemplatesMixin, OwnerMixin, TagsMixin, ChangeLoggedModel):
  60. """
  61. An EventRule defines an action to be taken automatically in response to a specific set of events, such as when a
  62. specific type of object is created, modified, or deleted. The action to be taken might entail transmitting a
  63. webhook or executing a custom script.
  64. """
  65. object_types = models.ManyToManyField(
  66. to='contenttypes.ContentType',
  67. related_name='event_rules',
  68. verbose_name=_('object types'),
  69. help_text=_("The object(s) to which this rule applies.")
  70. )
  71. name = models.CharField(
  72. verbose_name=_('name'),
  73. max_length=150,
  74. unique=True
  75. )
  76. description = models.CharField(
  77. verbose_name=_('description'),
  78. max_length=200,
  79. blank=True
  80. )
  81. event_types = ArrayField(
  82. base_field=models.CharField(max_length=50, choices=get_event_type_choices),
  83. help_text=_("The types of event which will trigger this rule.")
  84. )
  85. enabled = models.BooleanField(
  86. verbose_name=_('enabled'),
  87. default=True
  88. )
  89. conditions = models.JSONField(
  90. verbose_name=_('conditions'),
  91. blank=True,
  92. null=True,
  93. help_text=_("A set of conditions which determine whether the event will be generated.")
  94. )
  95. # Action to take
  96. action_type = models.CharField(
  97. max_length=100,
  98. # Bare callable, re-evaluated fresh on each access via Django's CallableChoiceIterator,
  99. # so a plugin action registered after this module was first imported is still reflected.
  100. choices=get_event_rule_action_choices,
  101. default=EventRuleActionChoices.WEBHOOK,
  102. verbose_name=_('action type')
  103. )
  104. action_object_type = models.ForeignKey(
  105. to='contenttypes.ContentType',
  106. related_name='eventrule_actions',
  107. on_delete=models.CASCADE,
  108. blank=True,
  109. null=True,
  110. )
  111. action_object_id = models.PositiveBigIntegerField(
  112. blank=True,
  113. null=True
  114. )
  115. action_object = GenericForeignKey(
  116. ct_field='action_object_type',
  117. fk_field='action_object_id'
  118. )
  119. action_data = models.JSONField(
  120. verbose_name=_('data'),
  121. blank=True,
  122. null=True,
  123. help_text=_("Additional data to pass to the action object")
  124. )
  125. comments = models.TextField(
  126. verbose_name=_('comments'),
  127. blank=True
  128. )
  129. class Meta:
  130. ordering = ('name',)
  131. indexes = (
  132. models.Index(fields=('action_object_type', 'action_object_id')),
  133. )
  134. verbose_name = _('event rule')
  135. verbose_name_plural = _('event rules')
  136. def __str__(self):
  137. return self.name
  138. def get_absolute_url(self):
  139. return reverse('extras:eventrule', args=[self.pk])
  140. @property
  141. def action_provider(self):
  142. """
  143. Return the registered EventRuleAction instance for this rule's action_type, or None if it
  144. is not currently registered (e.g. the providing plugin is not installed).
  145. """
  146. return get_event_rule_action(self.action_type)
  147. @property
  148. def action_is_available(self):
  149. return self.action_provider is not None
  150. def get_action_type_display(self):
  151. if action := self.action_provider:
  152. return action.label
  153. return _('{slug} (unavailable)').format(slug=self.action_type)
  154. def get_action_type_color(self):
  155. return None if self.action_is_available else 'red'
  156. def clean(self):
  157. super().clean()
  158. # Validate that any conditions are in the correct format
  159. if self.conditions:
  160. try:
  161. ConditionSet(self.conditions)
  162. except ValueError as e:
  163. raise ValidationError({'conditions': e})
  164. # action_data must be a JSON object (or null)
  165. if self.action_data is not None and not isinstance(self.action_data, dict):
  166. raise ValidationError({'action_data': _('Action data must be a JSON object or null.')})
  167. # action_type's own validity is already enforced by the field's dynamic choices= (Field.
  168. # validate(), earlier in full_clean()); guard here only in case clean() ran standalone.
  169. if self.action_is_available:
  170. self.action_provider._validate(action_object=self.action_object, action_data=self.action_data)
  171. def eval_conditions(self, data):
  172. """
  173. Test whether the given data meets the conditions of the event rule (if any). Return True
  174. if met or no conditions are specified.
  175. """
  176. if not self.conditions:
  177. return True
  178. logger = logging.getLogger('netbox.event_rules')
  179. try:
  180. result = ConditionSet(self.conditions).eval(data)
  181. logger.debug(f'{self.name}: Evaluated as {result}')
  182. return result
  183. except InvalidCondition as e:
  184. logger.error(f"{self.name}: Evaluation failed. {e}")
  185. return False
  186. class Webhook(CustomFieldsMixin, ExportTemplatesMixin, TagsMixin, OwnerMixin, ChangeLoggedModel):
  187. """
  188. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  189. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  190. Each Webhook can be limited to firing only on certain actions or certain object types.
  191. """
  192. name = models.CharField(
  193. verbose_name=_('name'),
  194. max_length=150,
  195. unique=True
  196. )
  197. description = models.CharField(
  198. verbose_name=_('description'),
  199. max_length=200,
  200. blank=True
  201. )
  202. payload_url = models.CharField(
  203. max_length=500,
  204. verbose_name=_('URL'),
  205. help_text=_(
  206. "This URL will be called using the HTTP method defined when the webhook is called. Must be "
  207. "http:// or https://. Jinja2 template processing is supported (with the same context as the "
  208. "request body) for part or all of the URL."
  209. )
  210. )
  211. http_method = models.CharField(
  212. max_length=30,
  213. choices=WebhookHttpMethodChoices,
  214. default=WebhookHttpMethodChoices.METHOD_POST,
  215. verbose_name=_('HTTP method')
  216. )
  217. http_content_type = models.CharField(
  218. max_length=100,
  219. default=HTTP_CONTENT_TYPE_JSON,
  220. verbose_name=_('HTTP content type'),
  221. help_text=_(
  222. 'The complete list of official content types is available '
  223. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.'
  224. )
  225. )
  226. additional_headers = models.TextField(
  227. verbose_name=_('additional headers'),
  228. blank=True,
  229. help_text=_(
  230. "User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. Headers "
  231. "should be defined in the format <code>Name: Value</code>. Jinja2 template processing is supported with "
  232. "the same context as the request body (below). When interpolating untrusted data (such as object "
  233. "attributes) into a header value, apply the <code>header_safe</code> filter to guard against HTTP header "
  234. "injection, e.g. <code>X-Object: {{ data.name | header_safe }}</code>."
  235. )
  236. )
  237. body_template = models.TextField(
  238. verbose_name=_('body template'),
  239. blank=True,
  240. help_text=_(
  241. "Jinja2 template for a custom request body. If blank, a JSON object representing the change will be "
  242. "included. Available context data includes: <code>event</code>, <code>model</code>, "
  243. "<code>timestamp</code>, <code>request</code>, and <code>data</code>."
  244. )
  245. )
  246. secret = models.CharField(
  247. verbose_name=_('secret'),
  248. max_length=255,
  249. blank=True,
  250. help_text=_(
  251. "When provided, the request will include a <code>X-Hook-Signature</code> header containing a HMAC hex "
  252. "digest of the payload body using the secret as the key. The secret is not transmitted in the request."
  253. )
  254. )
  255. ssl_verification = models.BooleanField(
  256. default=True,
  257. verbose_name=_('SSL verification'),
  258. help_text=_("Enable SSL certificate verification. Disable with caution!")
  259. )
  260. ca_file_path = models.CharField(
  261. max_length=4096,
  262. null=True,
  263. blank=True,
  264. verbose_name=_('CA File Path'),
  265. help_text=_(
  266. "The specific CA certificate file to use for SSL verification. Leave blank to use the system defaults."
  267. )
  268. )
  269. timeout = models.PositiveSmallIntegerField(
  270. verbose_name=_('timeout'),
  271. null=True,
  272. blank=True,
  273. validators=(
  274. MinValueValidator(1),
  275. MaxValueValidator(3600),
  276. ),
  277. help_text=format_lazy(
  278. _(
  279. "The maximum time (in seconds) to wait for a response before failing the request. Leave blank to use "
  280. "the system default ({default_timeout} seconds)."
  281. ),
  282. default_timeout=settings.WEBHOOK_DEFAULT_TIMEOUT
  283. )
  284. )
  285. events = GenericRelation(
  286. EventRule,
  287. content_type_field='action_object_type',
  288. object_id_field='action_object_id'
  289. )
  290. class Meta:
  291. ordering = ('name',)
  292. verbose_name = _('webhook')
  293. verbose_name_plural = _('webhooks')
  294. def __str__(self):
  295. return self.name
  296. def get_absolute_url(self):
  297. return reverse('extras:webhook', args=[self.pk])
  298. @property
  299. def docs_url(self):
  300. return f'{settings.STATIC_URL}docs/models/extras/webhook/'
  301. def clean(self):
  302. super().clean()
  303. errors = {}
  304. # CA file path requires SSL verification enabled
  305. if not self.ssl_verification and self.ca_file_path:
  306. errors['ca_file_path'] = _('Do not specify a CA certificate file if SSL verification is disabled.')
  307. # payload_url may be a literal URL or a Jinja2 template (see its help_text). Skipped when
  308. # blank; clean_fields() already flags that.
  309. if self.payload_url:
  310. if JINJA2_TEMPLATE_RE.search(self.payload_url):
  311. # A literal, disallowed scheme (e.g. "file://") can never resolve no matter what
  312. # else in the value is templated; anything else is checked for template syntax
  313. # only, since its rendered result isn't known here.
  314. match = LITERAL_SCHEME_RE.match(self.payload_url)
  315. if match and match.group(1).lower() not in ('http', 'https'):
  316. errors['payload_url'] = _("Enter a valid URL, beginning with http:// or https://.")
  317. else:
  318. try:
  319. validate_jinja2_syntax(self.payload_url)
  320. except ValidationError as e:
  321. errors['payload_url'] = e
  322. else:
  323. # Fully literal -- validate directly rather than via URLValidator, which rejects
  324. # single-label and underscore hosts that `requests` accepts fine. urlsplit() can
  325. # raise ValueError for a malformed netloc (e.g. an unbalanced IPv6 bracket).
  326. try:
  327. scheme, netloc = urllib.parse.urlsplit(self.payload_url)[:2]
  328. except ValueError:
  329. scheme, netloc = '', ''
  330. if scheme not in ('http', 'https') or not netloc:
  331. errors['payload_url'] = _("Enter a valid URL, beginning with http:// or https://.")
  332. if errors:
  333. raise ValidationError(errors)
  334. # A timeout which meets or exceeds the background job timeout leaves no room for the request's own timeout
  335. # to apply: the worker will terminate the job first. (Staying below the job timeout does not guarantee that
  336. # the request times out on its own, as the timeout applies separately to connecting and to reading data.)
  337. job_timeout = parse_job_timeout(settings.RQ_DEFAULT_TIMEOUT)
  338. if self.timeout is not None and job_timeout is not None and self.timeout >= job_timeout:
  339. raise ValidationError({
  340. 'timeout': _(
  341. "Timeout must be less than the background job timeout ({timeout} seconds)."
  342. ).format(timeout=job_timeout)
  343. })
  344. def render_headers(self, context):
  345. """
  346. Render additional_headers and return a dict of Header: Value pairs.
  347. """
  348. if not self.additional_headers:
  349. return {}
  350. ret = {}
  351. # Expose the `header_safe` filter so template authors can sanitize interpolated values (e.g. user-controlled
  352. # object data) against HTTP header (CR/LF) injection. See utilities.jinja2.sanitize_http_header.
  353. data = render_jinja2(self.additional_headers, context, filters={'header_safe': sanitize_http_header})
  354. for line in data.splitlines():
  355. if ':' not in line:
  356. continue
  357. header, value = line.split(':', 1)
  358. ret[header.strip()] = value.strip()
  359. return ret
  360. def render_body(self, context):
  361. """
  362. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  363. """
  364. if self.body_template:
  365. return render_jinja2(self.body_template, context)
  366. return json.dumps(context, cls=JSONEncoder)
  367. def render_payload_url(self, context):
  368. """
  369. Render the payload URL.
  370. """
  371. return render_jinja2(self.payload_url, context)
  372. class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel):
  373. """
  374. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  375. code to be rendered with an object as context.
  376. """
  377. object_types = models.ManyToManyField(
  378. to='contenttypes.ContentType',
  379. related_name='custom_links',
  380. help_text=_('The object type(s) to which this link applies.')
  381. )
  382. name = models.CharField(
  383. verbose_name=_('name'),
  384. max_length=100,
  385. unique=True
  386. )
  387. enabled = models.BooleanField(
  388. verbose_name=_('enabled'),
  389. default=True
  390. )
  391. link_text = models.TextField(
  392. verbose_name=_('link text'),
  393. help_text=_("Jinja2 template code for link text")
  394. )
  395. link_url = models.TextField(
  396. verbose_name=_('link URL'),
  397. help_text=_("Jinja2 template code for link URL")
  398. )
  399. weight = models.PositiveSmallIntegerField(
  400. verbose_name=_('weight'),
  401. default=100
  402. )
  403. group_name = models.CharField(
  404. verbose_name=_('group name'),
  405. max_length=50,
  406. blank=True,
  407. help_text=_("Links with the same group will appear as a dropdown menu")
  408. )
  409. button_class = models.CharField(
  410. verbose_name=_('button class'),
  411. max_length=30,
  412. choices=CustomLinkButtonClassChoices,
  413. default=CustomLinkButtonClassChoices.DEFAULT,
  414. help_text=_("The class of the first link in a group will be used for the dropdown button")
  415. )
  416. new_window = models.BooleanField(
  417. verbose_name=_('new window'),
  418. default=False,
  419. help_text=_("Force link to open in a new window")
  420. )
  421. clone_fields = (
  422. 'object_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window',
  423. )
  424. class Meta:
  425. ordering = ['group_name', 'weight', 'name']
  426. indexes = (
  427. models.Index(fields=('group_name', 'weight', 'name')), # Default ordering
  428. )
  429. verbose_name = _('custom link')
  430. verbose_name_plural = _('custom links')
  431. def __str__(self):
  432. return self.name
  433. def get_absolute_url(self):
  434. return reverse('extras:customlink', args=[self.pk])
  435. @property
  436. def docs_url(self):
  437. return f'{settings.STATIC_URL}docs/models/extras/customlink/'
  438. def render(self, context):
  439. """
  440. Render the CustomLink given the provided context, and return the text, link, and link_target.
  441. :param context: The context passed to Jinja2
  442. """
  443. text = render_jinja2(self.link_text, context).strip()
  444. if not text:
  445. return {}
  446. link = render_jinja2(self.link_url, context).strip()
  447. link_target = ' target="_blank"' if self.new_window else ''
  448. # Sanitize link text
  449. allowed_schemes = get_config().ALLOWED_URL_SCHEMES
  450. text = clean_html(text, allowed_schemes)
  451. # Sanitize link
  452. link = urllib.parse.quote(link, safe='/:?&=%+[]@#,;!')
  453. # Verify link scheme is allowed
  454. result = urllib.parse.urlparse(link)
  455. if result.scheme and result.scheme not in allowed_schemes:
  456. link = ""
  457. return {
  458. 'text': text,
  459. 'link': link,
  460. 'link_target': link_target,
  461. }
  462. class ExportTemplate(
  463. SyncedDataMixin,
  464. CloningMixin,
  465. ExportTemplatesMixin,
  466. OwnerMixin,
  467. ChangeLoggedModel,
  468. RenderTemplateMixin,
  469. ):
  470. object_types = models.ManyToManyField(
  471. to='contenttypes.ContentType',
  472. related_name='export_templates',
  473. help_text=_('The object type(s) to which this template applies.')
  474. )
  475. name = models.CharField(
  476. verbose_name=_('name'),
  477. max_length=100
  478. )
  479. description = models.CharField(
  480. verbose_name=_('description'),
  481. max_length=200,
  482. blank=True
  483. )
  484. clone_fields = (
  485. 'object_types', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment',
  486. )
  487. class Meta:
  488. ordering = ('name',)
  489. indexes = (
  490. models.Index(fields=('name',)), # Default ordering
  491. )
  492. verbose_name = _('export template')
  493. verbose_name_plural = _('export templates')
  494. def __str__(self):
  495. return self.name
  496. def get_absolute_url(self):
  497. return reverse('extras:exporttemplate', args=[self.pk])
  498. @property
  499. def docs_url(self):
  500. return f'{settings.STATIC_URL}docs/models/extras/exporttemplate/'
  501. def clean(self):
  502. super().clean()
  503. if self.name.lower() == 'table':
  504. raise ValidationError({
  505. 'name': _('"{name}" is a reserved name. Please choose a different name.').format(name=self.name)
  506. })
  507. def sync_data(self):
  508. """
  509. Synchronize template content from the designated DataFile (if any).
  510. """
  511. self.template_code = self.validate_synced_value('template_code', self.data_file.data_as_string)
  512. sync_data.alters_data = True
  513. def get_context(self, context=None, queryset=None):
  514. _context = super().get_context(context=context, queryset=queryset)
  515. _context['queryset'] = queryset
  516. return _context
  517. class SavedFilter(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel):
  518. """
  519. A set of predefined keyword parameters that can be reused to filter for specific objects.
  520. """
  521. object_types = models.ManyToManyField(
  522. to='contenttypes.ContentType',
  523. related_name='saved_filters',
  524. help_text=_('The object type(s) to which this filter applies.')
  525. )
  526. name = models.CharField(
  527. verbose_name=_('name'),
  528. max_length=100,
  529. unique=True
  530. )
  531. slug = models.SlugField(
  532. verbose_name=_('slug'),
  533. max_length=100,
  534. unique=True
  535. )
  536. description = models.CharField(
  537. verbose_name=_('description'),
  538. max_length=200,
  539. blank=True
  540. )
  541. user = models.ForeignKey(
  542. to=settings.AUTH_USER_MODEL,
  543. on_delete=models.SET_NULL,
  544. blank=True,
  545. null=True
  546. )
  547. weight = models.PositiveSmallIntegerField(
  548. verbose_name=_('weight'),
  549. default=100
  550. )
  551. enabled = models.BooleanField(
  552. verbose_name=_('enabled'),
  553. default=True
  554. )
  555. shared = models.BooleanField(
  556. verbose_name=_('shared'),
  557. default=True
  558. )
  559. parameters = models.JSONField(
  560. verbose_name=_('parameters')
  561. )
  562. objects = SharedObjectQuerySet.as_manager()
  563. clone_fields = (
  564. 'object_types', 'weight', 'enabled', 'parameters',
  565. )
  566. class Meta:
  567. ordering = ('weight', 'name')
  568. indexes = (
  569. models.Index(fields=('weight', 'name')), # Default ordering
  570. )
  571. verbose_name = _('saved filter')
  572. verbose_name_plural = _('saved filters')
  573. def __str__(self):
  574. return self.name
  575. def get_absolute_url(self):
  576. return reverse('extras:savedfilter', args=[self.pk])
  577. @property
  578. def docs_url(self):
  579. return f'{settings.STATIC_URL}docs/models/extras/savedfilter/'
  580. def clean(self):
  581. super().clean()
  582. # Verify that `parameters` is a JSON object
  583. if type(self.parameters) is not dict:
  584. raise ValidationError(
  585. {'parameters': _('Filter parameters must be stored as a dictionary of keyword arguments.')}
  586. )
  587. @property
  588. def url_params(self):
  589. qd = dict_to_querydict(self.parameters)
  590. return qd.urlencode()
  591. class TableConfig(CloningMixin, ChangeLoggedModel):
  592. """
  593. A saved configuration of columns and ordering which applies to a specific table.
  594. """
  595. object_type = models.ForeignKey(
  596. to='contenttypes.ContentType',
  597. on_delete=models.CASCADE,
  598. related_name='table_configs',
  599. help_text=_("The table's object type"),
  600. )
  601. table = models.CharField(
  602. verbose_name=_('table'),
  603. max_length=100,
  604. )
  605. name = models.CharField(
  606. verbose_name=_('name'),
  607. max_length=100,
  608. )
  609. description = models.CharField(
  610. verbose_name=_('description'),
  611. max_length=200,
  612. blank=True,
  613. )
  614. user = models.ForeignKey(
  615. to=settings.AUTH_USER_MODEL,
  616. on_delete=models.SET_NULL,
  617. blank=True,
  618. null=True,
  619. )
  620. weight = models.PositiveSmallIntegerField(
  621. verbose_name=_('weight'),
  622. default=1000,
  623. )
  624. enabled = models.BooleanField(
  625. verbose_name=_('enabled'),
  626. default=True
  627. )
  628. shared = models.BooleanField(
  629. verbose_name=_('shared'),
  630. default=True
  631. )
  632. columns = ArrayField(
  633. base_field=models.CharField(max_length=100),
  634. )
  635. ordering = ArrayField(
  636. base_field=models.CharField(max_length=100),
  637. blank=True,
  638. null=True,
  639. )
  640. objects = SharedObjectQuerySet.as_manager()
  641. clone_fields = ('object_type', 'table', 'enabled', 'shared', 'columns', 'ordering')
  642. class Meta:
  643. ordering = ('weight', 'name')
  644. indexes = (
  645. models.Index(fields=('weight', 'name')), # Default ordering
  646. )
  647. verbose_name = _('table config')
  648. verbose_name_plural = _('table configs')
  649. def __str__(self):
  650. return self.name
  651. def get_absolute_url(self):
  652. return reverse('extras:tableconfig', args=[self.pk])
  653. @property
  654. def docs_url(self):
  655. return f'{settings.STATIC_URL}docs/models/extras/tableconfig/'
  656. @property
  657. def table_class(self):
  658. return get_table_for_model(self.object_type.model_class(), name=self.table)
  659. @property
  660. def ordering_items(self):
  661. """
  662. Return a list of two-tuples indicating the column(s) by which the table is to be ordered and a boolean for each
  663. column indicating whether its ordering is ascending.
  664. """
  665. items = []
  666. for col in self.ordering or []:
  667. if col.startswith('-'):
  668. ascending = False
  669. col = col[1:]
  670. else:
  671. ascending = True
  672. items.append((col, ascending))
  673. return items
  674. def clean(self):
  675. super().clean()
  676. # Skip table validation until the object type and table have been set
  677. if not self.object_type_id or not self.table:
  678. return
  679. # Validate table
  680. if self.table_class is None:
  681. raise ValidationError({
  682. 'table': _("Unknown table: {name}").format(name=self.table)
  683. })
  684. table = self.table_class([])
  685. # Validate ordering columns
  686. for name in self.ordering or []:
  687. if name.startswith('-'):
  688. name = name[1:] # Strip leading hyphen
  689. if name not in table.columns:
  690. raise ValidationError({
  691. 'ordering': _('Unknown column: {name}').format(name=name)
  692. })
  693. # Validate selected columns
  694. for name in self.columns or []:
  695. if name not in table.columns:
  696. raise ValidationError({
  697. 'columns': _('Unknown column: {name}').format(name=name)
  698. })
  699. class ImageAttachment(ChangeLoggedModel):
  700. """
  701. An uploaded image which is associated with an object.
  702. """
  703. object_type = models.ForeignKey(
  704. to='contenttypes.ContentType',
  705. on_delete=models.CASCADE
  706. )
  707. object_id = models.PositiveBigIntegerField()
  708. parent = GenericForeignKey(
  709. ct_field='object_type',
  710. fk_field='object_id'
  711. )
  712. image = models.ImageField(
  713. upload_to=image_upload,
  714. height_field='image_height',
  715. width_field='image_width'
  716. )
  717. image_height = models.PositiveSmallIntegerField(
  718. verbose_name=_('image height'),
  719. )
  720. image_width = models.PositiveSmallIntegerField(
  721. verbose_name=_('image width'),
  722. )
  723. # Unlike image_height/image_width (populated automatically by ImageField), there is no native size_field, so
  724. # this is populated in save(). It is nullable because existing rows predate the field and storage reads can
  725. # fail; a null value means "not yet computed" and the size property falls back to reading storage.
  726. image_size = models.PositiveBigIntegerField(
  727. verbose_name=_('image size'),
  728. blank=True,
  729. null=True,
  730. )
  731. name = models.CharField(
  732. verbose_name=_('name'),
  733. max_length=50,
  734. blank=True
  735. )
  736. description = models.CharField(
  737. verbose_name=_('description'),
  738. max_length=200,
  739. blank=True
  740. )
  741. objects = RestrictedQuerySet.as_manager()
  742. def __init__(self, *args, **kwargs):
  743. super().__init__(*args, **kwargs)
  744. # Cache an identity for the current image so save() can detect a new/replaced file and recompute the cached
  745. # image_size. We combine the file name with the (auto-populated) dimensions: a replacement that reuses the
  746. # same name is still caught when its dimensions differ. Read the raw image value from __dict__ to avoid
  747. # triggering the ImageField descriptor here (doing so during ORM/GraphQL instantiation can recurse).
  748. self._orig_image_key = self._image_identity()
  749. def _image_identity(self):
  750. """
  751. Return a tuple identifying the current image file for change detection: its name plus the dimensions Django
  752. populates from it. All three are read raw from __dict__ to avoid triggering the ImageField descriptor
  753. (accessing `self.image` during ORM/GraphQL instantiation can recurse). Not a content fingerprint: a
  754. replacement with an identical name AND identical dimensions is not distinguished (would require reading the
  755. file, the storage round-trip this caching avoids).
  756. """
  757. original = self.__dict__.get('image')
  758. name = getattr(original, 'name', original)
  759. return (name, self.__dict__.get('image_height'), self.__dict__.get('image_width'))
  760. class Meta:
  761. ordering = ('name', 'pk') # name may be non-unique
  762. indexes = (
  763. models.Index(fields=('name', 'id')), # Default ordering
  764. models.Index(fields=('object_type', 'object_id')),
  765. )
  766. verbose_name = _('image attachment')
  767. verbose_name_plural = _('image attachments')
  768. def __str__(self):
  769. return self.name or self.filename
  770. def get_absolute_url(self):
  771. return reverse('extras:imageattachment', args=[self.pk])
  772. def clean(self):
  773. super().clean()
  774. # Validate the assigned object type
  775. if not has_feature(self.object_type, 'image_attachments'):
  776. raise ValidationError(
  777. _("Image attachments cannot be assigned to this object type ({type}).").format(type=self.object_type)
  778. )
  779. def delete(self, *args, **kwargs):
  780. _name = self.image.name
  781. super().delete(*args, **kwargs)
  782. # Delete file from disk
  783. self.image.delete(save=False)
  784. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  785. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  786. self.image.name = _name
  787. @property
  788. def filename(self):
  789. base_name = Path(self.image.name).name
  790. prefix = f"{self.object_type.model}_{self.object_id}_"
  791. return base_name.removeprefix(prefix)
  792. @property
  793. def html_tag(self):
  794. """
  795. Returns a complete <img> tag suitable for embedding in an HTML document.
  796. """
  797. return mark_safe('<img src="{url}" height="{height}" width="{width}" alt="{alt_text}" />'.format(
  798. url=self.image.url,
  799. height=self.image_height,
  800. width=self.image_width,
  801. alt_text=escape(self.description or self.name),
  802. ))
  803. def _read_image_size(self):
  804. """
  805. Read the image file's size from storage, suppressing an OSError in case the file is inaccessible. Also
  806. opportunistically catch other exceptions that we know other storage back-ends to throw. Returns None if the
  807. size cannot be determined. This may issue a request to the storage backend (e.g. a HEAD request to S3).
  808. """
  809. if not self.image:
  810. return None
  811. expected_exceptions = [OSError]
  812. try:
  813. from botocore.exceptions import ClientError
  814. expected_exceptions.append(ClientError)
  815. except ImportError:
  816. pass
  817. try:
  818. return self.image.size
  819. except tuple(expected_exceptions):
  820. return None
  821. @property
  822. def size(self):
  823. """
  824. Return the size of the image file in bytes. Prefer the cached `image_size` value to avoid a storage request;
  825. fall back to reading from storage for legacy rows where `image_size` has not yet been populated.
  826. """
  827. if self.image_size is not None:
  828. return self.image_size
  829. return self._read_image_size()
  830. def save(self, *args, **kwargs):
  831. # Populate image_size on creation or when the image file has changed. Reading the size may touch the storage
  832. # backend (e.g. a HEAD request to S3), so we only do it when necessary: bulk operations that don't alter the
  833. # image (bulk edit, rename) leave the identity unchanged and skip the read entirely. We never overwrite a good
  834. # value with None (e.g. on a transient storage error); a failed read while replacing a file keeps the prior
  835. # size until the next successful save, which is preferred over storing None.
  836. orig_image_key = getattr(self, '_orig_image_key', None)
  837. if self._state.adding or self._image_identity() != orig_image_key:
  838. size = self._read_image_size()
  839. if size is not None:
  840. self.image_size = size
  841. super().save(*args, **kwargs)
  842. # Refresh the cached identity so subsequent saves on this instance detect further changes correctly.
  843. self._orig_image_key = self._image_identity()
  844. def to_objectchange(self, action):
  845. objectchange = super().to_objectchange(action)
  846. objectchange.related_object = self.parent
  847. return objectchange
  848. class JournalEntry(CustomFieldsMixin, CustomLinksMixin, TagsMixin, ExportTemplatesMixin, ChangeLoggedModel):
  849. """
  850. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  851. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  852. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  853. """
  854. assigned_object_type = models.ForeignKey(
  855. to='contenttypes.ContentType',
  856. on_delete=models.CASCADE
  857. )
  858. assigned_object_id = models.PositiveBigIntegerField()
  859. assigned_object = GenericForeignKey(
  860. ct_field='assigned_object_type',
  861. fk_field='assigned_object_id'
  862. )
  863. created_by = models.ForeignKey(
  864. to=settings.AUTH_USER_MODEL,
  865. on_delete=models.SET_NULL,
  866. blank=True,
  867. null=True
  868. )
  869. kind = models.CharField(
  870. verbose_name=_('kind'),
  871. max_length=30,
  872. choices=JournalEntryKindChoices,
  873. default=JournalEntryKindChoices.KIND_INFO
  874. )
  875. comments = models.TextField(
  876. verbose_name=_('comments'),
  877. )
  878. class Meta:
  879. ordering = ('-created',)
  880. indexes = (
  881. models.Index(fields=('-created',)), # Default ordering
  882. models.Index(fields=('assigned_object_type', 'assigned_object_id')),
  883. )
  884. verbose_name = _('journal entry')
  885. verbose_name_plural = _('journal entries')
  886. def __str__(self):
  887. created = timezone.localtime(self.created)
  888. return (
  889. f"{created.date().isoformat()} {created.time().isoformat(timespec='minutes')} "
  890. f"({self.get_kind_display()})"
  891. )
  892. def get_absolute_url(self):
  893. return reverse('extras:journalentry', args=[self.pk])
  894. def clean(self):
  895. super().clean()
  896. # Validate the assigned object type
  897. if not has_feature(self.assigned_object_type, 'journaling'):
  898. raise ValidationError(
  899. _("Journaling is not supported for this object type ({type}).").format(type=self.assigned_object_type)
  900. )
  901. def get_kind_color(self):
  902. return JournalEntryKindChoices.colors.get(self.kind)
  903. class Bookmark(models.Model):
  904. """
  905. An object bookmarked by a User.
  906. """
  907. created = models.DateTimeField(
  908. verbose_name=_('created'),
  909. auto_now_add=True
  910. )
  911. object_type = models.ForeignKey(
  912. to='contenttypes.ContentType',
  913. on_delete=models.PROTECT
  914. )
  915. object_id = models.PositiveBigIntegerField()
  916. object = GenericForeignKey(
  917. ct_field='object_type',
  918. fk_field='object_id'
  919. )
  920. user = models.ForeignKey(
  921. to=settings.AUTH_USER_MODEL,
  922. on_delete=models.CASCADE
  923. )
  924. objects = RestrictedQuerySet.as_manager()
  925. class Meta:
  926. ordering = ('created', 'pk')
  927. indexes = (
  928. models.Index(fields=('created', 'id')), # Default ordering
  929. models.Index(fields=('object_type', 'object_id')),
  930. )
  931. constraints = (
  932. models.UniqueConstraint(
  933. fields=('object_type', 'object_id', 'user'),
  934. name='%(app_label)s_%(class)s_unique_per_object_and_user'
  935. ),
  936. )
  937. verbose_name = _('bookmark')
  938. verbose_name_plural = _('bookmarks')
  939. def __str__(self):
  940. if self.object:
  941. return str(self.object)
  942. return super().__str__()
  943. def get_absolute_url(self):
  944. return reverse('account:bookmarks')
  945. def clean(self):
  946. super().clean()
  947. # Validate the assigned object type
  948. if not has_feature(self.object_type, 'bookmarks'):
  949. raise ValidationError(
  950. _("Bookmarks cannot be assigned to this object type ({type}).").format(type=self.object_type)
  951. )