models.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 extras_features, FeatureQuery, image_upload
  19. from netbox.models import BigIDModel, ChangeLoggedModel
  20. from utilities.querysets import RestrictedQuerySet
  21. from utilities.utils import render_jinja2
  22. __all__ = (
  23. 'ConfigRevision',
  24. 'CustomLink',
  25. 'ExportTemplate',
  26. 'ImageAttachment',
  27. 'JobResult',
  28. 'JournalEntry',
  29. 'Report',
  30. 'Script',
  31. 'Webhook',
  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. @extras_features('webhooks')
  166. class CustomLink(ChangeLoggedModel):
  167. """
  168. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  169. code to be rendered with an object as context.
  170. """
  171. content_type = models.ForeignKey(
  172. to=ContentType,
  173. on_delete=models.CASCADE,
  174. limit_choices_to=FeatureQuery('custom_links')
  175. )
  176. name = models.CharField(
  177. max_length=100,
  178. unique=True
  179. )
  180. link_text = models.CharField(
  181. max_length=500,
  182. help_text="Jinja2 template code for link text"
  183. )
  184. link_url = models.CharField(
  185. max_length=500,
  186. verbose_name='Link URL',
  187. help_text="Jinja2 template code for link URL"
  188. )
  189. weight = models.PositiveSmallIntegerField(
  190. default=100
  191. )
  192. group_name = models.CharField(
  193. max_length=50,
  194. blank=True,
  195. help_text="Links with the same group will appear as a dropdown menu"
  196. )
  197. button_class = models.CharField(
  198. max_length=30,
  199. choices=CustomLinkButtonClassChoices,
  200. default=CustomLinkButtonClassChoices.CLASS_DEFAULT,
  201. help_text="The class of the first link in a group will be used for the dropdown button"
  202. )
  203. new_window = models.BooleanField(
  204. default=False,
  205. help_text="Force link to open in a new window"
  206. )
  207. objects = RestrictedQuerySet.as_manager()
  208. class Meta:
  209. ordering = ['group_name', 'weight', 'name']
  210. def __str__(self):
  211. return self.name
  212. def get_absolute_url(self):
  213. return reverse('extras:customlink', args=[self.pk])
  214. @extras_features('webhooks')
  215. class ExportTemplate(ChangeLoggedModel):
  216. content_type = models.ForeignKey(
  217. to=ContentType,
  218. on_delete=models.CASCADE,
  219. limit_choices_to=FeatureQuery('export_templates')
  220. )
  221. name = models.CharField(
  222. max_length=100
  223. )
  224. description = models.CharField(
  225. max_length=200,
  226. blank=True
  227. )
  228. template_code = models.TextField(
  229. help_text='Jinja2 template code. The list of objects being exported is passed as a context variable named '
  230. '<code>queryset</code>.'
  231. )
  232. mime_type = models.CharField(
  233. max_length=50,
  234. blank=True,
  235. verbose_name='MIME type',
  236. help_text='Defaults to <code>text/plain</code>'
  237. )
  238. file_extension = models.CharField(
  239. max_length=15,
  240. blank=True,
  241. help_text='Extension to append to the rendered filename'
  242. )
  243. as_attachment = models.BooleanField(
  244. default=True,
  245. help_text="Download file as attachment"
  246. )
  247. objects = RestrictedQuerySet.as_manager()
  248. class Meta:
  249. ordering = ['content_type', 'name']
  250. unique_together = [
  251. ['content_type', 'name']
  252. ]
  253. def __str__(self):
  254. return f"{self.content_type}: {self.name}"
  255. def get_absolute_url(self):
  256. return reverse('extras:exporttemplate', args=[self.pk])
  257. def clean(self):
  258. super().clean()
  259. if self.name.lower() == 'table':
  260. raise ValidationError({
  261. 'name': f'"{self.name}" is a reserved name. Please choose a different name.'
  262. })
  263. def render(self, queryset):
  264. """
  265. Render the contents of the template.
  266. """
  267. context = {
  268. 'queryset': queryset
  269. }
  270. output = render_jinja2(self.template_code, context)
  271. # Replace CRLF-style line terminators
  272. output = output.replace('\r\n', '\n')
  273. return output
  274. def render_to_response(self, queryset):
  275. """
  276. Render the template to an HTTP response, delivered as a named file attachment
  277. """
  278. output = self.render(queryset)
  279. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  280. # Build the response
  281. response = HttpResponse(output, content_type=mime_type)
  282. if self.as_attachment:
  283. basename = queryset.model._meta.verbose_name_plural.replace(' ', '_')
  284. extension = f'.{self.file_extension}' if self.file_extension else ''
  285. filename = f'netbox_{basename}{extension}'
  286. response['Content-Disposition'] = f'attachment; filename="{filename}"'
  287. return response
  288. class ImageAttachment(BigIDModel):
  289. """
  290. An uploaded image which is associated with an object.
  291. """
  292. content_type = models.ForeignKey(
  293. to=ContentType,
  294. on_delete=models.CASCADE
  295. )
  296. object_id = models.PositiveIntegerField()
  297. parent = GenericForeignKey(
  298. ct_field='content_type',
  299. fk_field='object_id'
  300. )
  301. image = models.ImageField(
  302. upload_to=image_upload,
  303. height_field='image_height',
  304. width_field='image_width'
  305. )
  306. image_height = models.PositiveSmallIntegerField()
  307. image_width = models.PositiveSmallIntegerField()
  308. name = models.CharField(
  309. max_length=50,
  310. blank=True
  311. )
  312. created = models.DateTimeField(
  313. auto_now_add=True
  314. )
  315. objects = RestrictedQuerySet.as_manager()
  316. class Meta:
  317. ordering = ('name', 'pk') # name may be non-unique
  318. def __str__(self):
  319. if self.name:
  320. return self.name
  321. filename = self.image.name.rsplit('/', 1)[-1]
  322. return filename.split('_', 2)[2]
  323. def delete(self, *args, **kwargs):
  324. _name = self.image.name
  325. super().delete(*args, **kwargs)
  326. # Delete file from disk
  327. self.image.delete(save=False)
  328. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  329. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  330. self.image.name = _name
  331. @property
  332. def size(self):
  333. """
  334. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  335. catch other exceptions that we know other storage back-ends to throw.
  336. """
  337. expected_exceptions = [OSError]
  338. try:
  339. from botocore.exceptions import ClientError
  340. expected_exceptions.append(ClientError)
  341. except ImportError:
  342. pass
  343. try:
  344. return self.image.size
  345. except tuple(expected_exceptions):
  346. return None
  347. @extras_features('webhooks')
  348. class JournalEntry(ChangeLoggedModel):
  349. """
  350. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  351. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  352. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  353. """
  354. assigned_object_type = models.ForeignKey(
  355. to=ContentType,
  356. on_delete=models.CASCADE
  357. )
  358. assigned_object_id = models.PositiveIntegerField()
  359. assigned_object = GenericForeignKey(
  360. ct_field='assigned_object_type',
  361. fk_field='assigned_object_id'
  362. )
  363. created = models.DateTimeField(
  364. auto_now_add=True
  365. )
  366. created_by = models.ForeignKey(
  367. to=User,
  368. on_delete=models.SET_NULL,
  369. blank=True,
  370. null=True
  371. )
  372. kind = models.CharField(
  373. max_length=30,
  374. choices=JournalEntryKindChoices,
  375. default=JournalEntryKindChoices.KIND_INFO
  376. )
  377. comments = models.TextField()
  378. objects = RestrictedQuerySet.as_manager()
  379. class Meta:
  380. ordering = ('-created',)
  381. verbose_name_plural = 'journal entries'
  382. def __str__(self):
  383. created = timezone.localtime(self.created)
  384. return f"{date_format(created, format='SHORT_DATETIME_FORMAT')} ({self.get_kind_display()})"
  385. def get_absolute_url(self):
  386. return reverse('extras:journalentry', args=[self.pk])
  387. def get_kind_class(self):
  388. return JournalEntryKindChoices.CSS_CLASSES.get(self.kind)
  389. class JobResult(BigIDModel):
  390. """
  391. This model stores the results from running a user-defined report.
  392. """
  393. name = models.CharField(
  394. max_length=255
  395. )
  396. obj_type = models.ForeignKey(
  397. to=ContentType,
  398. related_name='job_results',
  399. verbose_name='Object types',
  400. limit_choices_to=FeatureQuery('job_results'),
  401. help_text="The object type to which this job result applies",
  402. on_delete=models.CASCADE,
  403. )
  404. created = models.DateTimeField(
  405. auto_now_add=True
  406. )
  407. completed = models.DateTimeField(
  408. null=True,
  409. blank=True
  410. )
  411. user = models.ForeignKey(
  412. to=User,
  413. on_delete=models.SET_NULL,
  414. related_name='+',
  415. blank=True,
  416. null=True
  417. )
  418. status = models.CharField(
  419. max_length=30,
  420. choices=JobResultStatusChoices,
  421. default=JobResultStatusChoices.STATUS_PENDING
  422. )
  423. data = models.JSONField(
  424. null=True,
  425. blank=True
  426. )
  427. job_id = models.UUIDField(
  428. unique=True
  429. )
  430. class Meta:
  431. ordering = ['obj_type', 'name', '-created']
  432. def __str__(self):
  433. return str(self.job_id)
  434. @property
  435. def duration(self):
  436. if not self.completed:
  437. return None
  438. duration = self.completed - self.created
  439. minutes, seconds = divmod(duration.total_seconds(), 60)
  440. return f"{int(minutes)} minutes, {seconds:.2f} seconds"
  441. def set_status(self, status):
  442. """
  443. Helper method to change the status of the job result. If the target status is terminal, the completion
  444. time is also set.
  445. """
  446. self.status = status
  447. if status in JobResultStatusChoices.TERMINAL_STATE_CHOICES:
  448. self.completed = timezone.now()
  449. @classmethod
  450. def enqueue_job(cls, func, name, obj_type, user, *args, **kwargs):
  451. """
  452. Create a JobResult instance and enqueue a job using the given callable
  453. func: The callable object to be enqueued for execution
  454. name: Name for the JobResult instance
  455. obj_type: ContentType to link to the JobResult instance obj_type
  456. user: User object to link to the JobResult instance
  457. args: additional args passed to the callable
  458. kwargs: additional kargs passed to the callable
  459. """
  460. job_result = cls.objects.create(
  461. name=name,
  462. obj_type=obj_type,
  463. user=user,
  464. job_id=uuid.uuid4()
  465. )
  466. func.delay(*args, job_id=str(job_result.job_id), job_result=job_result, **kwargs)
  467. return job_result
  468. class ConfigRevision(models.Model):
  469. """
  470. An atomic revision of NetBox's configuration.
  471. """
  472. created = models.DateTimeField(
  473. auto_now_add=True
  474. )
  475. comment = models.CharField(
  476. max_length=200,
  477. blank=True
  478. )
  479. data = models.JSONField(
  480. blank=True,
  481. null=True,
  482. verbose_name='Configuration data'
  483. )
  484. def __str__(self):
  485. return f'Config revision #{self.pk} ({self.created})'
  486. def __getattr__(self, item):
  487. if item in self.data:
  488. return self.data[item]
  489. return super().__getattribute__(item)
  490. @admin.display(boolean=True)
  491. def is_active(self):
  492. return cache.get('config_version') == self.pk
  493. #
  494. # Custom scripts & reports
  495. #
  496. @extras_features('job_results')
  497. class Script(models.Model):
  498. """
  499. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  500. """
  501. class Meta:
  502. managed = False
  503. #
  504. # Reports
  505. #
  506. @extras_features('job_results')
  507. class Report(models.Model):
  508. """
  509. Dummy model used to generate permissions for reports. Does not exist in the database.
  510. """
  511. class Meta:
  512. managed = False