models.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. import json
  2. import uuid
  3. from collections import OrderedDict
  4. import django_rq
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericForeignKey
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.postgres.fields import JSONField
  9. from django.core.validators import ValidationError
  10. from django.db import models
  11. from django.http import HttpResponse
  12. from django.template import Template, Context
  13. from django.urls import reverse
  14. from rest_framework.utils.encoders import JSONEncoder
  15. from utilities.querysets import RestrictedQuerySet
  16. from utilities.utils import deepmerge, render_jinja2
  17. from extras.choices import *
  18. from extras.constants import *
  19. from extras.querysets import ConfigContextQuerySet
  20. from extras.utils import extras_features, FeatureQuery, image_upload
  21. #
  22. # Webhooks
  23. #
  24. class Webhook(models.Model):
  25. """
  26. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  27. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  28. Each Webhook can be limited to firing only on certain actions or certain object types.
  29. """
  30. obj_type = models.ManyToManyField(
  31. to=ContentType,
  32. related_name='webhooks',
  33. verbose_name='Object types',
  34. limit_choices_to=FeatureQuery('webhooks'),
  35. help_text="The object(s) to which this Webhook applies."
  36. )
  37. name = models.CharField(
  38. max_length=150,
  39. unique=True
  40. )
  41. type_create = models.BooleanField(
  42. default=False,
  43. help_text="Call this webhook when a matching object is created."
  44. )
  45. type_update = models.BooleanField(
  46. default=False,
  47. help_text="Call this webhook when a matching object is updated."
  48. )
  49. type_delete = models.BooleanField(
  50. default=False,
  51. help_text="Call this webhook when a matching object is deleted."
  52. )
  53. payload_url = models.CharField(
  54. max_length=500,
  55. verbose_name='URL',
  56. help_text="A POST will be sent to this URL when the webhook is called."
  57. )
  58. enabled = models.BooleanField(
  59. default=True
  60. )
  61. http_method = models.CharField(
  62. max_length=30,
  63. choices=WebhookHttpMethodChoices,
  64. default=WebhookHttpMethodChoices.METHOD_POST,
  65. verbose_name='HTTP method'
  66. )
  67. http_content_type = models.CharField(
  68. max_length=100,
  69. default=HTTP_CONTENT_TYPE_JSON,
  70. verbose_name='HTTP content type',
  71. help_text='The complete list of official content types is available '
  72. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.'
  73. )
  74. additional_headers = models.TextField(
  75. blank=True,
  76. help_text="User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. "
  77. "Headers should be defined in the format <code>Name: Value</code>. Jinja2 template processing is "
  78. "support with the same context as the request body (below)."
  79. )
  80. body_template = models.TextField(
  81. blank=True,
  82. help_text='Jinja2 template for a custom request body. If blank, a JSON object representing the change will be '
  83. 'included. Available context data includes: <code>event</code>, <code>model</code>, '
  84. '<code>timestamp</code>, <code>username</code>, <code>request_id</code>, and <code>data</code>.'
  85. )
  86. secret = models.CharField(
  87. max_length=255,
  88. blank=True,
  89. help_text="When provided, the request will include a 'X-Hook-Signature' "
  90. "header containing a HMAC hex digest of the payload body using "
  91. "the secret as the key. The secret is not transmitted in "
  92. "the request."
  93. )
  94. ssl_verification = models.BooleanField(
  95. default=True,
  96. verbose_name='SSL verification',
  97. help_text="Enable SSL certificate verification. Disable with caution!"
  98. )
  99. ca_file_path = models.CharField(
  100. max_length=4096,
  101. null=True,
  102. blank=True,
  103. verbose_name='CA File Path',
  104. help_text='The specific CA certificate file to use for SSL verification. '
  105. 'Leave blank to use the system defaults.'
  106. )
  107. class Meta:
  108. ordering = ('name',)
  109. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  110. def __str__(self):
  111. return self.name
  112. def clean(self):
  113. if not self.type_create and not self.type_delete and not self.type_update:
  114. raise ValidationError(
  115. "You must select at least one type: create, update, and/or delete."
  116. )
  117. if not self.ssl_verification and self.ca_file_path:
  118. raise ValidationError({
  119. 'ca_file_path': 'Do not specify a CA certificate file if SSL verification is disabled.'
  120. })
  121. def render_headers(self, context):
  122. """
  123. Render additional_headers and return a dict of Header: Value pairs.
  124. """
  125. if not self.additional_headers:
  126. return {}
  127. ret = {}
  128. data = render_jinja2(self.additional_headers, context)
  129. for line in data.splitlines():
  130. header, value = line.split(':')
  131. ret[header.strip()] = value.strip()
  132. return ret
  133. def render_body(self, context):
  134. """
  135. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  136. """
  137. if self.body_template:
  138. return render_jinja2(self.body_template, context)
  139. else:
  140. return json.dumps(context, cls=JSONEncoder)
  141. #
  142. # Custom links
  143. #
  144. class CustomLink(models.Model):
  145. """
  146. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  147. code to be rendered with an object as context.
  148. """
  149. content_type = models.ForeignKey(
  150. to=ContentType,
  151. on_delete=models.CASCADE,
  152. limit_choices_to=FeatureQuery('custom_links')
  153. )
  154. name = models.CharField(
  155. max_length=100,
  156. unique=True
  157. )
  158. text = models.CharField(
  159. max_length=500,
  160. help_text="Jinja2 template code for link text"
  161. )
  162. url = models.CharField(
  163. max_length=500,
  164. verbose_name='URL',
  165. help_text="Jinja2 template code for link URL"
  166. )
  167. weight = models.PositiveSmallIntegerField(
  168. default=100
  169. )
  170. group_name = models.CharField(
  171. max_length=50,
  172. blank=True,
  173. help_text="Links with the same group will appear as a dropdown menu"
  174. )
  175. button_class = models.CharField(
  176. max_length=30,
  177. choices=CustomLinkButtonClassChoices,
  178. default=CustomLinkButtonClassChoices.CLASS_DEFAULT,
  179. help_text="The class of the first link in a group will be used for the dropdown button"
  180. )
  181. new_window = models.BooleanField(
  182. help_text="Force link to open in a new window"
  183. )
  184. class Meta:
  185. ordering = ['group_name', 'weight', 'name']
  186. def __str__(self):
  187. return self.name
  188. #
  189. # Graphs
  190. #
  191. class Graph(models.Model):
  192. type = models.ForeignKey(
  193. to=ContentType,
  194. on_delete=models.CASCADE,
  195. limit_choices_to=FeatureQuery('graphs')
  196. )
  197. weight = models.PositiveSmallIntegerField(
  198. default=1000
  199. )
  200. name = models.CharField(
  201. max_length=100,
  202. verbose_name='Name'
  203. )
  204. template_language = models.CharField(
  205. max_length=50,
  206. choices=TemplateLanguageChoices,
  207. default=TemplateLanguageChoices.LANGUAGE_JINJA2
  208. )
  209. source = models.CharField(
  210. max_length=500,
  211. verbose_name='Source URL'
  212. )
  213. link = models.URLField(
  214. blank=True,
  215. verbose_name='Link URL'
  216. )
  217. objects = RestrictedQuerySet.as_manager()
  218. class Meta:
  219. ordering = ('type', 'weight', 'name', 'pk') # (type, weight, name) may be non-unique
  220. def __str__(self):
  221. return self.name
  222. def embed_url(self, obj):
  223. context = {'obj': obj}
  224. if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
  225. template = Template(self.source)
  226. return template.render(Context(context))
  227. elif self.template_language == TemplateLanguageChoices.LANGUAGE_JINJA2:
  228. return render_jinja2(self.source, context)
  229. def embed_link(self, obj):
  230. if self.link is None:
  231. return ''
  232. context = {'obj': obj}
  233. if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
  234. template = Template(self.link)
  235. return template.render(Context(context))
  236. elif self.template_language == TemplateLanguageChoices.LANGUAGE_JINJA2:
  237. return render_jinja2(self.link, context)
  238. #
  239. # Export templates
  240. #
  241. class ExportTemplate(models.Model):
  242. content_type = models.ForeignKey(
  243. to=ContentType,
  244. on_delete=models.CASCADE,
  245. limit_choices_to=FeatureQuery('export_templates')
  246. )
  247. name = models.CharField(
  248. max_length=100
  249. )
  250. description = models.CharField(
  251. max_length=200,
  252. blank=True
  253. )
  254. template_language = models.CharField(
  255. max_length=50,
  256. choices=TemplateLanguageChoices,
  257. default=TemplateLanguageChoices.LANGUAGE_JINJA2
  258. )
  259. template_code = models.TextField(
  260. help_text='The list of objects being exported is passed as a context variable named <code>queryset</code>.'
  261. )
  262. mime_type = models.CharField(
  263. max_length=50,
  264. blank=True,
  265. verbose_name='MIME type',
  266. help_text='Defaults to <code>text/plain</code>'
  267. )
  268. file_extension = models.CharField(
  269. max_length=15,
  270. blank=True,
  271. help_text='Extension to append to the rendered filename'
  272. )
  273. objects = RestrictedQuerySet.as_manager()
  274. class Meta:
  275. ordering = ['content_type', 'name']
  276. unique_together = [
  277. ['content_type', 'name']
  278. ]
  279. def __str__(self):
  280. return '{}: {}'.format(self.content_type, self.name)
  281. def render(self, queryset):
  282. """
  283. Render the contents of the template.
  284. """
  285. context = {
  286. 'queryset': queryset
  287. }
  288. if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
  289. template = Template(self.template_code)
  290. output = template.render(Context(context))
  291. elif self.template_language == TemplateLanguageChoices.LANGUAGE_JINJA2:
  292. output = render_jinja2(self.template_code, context)
  293. else:
  294. return None
  295. # Replace CRLF-style line terminators
  296. output = output.replace('\r\n', '\n')
  297. return output
  298. def render_to_response(self, queryset):
  299. """
  300. Render the template to an HTTP response, delivered as a named file attachment
  301. """
  302. output = self.render(queryset)
  303. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  304. # Build the response
  305. response = HttpResponse(output, content_type=mime_type)
  306. filename = 'netbox_{}{}'.format(
  307. queryset.model._meta.verbose_name_plural,
  308. '.{}'.format(self.file_extension) if self.file_extension else ''
  309. )
  310. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  311. return response
  312. #
  313. # Image attachments
  314. #
  315. class ImageAttachment(models.Model):
  316. """
  317. An uploaded image which is associated with an object.
  318. """
  319. content_type = models.ForeignKey(
  320. to=ContentType,
  321. on_delete=models.CASCADE
  322. )
  323. object_id = models.PositiveIntegerField()
  324. parent = GenericForeignKey(
  325. ct_field='content_type',
  326. fk_field='object_id'
  327. )
  328. image = models.ImageField(
  329. upload_to=image_upload,
  330. height_field='image_height',
  331. width_field='image_width'
  332. )
  333. image_height = models.PositiveSmallIntegerField()
  334. image_width = models.PositiveSmallIntegerField()
  335. name = models.CharField(
  336. max_length=50,
  337. blank=True
  338. )
  339. created = models.DateTimeField(
  340. auto_now_add=True
  341. )
  342. class Meta:
  343. ordering = ('name', 'pk') # name may be non-unique
  344. def __str__(self):
  345. if self.name:
  346. return self.name
  347. filename = self.image.name.rsplit('/', 1)[-1]
  348. return filename.split('_', 2)[2]
  349. def delete(self, *args, **kwargs):
  350. _name = self.image.name
  351. super().delete(*args, **kwargs)
  352. # Delete file from disk
  353. self.image.delete(save=False)
  354. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  355. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  356. self.image.name = _name
  357. @property
  358. def size(self):
  359. """
  360. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  361. catch other exceptions that we know other storage back-ends to throw.
  362. """
  363. expected_exceptions = [OSError]
  364. try:
  365. from botocore.exceptions import ClientError
  366. expected_exceptions.append(ClientError)
  367. except ImportError:
  368. pass
  369. try:
  370. return self.image.size
  371. except tuple(expected_exceptions):
  372. return None
  373. #
  374. # Config contexts
  375. #
  376. class ConfigContext(models.Model):
  377. """
  378. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  379. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  380. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  381. """
  382. name = models.CharField(
  383. max_length=100,
  384. unique=True
  385. )
  386. weight = models.PositiveSmallIntegerField(
  387. default=1000
  388. )
  389. description = models.CharField(
  390. max_length=200,
  391. blank=True
  392. )
  393. is_active = models.BooleanField(
  394. default=True,
  395. )
  396. regions = models.ManyToManyField(
  397. to='dcim.Region',
  398. related_name='+',
  399. blank=True
  400. )
  401. sites = models.ManyToManyField(
  402. to='dcim.Site',
  403. related_name='+',
  404. blank=True
  405. )
  406. roles = models.ManyToManyField(
  407. to='dcim.DeviceRole',
  408. related_name='+',
  409. blank=True
  410. )
  411. platforms = models.ManyToManyField(
  412. to='dcim.Platform',
  413. related_name='+',
  414. blank=True
  415. )
  416. cluster_groups = models.ManyToManyField(
  417. to='virtualization.ClusterGroup',
  418. related_name='+',
  419. blank=True
  420. )
  421. clusters = models.ManyToManyField(
  422. to='virtualization.Cluster',
  423. related_name='+',
  424. blank=True
  425. )
  426. tenant_groups = models.ManyToManyField(
  427. to='tenancy.TenantGroup',
  428. related_name='+',
  429. blank=True
  430. )
  431. tenants = models.ManyToManyField(
  432. to='tenancy.Tenant',
  433. related_name='+',
  434. blank=True
  435. )
  436. tags = models.ManyToManyField(
  437. to='extras.Tag',
  438. related_name='+',
  439. blank=True
  440. )
  441. data = JSONField()
  442. objects = ConfigContextQuerySet.as_manager()
  443. class Meta:
  444. ordering = ['weight', 'name']
  445. def __str__(self):
  446. return self.name
  447. def get_absolute_url(self):
  448. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  449. def clean(self):
  450. # Verify that JSON data is provided as an object
  451. if type(self.data) is not dict:
  452. raise ValidationError(
  453. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  454. )
  455. class ConfigContextModel(models.Model):
  456. """
  457. A model which includes local configuration context data. This local data will override any inherited data from
  458. ConfigContexts.
  459. """
  460. local_context_data = JSONField(
  461. blank=True,
  462. null=True,
  463. )
  464. class Meta:
  465. abstract = True
  466. def get_config_context(self):
  467. """
  468. Return the rendered configuration context for a device or VM.
  469. """
  470. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  471. data = OrderedDict()
  472. for context in ConfigContext.objects.get_for_object(self):
  473. data = deepmerge(data, context.data)
  474. # If the object has local config context data defined, merge it last
  475. if self.local_context_data:
  476. data = deepmerge(data, self.local_context_data)
  477. return data
  478. def clean(self):
  479. super().clean()
  480. # Verify that JSON data is provided as an object
  481. if self.local_context_data and type(self.local_context_data) is not dict:
  482. raise ValidationError(
  483. {'local_context_data': 'JSON data must be in object form. Example: {"foo": 123}'}
  484. )
  485. #
  486. # Custom scripts
  487. #
  488. @extras_features('job_results')
  489. class Script(models.Model):
  490. """
  491. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  492. """
  493. class Meta:
  494. managed = False
  495. #
  496. # Reports
  497. #
  498. @extras_features('job_results')
  499. class Report(models.Model):
  500. """
  501. Dummy model used to generate permissions for reports. Does not exist in the database.
  502. """
  503. class Meta:
  504. managed = False
  505. #
  506. # Job results
  507. #
  508. class JobResult(models.Model):
  509. """
  510. This model stores the results from running a user-defined report.
  511. """
  512. name = models.CharField(
  513. max_length=255
  514. )
  515. obj_type = models.ForeignKey(
  516. to=ContentType,
  517. related_name='job_results',
  518. verbose_name='Object types',
  519. limit_choices_to=FeatureQuery('job_results'),
  520. help_text="The object type to which this job result applies.",
  521. on_delete=models.CASCADE,
  522. )
  523. created = models.DateTimeField(
  524. auto_now_add=True
  525. )
  526. completed = models.DateTimeField(
  527. null=True,
  528. blank=True
  529. )
  530. user = models.ForeignKey(
  531. to=User,
  532. on_delete=models.SET_NULL,
  533. related_name='+',
  534. blank=True,
  535. null=True
  536. )
  537. status = models.CharField(
  538. max_length=30,
  539. choices=JobResultStatusChoices,
  540. default=JobResultStatusChoices.STATUS_PENDING
  541. )
  542. data = JSONField(
  543. null=True,
  544. blank=True
  545. )
  546. job_id = models.UUIDField(
  547. unique=True
  548. )
  549. class Meta:
  550. ordering = ['obj_type', 'name', '-created']
  551. def __str__(self):
  552. return str(self.job_id)
  553. @property
  554. def duration(self):
  555. if not self.completed:
  556. return None
  557. duration = self.completed - self.created
  558. minutes, seconds = divmod(duration.total_seconds(), 60)
  559. return f"{int(minutes)} minutes, {seconds:.2f} seconds"
  560. @classmethod
  561. def enqueue_job(cls, func, name, obj_type, user, *args, **kwargs):
  562. """
  563. Create a JobResult instance and enqueue a job using the given callable
  564. func: The callable object to be enqueued for execution
  565. name: Name for the JobResult instance
  566. obj_type: ContentType to link to the JobResult instance obj_type
  567. user: User object to link to the JobResult instance
  568. args: additional args passed to the callable
  569. kwargs: additional kargs passed to the callable
  570. """
  571. job_result = cls.objects.create(
  572. name=name,
  573. obj_type=obj_type,
  574. user=user,
  575. job_id=uuid.uuid4()
  576. )
  577. func.delay(*args, job_id=str(job_result.job_id), job_result=job_result, **kwargs)
  578. return job_result
  579. #
  580. # Change logging
  581. #
  582. class ObjectChange(models.Model):
  583. """
  584. Record a change to an object and the user account associated with that change. A change record may optionally
  585. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  586. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  587. """
  588. time = models.DateTimeField(
  589. auto_now_add=True,
  590. editable=False,
  591. db_index=True
  592. )
  593. user = models.ForeignKey(
  594. to=User,
  595. on_delete=models.SET_NULL,
  596. related_name='changes',
  597. blank=True,
  598. null=True
  599. )
  600. user_name = models.CharField(
  601. max_length=150,
  602. editable=False
  603. )
  604. request_id = models.UUIDField(
  605. editable=False
  606. )
  607. action = models.CharField(
  608. max_length=50,
  609. choices=ObjectChangeActionChoices
  610. )
  611. changed_object_type = models.ForeignKey(
  612. to=ContentType,
  613. on_delete=models.PROTECT,
  614. related_name='+'
  615. )
  616. changed_object_id = models.PositiveIntegerField()
  617. changed_object = GenericForeignKey(
  618. ct_field='changed_object_type',
  619. fk_field='changed_object_id'
  620. )
  621. related_object_type = models.ForeignKey(
  622. to=ContentType,
  623. on_delete=models.PROTECT,
  624. related_name='+',
  625. blank=True,
  626. null=True
  627. )
  628. related_object_id = models.PositiveIntegerField(
  629. blank=True,
  630. null=True
  631. )
  632. related_object = GenericForeignKey(
  633. ct_field='related_object_type',
  634. fk_field='related_object_id'
  635. )
  636. object_repr = models.CharField(
  637. max_length=200,
  638. editable=False
  639. )
  640. object_data = JSONField(
  641. editable=False
  642. )
  643. objects = RestrictedQuerySet.as_manager()
  644. csv_headers = [
  645. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  646. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  647. ]
  648. class Meta:
  649. ordering = ['-time']
  650. def __str__(self):
  651. return '{} {} {} by {}'.format(
  652. self.changed_object_type,
  653. self.object_repr,
  654. self.get_action_display().lower(),
  655. self.user_name
  656. )
  657. def save(self, *args, **kwargs):
  658. # Record the user's name and the object's representation as static strings
  659. if not self.user_name:
  660. self.user_name = self.user.username
  661. if not self.object_repr:
  662. self.object_repr = str(self.changed_object)
  663. return super().save(*args, **kwargs)
  664. def get_absolute_url(self):
  665. return reverse('extras:objectchange', args=[self.pk])
  666. def to_csv(self):
  667. return (
  668. self.time,
  669. self.user,
  670. self.user_name,
  671. self.request_id,
  672. self.get_action_display(),
  673. self.changed_object_type,
  674. self.changed_object_id,
  675. self.related_object_type,
  676. self.related_object_id,
  677. self.object_repr,
  678. self.object_data,
  679. )