models.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. import json
  2. import uuid
  3. from collections import OrderedDict
  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.validators import ValidationError
  8. from django.db import models
  9. from django.http import HttpResponse
  10. from django.urls import reverse
  11. from django.utils import timezone
  12. from rest_framework.utils.encoders import JSONEncoder
  13. from extras.choices import *
  14. from extras.constants import *
  15. from extras.querysets import ConfigContextQuerySet
  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 deepmerge, render_jinja2
  20. __all__ = (
  21. 'ConfigContext',
  22. 'ConfigContextModel',
  23. 'CustomLink',
  24. 'ExportTemplate',
  25. 'ImageAttachment',
  26. 'JobResult',
  27. 'Report',
  28. 'Script',
  29. 'Webhook',
  30. )
  31. #
  32. # Webhooks
  33. #
  34. class Webhook(BigIDModel):
  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. "support 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. ssl_verification = models.BooleanField(
  105. default=True,
  106. verbose_name='SSL verification',
  107. help_text="Enable SSL certificate verification. Disable with caution!"
  108. )
  109. ca_file_path = models.CharField(
  110. max_length=4096,
  111. null=True,
  112. blank=True,
  113. verbose_name='CA File Path',
  114. help_text='The specific CA certificate file to use for SSL verification. '
  115. 'Leave blank to use the system defaults.'
  116. )
  117. objects = RestrictedQuerySet.as_manager()
  118. class Meta:
  119. ordering = ('name',)
  120. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  121. def __str__(self):
  122. return self.name
  123. def clean(self):
  124. super().clean()
  125. # At least one action type must be selected
  126. if not self.type_create and not self.type_delete and not self.type_update:
  127. raise ValidationError(
  128. "You must select at least one type: create, update, and/or delete."
  129. )
  130. # CA file path requires SSL verification enabled
  131. if not self.ssl_verification and self.ca_file_path:
  132. raise ValidationError({
  133. 'ca_file_path': 'Do not specify a CA certificate file if SSL verification is disabled.'
  134. })
  135. def render_headers(self, context):
  136. """
  137. Render additional_headers and return a dict of Header: Value pairs.
  138. """
  139. if not self.additional_headers:
  140. return {}
  141. ret = {}
  142. data = render_jinja2(self.additional_headers, context)
  143. for line in data.splitlines():
  144. header, value = line.split(':')
  145. ret[header.strip()] = value.strip()
  146. return ret
  147. def render_body(self, context):
  148. """
  149. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  150. """
  151. if self.body_template:
  152. return render_jinja2(self.body_template, context)
  153. else:
  154. return json.dumps(context, cls=JSONEncoder)
  155. #
  156. # Custom links
  157. #
  158. class CustomLink(BigIDModel):
  159. """
  160. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  161. code to be rendered with an object as context.
  162. """
  163. content_type = models.ForeignKey(
  164. to=ContentType,
  165. on_delete=models.CASCADE,
  166. limit_choices_to=FeatureQuery('custom_links')
  167. )
  168. name = models.CharField(
  169. max_length=100,
  170. unique=True
  171. )
  172. link_text = models.CharField(
  173. max_length=500,
  174. help_text="Jinja2 template code for link text"
  175. )
  176. link_url = models.CharField(
  177. max_length=500,
  178. verbose_name='Link URL',
  179. help_text="Jinja2 template code for link URL"
  180. )
  181. weight = models.PositiveSmallIntegerField(
  182. default=100
  183. )
  184. group_name = models.CharField(
  185. max_length=50,
  186. blank=True,
  187. help_text="Links with the same group will appear as a dropdown menu"
  188. )
  189. button_class = models.CharField(
  190. max_length=30,
  191. choices=CustomLinkButtonClassChoices,
  192. default=CustomLinkButtonClassChoices.CLASS_DEFAULT,
  193. help_text="The class of the first link in a group will be used for the dropdown button"
  194. )
  195. new_window = models.BooleanField(
  196. default=False,
  197. help_text="Force link to open in a new window"
  198. )
  199. objects = RestrictedQuerySet.as_manager()
  200. class Meta:
  201. ordering = ['group_name', 'weight', 'name']
  202. def __str__(self):
  203. return self.name
  204. #
  205. # Export templates
  206. #
  207. class ExportTemplate(BigIDModel):
  208. content_type = models.ForeignKey(
  209. to=ContentType,
  210. on_delete=models.CASCADE,
  211. limit_choices_to=FeatureQuery('export_templates')
  212. )
  213. name = models.CharField(
  214. max_length=100
  215. )
  216. description = models.CharField(
  217. max_length=200,
  218. blank=True
  219. )
  220. template_code = models.TextField(
  221. help_text='The list of objects being exported is passed as a context variable named <code>queryset</code>.'
  222. )
  223. mime_type = models.CharField(
  224. max_length=50,
  225. blank=True,
  226. verbose_name='MIME type',
  227. help_text='Defaults to <code>text/plain</code>'
  228. )
  229. file_extension = models.CharField(
  230. max_length=15,
  231. blank=True,
  232. help_text='Extension to append to the rendered filename'
  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 '{}: {}'.format(self.content_type, self.name)
  242. def render(self, queryset):
  243. """
  244. Render the contents of the template.
  245. """
  246. context = {
  247. 'queryset': queryset
  248. }
  249. output = render_jinja2(self.template_code, context)
  250. # Replace CRLF-style line terminators
  251. output = output.replace('\r\n', '\n')
  252. return output
  253. def render_to_response(self, queryset):
  254. """
  255. Render the template to an HTTP response, delivered as a named file attachment
  256. """
  257. output = self.render(queryset)
  258. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  259. # Build the response
  260. response = HttpResponse(output, content_type=mime_type)
  261. filename = 'netbox_{}{}'.format(
  262. queryset.model._meta.verbose_name_plural,
  263. '.{}'.format(self.file_extension) if self.file_extension else ''
  264. )
  265. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  266. return response
  267. #
  268. # Image attachments
  269. #
  270. class ImageAttachment(BigIDModel):
  271. """
  272. An uploaded image which is associated with an object.
  273. """
  274. content_type = models.ForeignKey(
  275. to=ContentType,
  276. on_delete=models.CASCADE
  277. )
  278. object_id = models.PositiveIntegerField()
  279. parent = GenericForeignKey(
  280. ct_field='content_type',
  281. fk_field='object_id'
  282. )
  283. image = models.ImageField(
  284. upload_to=image_upload,
  285. height_field='image_height',
  286. width_field='image_width'
  287. )
  288. image_height = models.PositiveSmallIntegerField()
  289. image_width = models.PositiveSmallIntegerField()
  290. name = models.CharField(
  291. max_length=50,
  292. blank=True
  293. )
  294. created = models.DateTimeField(
  295. auto_now_add=True
  296. )
  297. objects = RestrictedQuerySet.as_manager()
  298. class Meta:
  299. ordering = ('name', 'pk') # name may be non-unique
  300. def __str__(self):
  301. if self.name:
  302. return self.name
  303. filename = self.image.name.rsplit('/', 1)[-1]
  304. return filename.split('_', 2)[2]
  305. def delete(self, *args, **kwargs):
  306. _name = self.image.name
  307. super().delete(*args, **kwargs)
  308. # Delete file from disk
  309. self.image.delete(save=False)
  310. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  311. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  312. self.image.name = _name
  313. @property
  314. def size(self):
  315. """
  316. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  317. catch other exceptions that we know other storage back-ends to throw.
  318. """
  319. expected_exceptions = [OSError]
  320. try:
  321. from botocore.exceptions import ClientError
  322. expected_exceptions.append(ClientError)
  323. except ImportError:
  324. pass
  325. try:
  326. return self.image.size
  327. except tuple(expected_exceptions):
  328. return None
  329. #
  330. # Config contexts
  331. #
  332. @extras_features('webhooks')
  333. class ConfigContext(ChangeLoggedModel):
  334. """
  335. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  336. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  337. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  338. """
  339. name = models.CharField(
  340. max_length=100,
  341. unique=True
  342. )
  343. weight = models.PositiveSmallIntegerField(
  344. default=1000
  345. )
  346. description = models.CharField(
  347. max_length=200,
  348. blank=True
  349. )
  350. is_active = models.BooleanField(
  351. default=True,
  352. )
  353. regions = models.ManyToManyField(
  354. to='dcim.Region',
  355. related_name='+',
  356. blank=True
  357. )
  358. site_groups = models.ManyToManyField(
  359. to='dcim.SiteGroup',
  360. related_name='+',
  361. blank=True
  362. )
  363. sites = models.ManyToManyField(
  364. to='dcim.Site',
  365. related_name='+',
  366. blank=True
  367. )
  368. roles = models.ManyToManyField(
  369. to='dcim.DeviceRole',
  370. related_name='+',
  371. blank=True
  372. )
  373. platforms = models.ManyToManyField(
  374. to='dcim.Platform',
  375. related_name='+',
  376. blank=True
  377. )
  378. cluster_groups = models.ManyToManyField(
  379. to='virtualization.ClusterGroup',
  380. related_name='+',
  381. blank=True
  382. )
  383. clusters = models.ManyToManyField(
  384. to='virtualization.Cluster',
  385. related_name='+',
  386. blank=True
  387. )
  388. tenant_groups = models.ManyToManyField(
  389. to='tenancy.TenantGroup',
  390. related_name='+',
  391. blank=True
  392. )
  393. tenants = models.ManyToManyField(
  394. to='tenancy.Tenant',
  395. related_name='+',
  396. blank=True
  397. )
  398. tags = models.ManyToManyField(
  399. to='extras.Tag',
  400. related_name='+',
  401. blank=True
  402. )
  403. data = models.JSONField()
  404. objects = ConfigContextQuerySet.as_manager()
  405. class Meta:
  406. ordering = ['weight', 'name']
  407. def __str__(self):
  408. return self.name
  409. def get_absolute_url(self):
  410. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  411. def clean(self):
  412. super().clean()
  413. # Verify that JSON data is provided as an object
  414. if type(self.data) is not dict:
  415. raise ValidationError(
  416. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  417. )
  418. class ConfigContextModel(models.Model):
  419. """
  420. A model which includes local configuration context data. This local data will override any inherited data from
  421. ConfigContexts.
  422. """
  423. local_context_data = models.JSONField(
  424. blank=True,
  425. null=True,
  426. )
  427. class Meta:
  428. abstract = True
  429. def get_config_context(self):
  430. """
  431. Return the rendered configuration context for a device or VM.
  432. """
  433. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  434. data = OrderedDict()
  435. if not hasattr(self, 'config_context_data'):
  436. # The annotation is not available, so we fall back to manually querying for the config context objects
  437. config_context_data = ConfigContext.objects.get_for_object(self, aggregate_data=True)
  438. else:
  439. # The attribute may exist, but the annotated value could be None if there is no config context data
  440. config_context_data = self.config_context_data or []
  441. for context in config_context_data:
  442. data = deepmerge(data, context)
  443. # If the object has local config context data defined, merge it last
  444. if self.local_context_data:
  445. data = deepmerge(data, self.local_context_data)
  446. return data
  447. def clean(self):
  448. super().clean()
  449. # Verify that JSON data is provided as an object
  450. if self.local_context_data and type(self.local_context_data) is not dict:
  451. raise ValidationError(
  452. {'local_context_data': 'JSON data must be in object form. Example: {"foo": 123}'}
  453. )
  454. #
  455. # Custom scripts
  456. #
  457. @extras_features('job_results')
  458. class Script(models.Model):
  459. """
  460. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  461. """
  462. class Meta:
  463. managed = False
  464. #
  465. # Reports
  466. #
  467. @extras_features('job_results')
  468. class Report(models.Model):
  469. """
  470. Dummy model used to generate permissions for reports. Does not exist in the database.
  471. """
  472. class Meta:
  473. managed = False
  474. #
  475. # Job results
  476. #
  477. class JobResult(BigIDModel):
  478. """
  479. This model stores the results from running a user-defined report.
  480. """
  481. name = models.CharField(
  482. max_length=255
  483. )
  484. obj_type = models.ForeignKey(
  485. to=ContentType,
  486. related_name='job_results',
  487. verbose_name='Object types',
  488. limit_choices_to=FeatureQuery('job_results'),
  489. help_text="The object type to which this job result applies",
  490. on_delete=models.CASCADE,
  491. )
  492. created = models.DateTimeField(
  493. auto_now_add=True
  494. )
  495. completed = models.DateTimeField(
  496. null=True,
  497. blank=True
  498. )
  499. user = models.ForeignKey(
  500. to=User,
  501. on_delete=models.SET_NULL,
  502. related_name='+',
  503. blank=True,
  504. null=True
  505. )
  506. status = models.CharField(
  507. max_length=30,
  508. choices=JobResultStatusChoices,
  509. default=JobResultStatusChoices.STATUS_PENDING
  510. )
  511. data = models.JSONField(
  512. null=True,
  513. blank=True
  514. )
  515. job_id = models.UUIDField(
  516. unique=True
  517. )
  518. class Meta:
  519. ordering = ['obj_type', 'name', '-created']
  520. def __str__(self):
  521. return str(self.job_id)
  522. @property
  523. def duration(self):
  524. if not self.completed:
  525. return None
  526. duration = self.completed - self.created
  527. minutes, seconds = divmod(duration.total_seconds(), 60)
  528. return f"{int(minutes)} minutes, {seconds:.2f} seconds"
  529. def set_status(self, status):
  530. """
  531. Helper method to change the status of the job result. If the target status is terminal, the completion
  532. time is also set.
  533. """
  534. self.status = status
  535. if status in JobResultStatusChoices.TERMINAL_STATE_CHOICES:
  536. self.completed = timezone.now()
  537. @classmethod
  538. def enqueue_job(cls, func, name, obj_type, user, *args, **kwargs):
  539. """
  540. Create a JobResult instance and enqueue a job using the given callable
  541. func: The callable object to be enqueued for execution
  542. name: Name for the JobResult instance
  543. obj_type: ContentType to link to the JobResult instance obj_type
  544. user: User object to link to the JobResult instance
  545. args: additional args passed to the callable
  546. kwargs: additional kargs passed to the callable
  547. """
  548. job_result = cls.objects.create(
  549. name=name,
  550. obj_type=obj_type,
  551. user=user,
  552. job_id=uuid.uuid4()
  553. )
  554. func.delay(*args, job_id=str(job_result.job_id), job_result=job_result, **kwargs)
  555. return job_result