models.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. import json
  2. import urllib.parse
  3. from django.conf import settings
  4. from django.contrib import admin
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericForeignKey
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.core.cache import cache
  9. from django.core.validators import ValidationError
  10. from django.db import models
  11. from django.http import HttpResponse, QueryDict
  12. from django.urls import reverse
  13. from django.utils import timezone
  14. from django.utils.formats import date_format
  15. from django.utils.translation import gettext as _
  16. from rest_framework.utils.encoders import JSONEncoder
  17. from extras.choices import *
  18. from extras.conditions import ConditionSet
  19. from extras.constants import *
  20. from extras.utils import FeatureQuery, image_upload
  21. from netbox.config import get_config
  22. from netbox.models import ChangeLoggedModel
  23. from netbox.models.features import (
  24. CloningMixin, CustomFieldsMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin,
  25. )
  26. from utilities.querysets import RestrictedQuerySet
  27. from utilities.utils import clean_html, render_jinja2
  28. __all__ = (
  29. 'ConfigRevision',
  30. 'CustomLink',
  31. 'ExportTemplate',
  32. 'ImageAttachment',
  33. 'JournalEntry',
  34. 'SavedFilter',
  35. 'Webhook',
  36. )
  37. class Webhook(ExportTemplatesMixin, ChangeLoggedModel):
  38. """
  39. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  40. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  41. Each Webhook can be limited to firing only on certain actions or certain object types.
  42. """
  43. content_types = models.ManyToManyField(
  44. to=ContentType,
  45. related_name='webhooks',
  46. verbose_name='Object types',
  47. limit_choices_to=FeatureQuery('webhooks'),
  48. help_text=_("The object(s) to which this Webhook applies.")
  49. )
  50. name = models.CharField(
  51. max_length=150,
  52. unique=True
  53. )
  54. type_create = models.BooleanField(
  55. default=False,
  56. help_text=_("Triggers when a matching object is created.")
  57. )
  58. type_update = models.BooleanField(
  59. default=False,
  60. help_text=_("Triggers when a matching object is updated.")
  61. )
  62. type_delete = models.BooleanField(
  63. default=False,
  64. help_text=_("Triggers when a matching object is deleted.")
  65. )
  66. type_job_start = models.BooleanField(
  67. default=False,
  68. help_text=_("Triggers when a job for a matching object is started.")
  69. )
  70. type_job_end = models.BooleanField(
  71. default=False,
  72. help_text=_("Triggers when a job for a matching object terminates.")
  73. )
  74. payload_url = models.CharField(
  75. max_length=500,
  76. verbose_name='URL',
  77. help_text=_('This URL will be called using the HTTP method defined when the webhook is called. '
  78. 'Jinja2 template processing is supported with the same context as the request body.')
  79. )
  80. enabled = models.BooleanField(
  81. default=True
  82. )
  83. http_method = models.CharField(
  84. max_length=30,
  85. choices=WebhookHttpMethodChoices,
  86. default=WebhookHttpMethodChoices.METHOD_POST,
  87. verbose_name='HTTP method'
  88. )
  89. http_content_type = models.CharField(
  90. max_length=100,
  91. default=HTTP_CONTENT_TYPE_JSON,
  92. verbose_name='HTTP content type',
  93. help_text=_('The complete list of official content types is available '
  94. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.')
  95. )
  96. additional_headers = models.TextField(
  97. blank=True,
  98. help_text=_("User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. "
  99. "Headers should be defined in the format <code>Name: Value</code>. Jinja2 template processing is "
  100. "supported with the same context as the request body (below).")
  101. )
  102. body_template = models.TextField(
  103. blank=True,
  104. help_text=_('Jinja2 template for a custom request body. If blank, a JSON object representing the change will be '
  105. 'included. Available context data includes: <code>event</code>, <code>model</code>, '
  106. '<code>timestamp</code>, <code>username</code>, <code>request_id</code>, and <code>data</code>.')
  107. )
  108. secret = models.CharField(
  109. max_length=255,
  110. blank=True,
  111. help_text=_("When provided, the request will include a 'X-Hook-Signature' "
  112. "header containing a HMAC hex digest of the payload body using "
  113. "the secret as the key. The secret is not transmitted in "
  114. "the request.")
  115. )
  116. conditions = models.JSONField(
  117. blank=True,
  118. null=True,
  119. help_text=_("A set of conditions which determine whether the webhook will be generated.")
  120. )
  121. ssl_verification = models.BooleanField(
  122. default=True,
  123. verbose_name='SSL verification',
  124. help_text=_("Enable SSL certificate verification. Disable with caution!")
  125. )
  126. ca_file_path = models.CharField(
  127. max_length=4096,
  128. null=True,
  129. blank=True,
  130. verbose_name='CA File Path',
  131. help_text=_('The specific CA certificate file to use for SSL verification. '
  132. 'Leave blank to use the system defaults.')
  133. )
  134. class Meta:
  135. ordering = ('name',)
  136. constraints = (
  137. models.UniqueConstraint(
  138. fields=('payload_url', 'type_create', 'type_update', 'type_delete'),
  139. name='%(app_label)s_%(class)s_unique_payload_url_types'
  140. ),
  141. )
  142. def __str__(self):
  143. return self.name
  144. def get_absolute_url(self):
  145. return reverse('extras:webhook', args=[self.pk])
  146. @property
  147. def docs_url(self):
  148. return f'{settings.STATIC_URL}docs/models/extras/webhook/'
  149. def clean(self):
  150. super().clean()
  151. # At least one action type must be selected
  152. if not any([
  153. self.type_create, self.type_update, self.type_delete, self.type_job_start, self.type_job_end
  154. ]):
  155. raise ValidationError(
  156. "At least one event type must be selected: create, update, delete, job_start, and/or job_end."
  157. )
  158. if self.conditions:
  159. try:
  160. ConditionSet(self.conditions)
  161. except ValueError as e:
  162. raise ValidationError({'conditions': e})
  163. # CA file path requires SSL verification enabled
  164. if not self.ssl_verification and self.ca_file_path:
  165. raise ValidationError({
  166. 'ca_file_path': 'Do not specify a CA certificate file if SSL verification is disabled.'
  167. })
  168. def render_headers(self, context):
  169. """
  170. Render additional_headers and return a dict of Header: Value pairs.
  171. """
  172. if not self.additional_headers:
  173. return {}
  174. ret = {}
  175. data = render_jinja2(self.additional_headers, context)
  176. for line in data.splitlines():
  177. header, value = line.split(':', 1)
  178. ret[header.strip()] = value.strip()
  179. return ret
  180. def render_body(self, context):
  181. """
  182. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  183. """
  184. if self.body_template:
  185. return render_jinja2(self.body_template, context)
  186. else:
  187. return json.dumps(context, cls=JSONEncoder)
  188. def render_payload_url(self, context):
  189. """
  190. Render the payload URL.
  191. """
  192. return render_jinja2(self.payload_url, context)
  193. class CustomLink(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  194. """
  195. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  196. code to be rendered with an object as context.
  197. """
  198. content_types = models.ManyToManyField(
  199. to=ContentType,
  200. related_name='custom_links',
  201. help_text=_('The object type(s) to which this link applies.')
  202. )
  203. name = models.CharField(
  204. max_length=100,
  205. unique=True
  206. )
  207. enabled = models.BooleanField(
  208. default=True
  209. )
  210. link_text = models.TextField(
  211. help_text=_("Jinja2 template code for link text")
  212. )
  213. link_url = models.TextField(
  214. verbose_name='Link URL',
  215. help_text=_("Jinja2 template code for link URL")
  216. )
  217. weight = models.PositiveSmallIntegerField(
  218. default=100
  219. )
  220. group_name = models.CharField(
  221. max_length=50,
  222. blank=True,
  223. help_text=_("Links with the same group will appear as a dropdown menu")
  224. )
  225. button_class = models.CharField(
  226. max_length=30,
  227. choices=CustomLinkButtonClassChoices,
  228. default=CustomLinkButtonClassChoices.DEFAULT,
  229. help_text=_("The class of the first link in a group will be used for the dropdown button")
  230. )
  231. new_window = models.BooleanField(
  232. default=False,
  233. help_text=_("Force link to open in a new window")
  234. )
  235. clone_fields = (
  236. 'content_types', 'enabled', 'weight', 'group_name', 'button_class', 'new_window',
  237. )
  238. class Meta:
  239. ordering = ['group_name', 'weight', 'name']
  240. def __str__(self):
  241. return self.name
  242. def get_absolute_url(self):
  243. return reverse('extras:customlink', args=[self.pk])
  244. @property
  245. def docs_url(self):
  246. return f'{settings.STATIC_URL}docs/models/extras/customlink/'
  247. def render(self, context):
  248. """
  249. Render the CustomLink given the provided context, and return the text, link, and link_target.
  250. :param context: The context passed to Jinja2
  251. """
  252. text = render_jinja2(self.link_text, context).strip()
  253. if not text:
  254. return {}
  255. link = render_jinja2(self.link_url, context).strip()
  256. link_target = ' target="_blank"' if self.new_window else ''
  257. # Sanitize link text
  258. allowed_schemes = get_config().ALLOWED_URL_SCHEMES
  259. text = clean_html(text, allowed_schemes)
  260. # Sanitize link
  261. link = urllib.parse.quote(link, safe='/:?&=%+[]@#')
  262. # Verify link scheme is allowed
  263. result = urllib.parse.urlparse(link)
  264. if result.scheme and result.scheme not in allowed_schemes:
  265. link = ""
  266. return {
  267. 'text': text,
  268. 'link': link,
  269. 'link_target': link_target,
  270. }
  271. class ExportTemplate(SyncedDataMixin, CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  272. content_types = models.ManyToManyField(
  273. to=ContentType,
  274. related_name='export_templates',
  275. help_text=_('The object type(s) to which this template applies.')
  276. )
  277. name = models.CharField(
  278. max_length=100
  279. )
  280. description = models.CharField(
  281. max_length=200,
  282. blank=True
  283. )
  284. template_code = models.TextField(
  285. help_text=_('Jinja2 template code. The list of objects being exported is passed as a context variable named '
  286. '<code>queryset</code>.')
  287. )
  288. mime_type = models.CharField(
  289. max_length=50,
  290. blank=True,
  291. verbose_name='MIME type',
  292. help_text=_('Defaults to <code>text/plain; charset=utf-8</code>')
  293. )
  294. file_extension = models.CharField(
  295. max_length=15,
  296. blank=True,
  297. help_text=_('Extension to append to the rendered filename')
  298. )
  299. as_attachment = models.BooleanField(
  300. default=True,
  301. help_text=_("Download file as attachment")
  302. )
  303. clone_fields = (
  304. 'content_types', 'template_code', 'mime_type', 'file_extension', 'as_attachment',
  305. )
  306. class Meta:
  307. ordering = ('name',)
  308. def __str__(self):
  309. return self.name
  310. def get_absolute_url(self):
  311. return reverse('extras:exporttemplate', args=[self.pk])
  312. @property
  313. def docs_url(self):
  314. return f'{settings.STATIC_URL}docs/models/extras/exporttemplate/'
  315. def clean(self):
  316. super().clean()
  317. if self.name.lower() == 'table':
  318. raise ValidationError({
  319. 'name': f'"{self.name}" is a reserved name. Please choose a different name.'
  320. })
  321. def sync_data(self):
  322. """
  323. Synchronize template content from the designated DataFile (if any).
  324. """
  325. self.template_code = self.data_file.data_as_string
  326. sync_data.alters_data = True
  327. def render(self, queryset):
  328. """
  329. Render the contents of the template.
  330. """
  331. context = {
  332. 'queryset': queryset
  333. }
  334. output = render_jinja2(self.template_code, context)
  335. # Replace CRLF-style line terminators
  336. output = output.replace('\r\n', '\n')
  337. return output
  338. def render_to_response(self, queryset):
  339. """
  340. Render the template to an HTTP response, delivered as a named file attachment
  341. """
  342. output = self.render(queryset)
  343. mime_type = 'text/plain; charset=utf-8' if not self.mime_type else self.mime_type
  344. # Build the response
  345. response = HttpResponse(output, content_type=mime_type)
  346. if self.as_attachment:
  347. basename = queryset.model._meta.verbose_name_plural.replace(' ', '_')
  348. extension = f'.{self.file_extension}' if self.file_extension else ''
  349. filename = f'netbox_{basename}{extension}'
  350. response['Content-Disposition'] = f'attachment; filename="{filename}"'
  351. return response
  352. class SavedFilter(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  353. """
  354. A set of predefined keyword parameters that can be reused to filter for specific objects.
  355. """
  356. content_types = models.ManyToManyField(
  357. to=ContentType,
  358. related_name='saved_filters',
  359. help_text=_('The object type(s) to which this filter applies.')
  360. )
  361. name = models.CharField(
  362. max_length=100,
  363. unique=True
  364. )
  365. slug = models.SlugField(
  366. max_length=100,
  367. unique=True
  368. )
  369. description = models.CharField(
  370. max_length=200,
  371. blank=True
  372. )
  373. user = models.ForeignKey(
  374. to=User,
  375. on_delete=models.SET_NULL,
  376. blank=True,
  377. null=True
  378. )
  379. weight = models.PositiveSmallIntegerField(
  380. default=100
  381. )
  382. enabled = models.BooleanField(
  383. default=True
  384. )
  385. shared = models.BooleanField(
  386. default=True
  387. )
  388. parameters = models.JSONField()
  389. clone_fields = (
  390. 'content_types', 'weight', 'enabled', 'parameters',
  391. )
  392. class Meta:
  393. ordering = ('weight', 'name')
  394. def __str__(self):
  395. return self.name
  396. def get_absolute_url(self):
  397. return reverse('extras:savedfilter', args=[self.pk])
  398. @property
  399. def docs_url(self):
  400. return f'{settings.STATIC_URL}docs/models/extras/savedfilter/'
  401. def clean(self):
  402. super().clean()
  403. # Verify that `parameters` is a JSON object
  404. if type(self.parameters) is not dict:
  405. raise ValidationError(
  406. {'parameters': 'Filter parameters must be stored as a dictionary of keyword arguments.'}
  407. )
  408. @property
  409. def url_params(self):
  410. qd = QueryDict(mutable=True)
  411. qd.update(self.parameters)
  412. return qd.urlencode()
  413. class ImageAttachment(ChangeLoggedModel):
  414. """
  415. An uploaded image which is associated with an object.
  416. """
  417. content_type = models.ForeignKey(
  418. to=ContentType,
  419. on_delete=models.CASCADE
  420. )
  421. object_id = models.PositiveBigIntegerField()
  422. parent = GenericForeignKey(
  423. ct_field='content_type',
  424. fk_field='object_id'
  425. )
  426. image = models.ImageField(
  427. upload_to=image_upload,
  428. height_field='image_height',
  429. width_field='image_width'
  430. )
  431. image_height = models.PositiveSmallIntegerField()
  432. image_width = models.PositiveSmallIntegerField()
  433. name = models.CharField(
  434. max_length=50,
  435. blank=True
  436. )
  437. objects = RestrictedQuerySet.as_manager()
  438. clone_fields = ('content_type', 'object_id')
  439. class Meta:
  440. ordering = ('name', 'pk') # name may be non-unique
  441. def __str__(self):
  442. if self.name:
  443. return self.name
  444. filename = self.image.name.rsplit('/', 1)[-1]
  445. return filename.split('_', 2)[2]
  446. def delete(self, *args, **kwargs):
  447. _name = self.image.name
  448. super().delete(*args, **kwargs)
  449. # Delete file from disk
  450. self.image.delete(save=False)
  451. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  452. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  453. self.image.name = _name
  454. @property
  455. def size(self):
  456. """
  457. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  458. catch other exceptions that we know other storage back-ends to throw.
  459. """
  460. expected_exceptions = [OSError]
  461. try:
  462. from botocore.exceptions import ClientError
  463. expected_exceptions.append(ClientError)
  464. except ImportError:
  465. pass
  466. try:
  467. return self.image.size
  468. except tuple(expected_exceptions):
  469. return None
  470. def to_objectchange(self, action):
  471. objectchange = super().to_objectchange(action)
  472. objectchange.related_object = self.parent
  473. return objectchange
  474. class JournalEntry(CustomFieldsMixin, CustomLinksMixin, TagsMixin, ExportTemplatesMixin, ChangeLoggedModel):
  475. """
  476. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  477. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  478. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  479. """
  480. assigned_object_type = models.ForeignKey(
  481. to=ContentType,
  482. on_delete=models.CASCADE
  483. )
  484. assigned_object_id = models.PositiveBigIntegerField()
  485. assigned_object = GenericForeignKey(
  486. ct_field='assigned_object_type',
  487. fk_field='assigned_object_id'
  488. )
  489. created_by = models.ForeignKey(
  490. to=User,
  491. on_delete=models.SET_NULL,
  492. blank=True,
  493. null=True
  494. )
  495. kind = models.CharField(
  496. max_length=30,
  497. choices=JournalEntryKindChoices,
  498. default=JournalEntryKindChoices.KIND_INFO
  499. )
  500. comments = models.TextField()
  501. class Meta:
  502. ordering = ('-created',)
  503. verbose_name_plural = 'journal entries'
  504. def __str__(self):
  505. created = timezone.localtime(self.created)
  506. return f"{date_format(created, format='SHORT_DATETIME_FORMAT')} ({self.get_kind_display()})"
  507. def get_absolute_url(self):
  508. return reverse('extras:journalentry', args=[self.pk])
  509. def clean(self):
  510. super().clean()
  511. # Prevent the creation of journal entries on unsupported models
  512. permitted_types = ContentType.objects.filter(FeatureQuery('journaling').get_query())
  513. if self.assigned_object_type not in permitted_types:
  514. raise ValidationError(f"Journaling is not supported for this object type ({self.assigned_object_type}).")
  515. def get_kind_color(self):
  516. return JournalEntryKindChoices.colors.get(self.kind)
  517. class ConfigRevision(models.Model):
  518. """
  519. An atomic revision of NetBox's configuration.
  520. """
  521. created = models.DateTimeField(
  522. auto_now_add=True
  523. )
  524. comment = models.CharField(
  525. max_length=200,
  526. blank=True
  527. )
  528. data = models.JSONField(
  529. blank=True,
  530. null=True,
  531. verbose_name='Configuration data'
  532. )
  533. def __str__(self):
  534. return f'Config revision #{self.pk} ({self.created})'
  535. def __getattr__(self, item):
  536. if item in self.data:
  537. return self.data[item]
  538. return super().__getattribute__(item)
  539. def activate(self):
  540. """
  541. Cache the configuration data.
  542. """
  543. cache.set('config', self.data, None)
  544. cache.set('config_version', self.pk, None)
  545. activate.alters_data = True
  546. @admin.display(boolean=True)
  547. def is_active(self):
  548. return cache.get('config_version') == self.pk