models.py 20 KB

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