models.py 17 KB

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