models.py 19 KB

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