models.py 20 KB

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