models.py 21 KB

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