models.py 16 KB

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