models.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import json
  2. import uuid
  3. from django.contrib.auth.models import User
  4. from django.contrib.contenttypes.fields import GenericForeignKey
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.validators import ValidationError
  7. from django.db import models
  8. from django.http import HttpResponse
  9. from django.urls import reverse
  10. from django.utils import timezone
  11. from django.utils.formats import date_format
  12. from rest_framework.utils.encoders import JSONEncoder
  13. from extras.choices import *
  14. from extras.constants import *
  15. from extras.conditions import ConditionSet
  16. from extras.utils import extras_features, FeatureQuery, image_upload
  17. from netbox.models import BigIDModel, ChangeLoggedModel
  18. from utilities.querysets import RestrictedQuerySet
  19. from utilities.utils import render_jinja2
  20. __all__ = (
  21. 'CustomLink',
  22. 'ExportTemplate',
  23. 'ImageAttachment',
  24. 'JobResult',
  25. 'JournalEntry',
  26. 'Report',
  27. 'Script',
  28. 'Webhook',
  29. )
  30. #
  31. # Webhooks
  32. #
  33. @extras_features('webhooks')
  34. class Webhook(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="A POST will be sent to this URL when the webhook is called."
  67. )
  68. enabled = models.BooleanField(
  69. default=True
  70. )
  71. http_method = models.CharField(
  72. max_length=30,
  73. choices=WebhookHttpMethodChoices,
  74. default=WebhookHttpMethodChoices.METHOD_POST,
  75. verbose_name='HTTP method'
  76. )
  77. http_content_type = models.CharField(
  78. max_length=100,
  79. default=HTTP_CONTENT_TYPE_JSON,
  80. verbose_name='HTTP content type',
  81. help_text='The complete list of official content types is available '
  82. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.'
  83. )
  84. additional_headers = models.TextField(
  85. blank=True,
  86. help_text="User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. "
  87. "Headers should be defined in the format <code>Name: Value</code>. Jinja2 template processing is "
  88. "supported with the same context as the request body (below)."
  89. )
  90. body_template = models.TextField(
  91. blank=True,
  92. help_text='Jinja2 template for a custom request body. If blank, a JSON object representing the change will be '
  93. 'included. Available context data includes: <code>event</code>, <code>model</code>, '
  94. '<code>timestamp</code>, <code>username</code>, <code>request_id</code>, and <code>data</code>.'
  95. )
  96. secret = models.CharField(
  97. max_length=255,
  98. blank=True,
  99. help_text="When provided, the request will include a 'X-Hook-Signature' "
  100. "header containing a HMAC hex digest of the payload body using "
  101. "the secret as the key. The secret is not transmitted in "
  102. "the request."
  103. )
  104. conditions = models.JSONField(
  105. blank=True,
  106. null=True,
  107. help_text="A set of conditions which determine whether the webhook will be generated."
  108. )
  109. ssl_verification = models.BooleanField(
  110. default=True,
  111. verbose_name='SSL verification',
  112. help_text="Enable SSL certificate verification. Disable with caution!"
  113. )
  114. ca_file_path = models.CharField(
  115. max_length=4096,
  116. null=True,
  117. blank=True,
  118. verbose_name='CA File Path',
  119. help_text='The specific CA certificate file to use for SSL verification. '
  120. 'Leave blank to use the system defaults.'
  121. )
  122. objects = RestrictedQuerySet.as_manager()
  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. #
  166. # Custom links
  167. #
  168. @extras_features('webhooks')
  169. class CustomLink(ChangeLoggedModel):
  170. """
  171. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  172. code to be rendered with an object as context.
  173. """
  174. content_type = models.ForeignKey(
  175. to=ContentType,
  176. on_delete=models.CASCADE,
  177. limit_choices_to=FeatureQuery('custom_links')
  178. )
  179. name = models.CharField(
  180. max_length=100,
  181. unique=True
  182. )
  183. link_text = models.CharField(
  184. max_length=500,
  185. help_text="Jinja2 template code for link text"
  186. )
  187. link_url = models.CharField(
  188. max_length=500,
  189. verbose_name='Link URL',
  190. help_text="Jinja2 template code for link URL"
  191. )
  192. weight = models.PositiveSmallIntegerField(
  193. default=100
  194. )
  195. group_name = models.CharField(
  196. max_length=50,
  197. blank=True,
  198. help_text="Links with the same group will appear as a dropdown menu"
  199. )
  200. button_class = models.CharField(
  201. max_length=30,
  202. choices=CustomLinkButtonClassChoices,
  203. default=CustomLinkButtonClassChoices.CLASS_DEFAULT,
  204. help_text="The class of the first link in a group will be used for the dropdown button"
  205. )
  206. new_window = models.BooleanField(
  207. default=False,
  208. help_text="Force link to open in a new window"
  209. )
  210. objects = RestrictedQuerySet.as_manager()
  211. class Meta:
  212. ordering = ['group_name', 'weight', 'name']
  213. def __str__(self):
  214. return self.name
  215. def get_absolute_url(self):
  216. return reverse('extras:customlink', args=[self.pk])
  217. #
  218. # Export templates
  219. #
  220. @extras_features('webhooks')
  221. class ExportTemplate(ChangeLoggedModel):
  222. content_type = models.ForeignKey(
  223. to=ContentType,
  224. on_delete=models.CASCADE,
  225. limit_choices_to=FeatureQuery('export_templates')
  226. )
  227. name = models.CharField(
  228. max_length=100
  229. )
  230. description = models.CharField(
  231. max_length=200,
  232. blank=True
  233. )
  234. template_code = models.TextField(
  235. help_text='Jinja2 template code. The list of objects being exported is passed as a context variable named '
  236. '<code>queryset</code>.'
  237. )
  238. mime_type = models.CharField(
  239. max_length=50,
  240. blank=True,
  241. verbose_name='MIME type',
  242. help_text='Defaults to <code>text/plain</code>'
  243. )
  244. file_extension = models.CharField(
  245. max_length=15,
  246. blank=True,
  247. help_text='Extension to append to the rendered filename'
  248. )
  249. as_attachment = models.BooleanField(
  250. default=True,
  251. help_text="Download file as attachment"
  252. )
  253. objects = RestrictedQuerySet.as_manager()
  254. class Meta:
  255. ordering = ['content_type', 'name']
  256. unique_together = [
  257. ['content_type', 'name']
  258. ]
  259. def __str__(self):
  260. return f"{self.content_type}: {self.name}"
  261. def get_absolute_url(self):
  262. return reverse('extras:exporttemplate', args=[self.pk])
  263. def clean(self):
  264. super().clean()
  265. if self.name.lower() == 'table':
  266. raise ValidationError({
  267. 'name': f'"{self.name}" is a reserved name. Please choose a different name.'
  268. })
  269. def render(self, queryset):
  270. """
  271. Render the contents of the template.
  272. """
  273. context = {
  274. 'queryset': queryset
  275. }
  276. output = render_jinja2(self.template_code, context)
  277. # Replace CRLF-style line terminators
  278. output = output.replace('\r\n', '\n')
  279. return output
  280. def render_to_response(self, queryset):
  281. """
  282. Render the template to an HTTP response, delivered as a named file attachment
  283. """
  284. output = self.render(queryset)
  285. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  286. # Build the response
  287. response = HttpResponse(output, content_type=mime_type)
  288. if self.as_attachment:
  289. basename = queryset.model._meta.verbose_name_plural.replace(' ', '_')
  290. extension = f'.{self.file_extension}' if self.file_extension else ''
  291. filename = f'netbox_{basename}{extension}'
  292. response['Content-Disposition'] = f'attachment; filename="{filename}"'
  293. return response
  294. #
  295. # Image attachments
  296. #
  297. class ImageAttachment(BigIDModel):
  298. """
  299. An uploaded image which is associated with an object.
  300. """
  301. content_type = models.ForeignKey(
  302. to=ContentType,
  303. on_delete=models.CASCADE
  304. )
  305. object_id = models.PositiveIntegerField()
  306. parent = GenericForeignKey(
  307. ct_field='content_type',
  308. fk_field='object_id'
  309. )
  310. image = models.ImageField(
  311. upload_to=image_upload,
  312. height_field='image_height',
  313. width_field='image_width'
  314. )
  315. image_height = models.PositiveSmallIntegerField()
  316. image_width = models.PositiveSmallIntegerField()
  317. name = models.CharField(
  318. max_length=50,
  319. blank=True
  320. )
  321. created = models.DateTimeField(
  322. auto_now_add=True
  323. )
  324. objects = RestrictedQuerySet.as_manager()
  325. class Meta:
  326. ordering = ('name', 'pk') # name may be non-unique
  327. def __str__(self):
  328. if self.name:
  329. return self.name
  330. filename = self.image.name.rsplit('/', 1)[-1]
  331. return filename.split('_', 2)[2]
  332. def delete(self, *args, **kwargs):
  333. _name = self.image.name
  334. super().delete(*args, **kwargs)
  335. # Delete file from disk
  336. self.image.delete(save=False)
  337. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  338. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  339. self.image.name = _name
  340. @property
  341. def size(self):
  342. """
  343. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  344. catch other exceptions that we know other storage back-ends to throw.
  345. """
  346. expected_exceptions = [OSError]
  347. try:
  348. from botocore.exceptions import ClientError
  349. expected_exceptions.append(ClientError)
  350. except ImportError:
  351. pass
  352. try:
  353. return self.image.size
  354. except tuple(expected_exceptions):
  355. return None
  356. #
  357. # Journal entries
  358. #
  359. @extras_features('webhooks')
  360. class JournalEntry(ChangeLoggedModel):
  361. """
  362. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  363. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  364. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  365. """
  366. assigned_object_type = models.ForeignKey(
  367. to=ContentType,
  368. on_delete=models.CASCADE
  369. )
  370. assigned_object_id = models.PositiveIntegerField()
  371. assigned_object = GenericForeignKey(
  372. ct_field='assigned_object_type',
  373. fk_field='assigned_object_id'
  374. )
  375. created = models.DateTimeField(
  376. auto_now_add=True
  377. )
  378. created_by = models.ForeignKey(
  379. to=User,
  380. on_delete=models.SET_NULL,
  381. blank=True,
  382. null=True
  383. )
  384. kind = models.CharField(
  385. max_length=30,
  386. choices=JournalEntryKindChoices,
  387. default=JournalEntryKindChoices.KIND_INFO
  388. )
  389. comments = models.TextField()
  390. objects = RestrictedQuerySet.as_manager()
  391. class Meta:
  392. ordering = ('-created',)
  393. verbose_name_plural = 'journal entries'
  394. def __str__(self):
  395. created = timezone.localtime(self.created)
  396. return f"{date_format(created, format='SHORT_DATETIME_FORMAT')} ({self.get_kind_display()})"
  397. def get_absolute_url(self):
  398. return reverse('extras:journalentry', args=[self.pk])
  399. def get_kind_class(self):
  400. return JournalEntryKindChoices.CSS_CLASSES.get(self.kind)
  401. #
  402. # Custom scripts
  403. #
  404. @extras_features('job_results')
  405. class Script(models.Model):
  406. """
  407. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  408. """
  409. class Meta:
  410. managed = False
  411. #
  412. # Reports
  413. #
  414. @extras_features('job_results')
  415. class Report(models.Model):
  416. """
  417. Dummy model used to generate permissions for reports. Does not exist in the database.
  418. """
  419. class Meta:
  420. managed = False
  421. #
  422. # Job results
  423. #
  424. class JobResult(BigIDModel):
  425. """
  426. This model stores the results from running a user-defined report.
  427. """
  428. name = models.CharField(
  429. max_length=255
  430. )
  431. obj_type = models.ForeignKey(
  432. to=ContentType,
  433. related_name='job_results',
  434. verbose_name='Object types',
  435. limit_choices_to=FeatureQuery('job_results'),
  436. help_text="The object type to which this job result applies",
  437. on_delete=models.CASCADE,
  438. )
  439. created = models.DateTimeField(
  440. auto_now_add=True
  441. )
  442. completed = models.DateTimeField(
  443. null=True,
  444. blank=True
  445. )
  446. user = models.ForeignKey(
  447. to=User,
  448. on_delete=models.SET_NULL,
  449. related_name='+',
  450. blank=True,
  451. null=True
  452. )
  453. status = models.CharField(
  454. max_length=30,
  455. choices=JobResultStatusChoices,
  456. default=JobResultStatusChoices.STATUS_PENDING
  457. )
  458. data = models.JSONField(
  459. null=True,
  460. blank=True
  461. )
  462. job_id = models.UUIDField(
  463. unique=True
  464. )
  465. class Meta:
  466. ordering = ['obj_type', 'name', '-created']
  467. def __str__(self):
  468. return str(self.job_id)
  469. @property
  470. def duration(self):
  471. if not self.completed:
  472. return None
  473. duration = self.completed - self.created
  474. minutes, seconds = divmod(duration.total_seconds(), 60)
  475. return f"{int(minutes)} minutes, {seconds:.2f} seconds"
  476. def set_status(self, status):
  477. """
  478. Helper method to change the status of the job result. If the target status is terminal, the completion
  479. time is also set.
  480. """
  481. self.status = status
  482. if status in JobResultStatusChoices.TERMINAL_STATE_CHOICES:
  483. self.completed = timezone.now()
  484. @classmethod
  485. def enqueue_job(cls, func, name, obj_type, user, *args, **kwargs):
  486. """
  487. Create a JobResult instance and enqueue a job using the given callable
  488. func: The callable object to be enqueued for execution
  489. name: Name for the JobResult instance
  490. obj_type: ContentType to link to the JobResult instance obj_type
  491. user: User object to link to the JobResult instance
  492. args: additional args passed to the callable
  493. kwargs: additional kargs passed to the callable
  494. """
  495. job_result = cls.objects.create(
  496. name=name,
  497. obj_type=obj_type,
  498. user=user,
  499. job_id=uuid.uuid4()
  500. )
  501. func.delay(*args, job_id=str(job_result.job_id), job_result=job_result, **kwargs)
  502. return job_result