models.py 19 KB

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