models.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. from collections import OrderedDict
  2. from datetime import date
  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.contrib.postgres.fields import JSONField
  7. from django.core.validators import ValidationError
  8. from django.db import models
  9. from django.http import HttpResponse
  10. from django.template import Template, Context
  11. from django.urls import reverse
  12. from django.utils.text import slugify
  13. from taggit.models import TagBase, GenericTaggedItemBase
  14. from utilities.fields import ColorField
  15. from utilities.utils import deepmerge, render_jinja2
  16. from .choices import *
  17. from .constants import *
  18. from .querysets import ConfigContextQuerySet
  19. __all__ = (
  20. 'ConfigContext',
  21. 'ConfigContextModel',
  22. 'CustomField',
  23. 'CustomFieldChoice',
  24. 'CustomFieldModel',
  25. 'CustomFieldValue',
  26. 'CustomLink',
  27. 'ExportTemplate',
  28. 'Graph',
  29. 'ImageAttachment',
  30. 'ObjectChange',
  31. 'ReportResult',
  32. 'Script',
  33. 'Tag',
  34. 'TaggedItem',
  35. 'Webhook',
  36. )
  37. #
  38. # Webhooks
  39. #
  40. class Webhook(models.Model):
  41. """
  42. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  43. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  44. Each Webhook can be limited to firing only on certain actions or certain object types.
  45. """
  46. obj_type = models.ManyToManyField(
  47. to=ContentType,
  48. related_name='webhooks',
  49. verbose_name='Object types',
  50. limit_choices_to=WEBHOOK_MODELS,
  51. help_text="The object(s) to which this Webhook applies."
  52. )
  53. name = models.CharField(
  54. max_length=150,
  55. unique=True
  56. )
  57. type_create = models.BooleanField(
  58. default=False,
  59. help_text="Call this webhook when a matching object is created."
  60. )
  61. type_update = models.BooleanField(
  62. default=False,
  63. help_text="Call this webhook when a matching object is updated."
  64. )
  65. type_delete = models.BooleanField(
  66. default=False,
  67. help_text="Call this webhook when a matching object is deleted."
  68. )
  69. payload_url = models.CharField(
  70. max_length=500,
  71. verbose_name='URL',
  72. help_text="A POST will be sent to this URL when the webhook is called."
  73. )
  74. http_content_type = models.CharField(
  75. max_length=50,
  76. choices=WebhookContentTypeChoices,
  77. default=WebhookContentTypeChoices.CONTENTTYPE_JSON,
  78. verbose_name='HTTP content type'
  79. )
  80. additional_headers = JSONField(
  81. null=True,
  82. blank=True,
  83. help_text="User supplied headers which should be added to the request in addition to the HTTP content type. "
  84. "Headers are supplied as key/value pairs in a JSON object."
  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. enabled = models.BooleanField(
  95. default=True
  96. )
  97. ssl_verification = models.BooleanField(
  98. default=True,
  99. verbose_name='SSL verification',
  100. help_text="Enable SSL certificate verification. Disable with caution!"
  101. )
  102. ca_file_path = models.CharField(
  103. max_length=4096,
  104. null=True,
  105. blank=True,
  106. verbose_name='CA File Path',
  107. help_text='The specific CA certificate file to use for SSL verification. '
  108. 'Leave blank to use the system defaults.'
  109. )
  110. class Meta:
  111. ordering = ('name',)
  112. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  113. def __str__(self):
  114. return self.name
  115. def clean(self):
  116. """
  117. Validate model
  118. """
  119. if not self.type_create and not self.type_delete and not self.type_update:
  120. raise ValidationError(
  121. "You must select at least one type: create, update, and/or delete."
  122. )
  123. if not self.ssl_verification and self.ca_file_path:
  124. raise ValidationError({
  125. 'ca_file_path': 'Do not specify a CA certificate file if SSL verification is dissabled.'
  126. })
  127. # Verify that JSON data is provided as an object
  128. if self.additional_headers and type(self.additional_headers) is not dict:
  129. raise ValidationError({
  130. 'additional_headers': 'Header JSON data must be in object form. Example: {"X-API-KEY": "abc123"}'
  131. })
  132. #
  133. # Custom fields
  134. #
  135. class CustomFieldModel(models.Model):
  136. _cf = None
  137. class Meta:
  138. abstract = True
  139. def cache_custom_fields(self):
  140. """
  141. Cache all custom field values for this instance
  142. """
  143. self._cf = {
  144. field.name: value for field, value in self.get_custom_fields().items()
  145. }
  146. @property
  147. def cf(self):
  148. """
  149. Name-based CustomFieldValue accessor for use in templates
  150. """
  151. if self._cf is None:
  152. self.cache_custom_fields()
  153. return self._cf
  154. def get_custom_fields(self):
  155. """
  156. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  157. """
  158. # Find all custom fields applicable to this type of object
  159. content_type = ContentType.objects.get_for_model(self)
  160. fields = CustomField.objects.filter(obj_type=content_type)
  161. # If the object exists, populate its custom fields with values
  162. if hasattr(self, 'pk'):
  163. values = self.custom_field_values.all()
  164. values_dict = {cfv.field_id: cfv.value for cfv in values}
  165. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  166. else:
  167. return OrderedDict([(field, None) for field in fields])
  168. class CustomField(models.Model):
  169. obj_type = models.ManyToManyField(
  170. to=ContentType,
  171. related_name='custom_fields',
  172. verbose_name='Object(s)',
  173. limit_choices_to=CUSTOMFIELD_MODELS,
  174. help_text='The object(s) to which this field applies.'
  175. )
  176. type = models.CharField(
  177. max_length=50,
  178. choices=CustomFieldTypeChoices,
  179. default=CustomFieldTypeChoices.TYPE_TEXT
  180. )
  181. name = models.CharField(
  182. max_length=50,
  183. unique=True
  184. )
  185. label = models.CharField(
  186. max_length=50,
  187. blank=True,
  188. help_text='Name of the field as displayed to users (if not provided, '
  189. 'the field\'s name will be used)'
  190. )
  191. description = models.CharField(
  192. max_length=100,
  193. blank=True
  194. )
  195. required = models.BooleanField(
  196. default=False,
  197. help_text='If true, this field is required when creating new objects '
  198. 'or editing an existing object.'
  199. )
  200. filter_logic = models.CharField(
  201. max_length=50,
  202. choices=CustomFieldFilterLogicChoices,
  203. default=CustomFieldFilterLogicChoices.FILTER_LOOSE,
  204. help_text='Loose matches any instance of a given string; exact '
  205. 'matches the entire field.'
  206. )
  207. default = models.CharField(
  208. max_length=100,
  209. blank=True,
  210. help_text='Default value for the field. Use "true" or "false" for booleans.'
  211. )
  212. weight = models.PositiveSmallIntegerField(
  213. default=100,
  214. help_text='Fields with higher weights appear lower in a form.'
  215. )
  216. class Meta:
  217. ordering = ['weight', 'name']
  218. def __str__(self):
  219. return self.label or self.name.replace('_', ' ').capitalize()
  220. def serialize_value(self, value):
  221. """
  222. Serialize the given value to a string suitable for storage as a CustomFieldValue
  223. """
  224. if value is None:
  225. return ''
  226. if self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  227. return str(int(bool(value)))
  228. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  229. # Could be date/datetime object or string
  230. try:
  231. return value.strftime('%Y-%m-%d')
  232. except AttributeError:
  233. return value
  234. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  235. # Could be ModelChoiceField or TypedChoiceField
  236. return str(value.id) if hasattr(value, 'id') else str(value)
  237. return value
  238. def deserialize_value(self, serialized_value):
  239. """
  240. Convert a string into the object it represents depending on the type of field
  241. """
  242. if serialized_value == '':
  243. return None
  244. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  245. return int(serialized_value)
  246. if self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  247. return bool(int(serialized_value))
  248. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  249. # Read date as YYYY-MM-DD
  250. return date(*[int(n) for n in serialized_value.split('-')])
  251. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  252. return self.choices.get(pk=int(serialized_value))
  253. return serialized_value
  254. class CustomFieldValue(models.Model):
  255. field = models.ForeignKey(
  256. to='extras.CustomField',
  257. on_delete=models.CASCADE,
  258. related_name='values'
  259. )
  260. obj_type = models.ForeignKey(
  261. to=ContentType,
  262. on_delete=models.PROTECT,
  263. related_name='+'
  264. )
  265. obj_id = models.PositiveIntegerField()
  266. obj = GenericForeignKey(
  267. ct_field='obj_type',
  268. fk_field='obj_id'
  269. )
  270. serialized_value = models.CharField(
  271. max_length=255
  272. )
  273. class Meta:
  274. ordering = ('obj_type', 'obj_id', 'pk') # (obj_type, obj_id) may be non-unique
  275. unique_together = ('field', 'obj_type', 'obj_id')
  276. def __str__(self):
  277. return '{} {}'.format(self.obj, self.field)
  278. @property
  279. def value(self):
  280. return self.field.deserialize_value(self.serialized_value)
  281. @value.setter
  282. def value(self, value):
  283. self.serialized_value = self.field.serialize_value(value)
  284. def save(self, *args, **kwargs):
  285. # Delete this object if it no longer has a value to store
  286. if self.pk and self.value is None:
  287. self.delete()
  288. else:
  289. super().save(*args, **kwargs)
  290. class CustomFieldChoice(models.Model):
  291. field = models.ForeignKey(
  292. to='extras.CustomField',
  293. on_delete=models.CASCADE,
  294. related_name='choices',
  295. limit_choices_to={'type': CustomFieldTypeChoices.TYPE_SELECT}
  296. )
  297. value = models.CharField(
  298. max_length=100
  299. )
  300. weight = models.PositiveSmallIntegerField(
  301. default=100,
  302. help_text='Higher weights appear lower in the list'
  303. )
  304. class Meta:
  305. ordering = ['field', 'weight', 'value']
  306. unique_together = ['field', 'value']
  307. def __str__(self):
  308. return self.value
  309. def clean(self):
  310. if self.field.type != CustomFieldTypeChoices.TYPE_SELECT:
  311. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  312. def delete(self, using=None, keep_parents=False):
  313. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  314. pk = self.pk
  315. super().delete(using, keep_parents)
  316. CustomFieldValue.objects.filter(
  317. field__type=CustomFieldTypeChoices.TYPE_SELECT,
  318. serialized_value=str(pk)
  319. ).delete()
  320. #
  321. # Custom links
  322. #
  323. class CustomLink(models.Model):
  324. """
  325. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  326. code to be rendered with an object as context.
  327. """
  328. content_type = models.ForeignKey(
  329. to=ContentType,
  330. on_delete=models.CASCADE,
  331. limit_choices_to=CUSTOMLINK_MODELS
  332. )
  333. name = models.CharField(
  334. max_length=100,
  335. unique=True
  336. )
  337. text = models.CharField(
  338. max_length=500,
  339. help_text="Jinja2 template code for link text"
  340. )
  341. url = models.CharField(
  342. max_length=500,
  343. verbose_name='URL',
  344. help_text="Jinja2 template code for link URL"
  345. )
  346. weight = models.PositiveSmallIntegerField(
  347. default=100
  348. )
  349. group_name = models.CharField(
  350. max_length=50,
  351. blank=True,
  352. help_text="Links with the same group will appear as a dropdown menu"
  353. )
  354. button_class = models.CharField(
  355. max_length=30,
  356. choices=CustomLinkButtonClassChoices,
  357. default=CustomLinkButtonClassChoices.CLASS_DEFAULT,
  358. help_text="The class of the first link in a group will be used for the dropdown button"
  359. )
  360. new_window = models.BooleanField(
  361. help_text="Force link to open in a new window"
  362. )
  363. class Meta:
  364. ordering = ['group_name', 'weight', 'name']
  365. def __str__(self):
  366. return self.name
  367. #
  368. # Graphs
  369. #
  370. class Graph(models.Model):
  371. type = models.ForeignKey(
  372. to=ContentType,
  373. on_delete=models.CASCADE,
  374. limit_choices_to=GRAPH_MODELS
  375. )
  376. weight = models.PositiveSmallIntegerField(
  377. default=1000
  378. )
  379. name = models.CharField(
  380. max_length=100,
  381. verbose_name='Name'
  382. )
  383. template_language = models.CharField(
  384. max_length=50,
  385. choices=TemplateLanguageChoices,
  386. default=TemplateLanguageChoices.LANGUAGE_JINJA2
  387. )
  388. source = models.CharField(
  389. max_length=500,
  390. verbose_name='Source URL'
  391. )
  392. link = models.URLField(
  393. blank=True,
  394. verbose_name='Link URL'
  395. )
  396. class Meta:
  397. ordering = ('type', 'weight', 'name', 'pk') # (type, weight, name) may be non-unique
  398. def __str__(self):
  399. return self.name
  400. def embed_url(self, obj):
  401. context = {'obj': obj}
  402. # TODO: Remove in v2.8
  403. if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
  404. template = Template(self.source)
  405. return template.render(Context(context))
  406. elif self.template_language == TemplateLanguageChoices.LANGUAGE_JINJA2:
  407. return render_jinja2(self.source, context)
  408. def embed_link(self, obj):
  409. if self.link is None:
  410. return ''
  411. context = {'obj': obj}
  412. # TODO: Remove in v2.8
  413. if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
  414. template = Template(self.link)
  415. return template.render(Context(context))
  416. elif self.template_language == TemplateLanguageChoices.LANGUAGE_JINJA2:
  417. return render_jinja2(self.link, context)
  418. #
  419. # Export templates
  420. #
  421. class ExportTemplate(models.Model):
  422. content_type = models.ForeignKey(
  423. to=ContentType,
  424. on_delete=models.CASCADE,
  425. limit_choices_to=EXPORTTEMPLATE_MODELS
  426. )
  427. name = models.CharField(
  428. max_length=100
  429. )
  430. description = models.CharField(
  431. max_length=200,
  432. blank=True
  433. )
  434. template_language = models.CharField(
  435. max_length=50,
  436. choices=TemplateLanguageChoices,
  437. default=TemplateLanguageChoices.LANGUAGE_JINJA2
  438. )
  439. template_code = models.TextField(
  440. help_text='The list of objects being exported is passed as a context variable named <code>queryset</code>.'
  441. )
  442. mime_type = models.CharField(
  443. max_length=50,
  444. blank=True,
  445. verbose_name='MIME type',
  446. help_text='Defaults to <code>text/plain</code>'
  447. )
  448. file_extension = models.CharField(
  449. max_length=15,
  450. blank=True,
  451. help_text='Extension to append to the rendered filename'
  452. )
  453. class Meta:
  454. ordering = ['content_type', 'name']
  455. unique_together = [
  456. ['content_type', 'name']
  457. ]
  458. def __str__(self):
  459. return '{}: {}'.format(self.content_type, self.name)
  460. def render(self, queryset):
  461. """
  462. Render the contents of the template.
  463. """
  464. context = {
  465. 'queryset': queryset
  466. }
  467. if self.template_language == TemplateLanguageChoices.LANGUAGE_DJANGO:
  468. template = Template(self.template_code)
  469. output = template.render(Context(context))
  470. elif self.template_language == TemplateLanguageChoices.LANGUAGE_JINJA2:
  471. output = render_jinja2(self.template_code, context)
  472. else:
  473. return None
  474. # Replace CRLF-style line terminators
  475. output = output.replace('\r\n', '\n')
  476. return output
  477. def render_to_response(self, queryset):
  478. """
  479. Render the template to an HTTP response, delivered as a named file attachment
  480. """
  481. output = self.render(queryset)
  482. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  483. # Build the response
  484. response = HttpResponse(output, content_type=mime_type)
  485. filename = 'netbox_{}{}'.format(
  486. queryset.model._meta.verbose_name_plural,
  487. '.{}'.format(self.file_extension) if self.file_extension else ''
  488. )
  489. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  490. return response
  491. #
  492. # Image attachments
  493. #
  494. def image_upload(instance, filename):
  495. path = 'image-attachments/'
  496. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  497. extension = filename.rsplit('.')[-1].lower()
  498. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  499. filename = '.'.join([instance.name, extension])
  500. elif instance.name:
  501. filename = instance.name
  502. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  503. class ImageAttachment(models.Model):
  504. """
  505. An uploaded image which is associated with an object.
  506. """
  507. content_type = models.ForeignKey(
  508. to=ContentType,
  509. on_delete=models.CASCADE
  510. )
  511. object_id = models.PositiveIntegerField()
  512. parent = GenericForeignKey(
  513. ct_field='content_type',
  514. fk_field='object_id'
  515. )
  516. image = models.ImageField(
  517. upload_to=image_upload,
  518. height_field='image_height',
  519. width_field='image_width'
  520. )
  521. image_height = models.PositiveSmallIntegerField()
  522. image_width = models.PositiveSmallIntegerField()
  523. name = models.CharField(
  524. max_length=50,
  525. blank=True
  526. )
  527. created = models.DateTimeField(
  528. auto_now_add=True
  529. )
  530. class Meta:
  531. ordering = ('name', 'pk') # name may be non-unique
  532. def __str__(self):
  533. if self.name:
  534. return self.name
  535. filename = self.image.name.rsplit('/', 1)[-1]
  536. return filename.split('_', 2)[2]
  537. def delete(self, *args, **kwargs):
  538. _name = self.image.name
  539. super().delete(*args, **kwargs)
  540. # Delete file from disk
  541. self.image.delete(save=False)
  542. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  543. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  544. self.image.name = _name
  545. @property
  546. def size(self):
  547. """
  548. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  549. catch other exceptions that we know other storage back-ends to throw.
  550. """
  551. expected_exceptions = [OSError]
  552. try:
  553. from botocore.exceptions import ClientError
  554. expected_exceptions.append(ClientError)
  555. except ImportError:
  556. pass
  557. try:
  558. return self.image.size
  559. except tuple(expected_exceptions):
  560. return None
  561. #
  562. # Config contexts
  563. #
  564. class ConfigContext(models.Model):
  565. """
  566. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  567. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  568. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  569. """
  570. name = models.CharField(
  571. max_length=100,
  572. unique=True
  573. )
  574. weight = models.PositiveSmallIntegerField(
  575. default=1000
  576. )
  577. description = models.CharField(
  578. max_length=100,
  579. blank=True
  580. )
  581. is_active = models.BooleanField(
  582. default=True,
  583. )
  584. regions = models.ManyToManyField(
  585. to='dcim.Region',
  586. related_name='+',
  587. blank=True
  588. )
  589. sites = models.ManyToManyField(
  590. to='dcim.Site',
  591. related_name='+',
  592. blank=True
  593. )
  594. roles = models.ManyToManyField(
  595. to='dcim.DeviceRole',
  596. related_name='+',
  597. blank=True
  598. )
  599. platforms = models.ManyToManyField(
  600. to='dcim.Platform',
  601. related_name='+',
  602. blank=True
  603. )
  604. cluster_groups = models.ManyToManyField(
  605. to='virtualization.ClusterGroup',
  606. related_name='+',
  607. blank=True
  608. )
  609. clusters = models.ManyToManyField(
  610. to='virtualization.Cluster',
  611. related_name='+',
  612. blank=True
  613. )
  614. tenant_groups = models.ManyToManyField(
  615. to='tenancy.TenantGroup',
  616. related_name='+',
  617. blank=True
  618. )
  619. tenants = models.ManyToManyField(
  620. to='tenancy.Tenant',
  621. related_name='+',
  622. blank=True
  623. )
  624. tags = models.ManyToManyField(
  625. to='extras.Tag',
  626. related_name='+',
  627. blank=True
  628. )
  629. data = JSONField()
  630. objects = ConfigContextQuerySet.as_manager()
  631. class Meta:
  632. ordering = ['weight', 'name']
  633. def __str__(self):
  634. return self.name
  635. def get_absolute_url(self):
  636. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  637. def clean(self):
  638. # Verify that JSON data is provided as an object
  639. if type(self.data) is not dict:
  640. raise ValidationError(
  641. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  642. )
  643. class ConfigContextModel(models.Model):
  644. """
  645. A model which includes local configuration context data. This local data will override any inherited data from
  646. ConfigContexts.
  647. """
  648. local_context_data = JSONField(
  649. blank=True,
  650. null=True,
  651. )
  652. class Meta:
  653. abstract = True
  654. def get_config_context(self):
  655. """
  656. Return the rendered configuration context for a device or VM.
  657. """
  658. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  659. data = OrderedDict()
  660. for context in ConfigContext.objects.get_for_object(self):
  661. data = deepmerge(data, context.data)
  662. # If the object has local config context data defined, merge it last
  663. if self.local_context_data:
  664. data = deepmerge(data, self.local_context_data)
  665. return data
  666. def clean(self):
  667. super().clean()
  668. # Verify that JSON data is provided as an object
  669. if self.local_context_data and type(self.local_context_data) is not dict:
  670. raise ValidationError(
  671. {'local_context_data': 'JSON data must be in object form. Example: {"foo": 123}'}
  672. )
  673. #
  674. # Custom scripts
  675. #
  676. class Script(models.Model):
  677. """
  678. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  679. """
  680. class Meta:
  681. managed = False
  682. permissions = (
  683. ('run_script', 'Can run script'),
  684. )
  685. #
  686. # Report results
  687. #
  688. class ReportResult(models.Model):
  689. """
  690. This model stores the results from running a user-defined report.
  691. """
  692. report = models.CharField(
  693. max_length=255,
  694. unique=True
  695. )
  696. created = models.DateTimeField(
  697. auto_now_add=True
  698. )
  699. user = models.ForeignKey(
  700. to=User,
  701. on_delete=models.SET_NULL,
  702. related_name='+',
  703. blank=True,
  704. null=True
  705. )
  706. failed = models.BooleanField()
  707. data = JSONField()
  708. class Meta:
  709. ordering = ['report']
  710. def __str__(self):
  711. return "{} {} at {}".format(
  712. self.report,
  713. "passed" if not self.failed else "failed",
  714. self.created
  715. )
  716. #
  717. # Change logging
  718. #
  719. class ObjectChange(models.Model):
  720. """
  721. Record a change to an object and the user account associated with that change. A change record may optionally
  722. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  723. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  724. """
  725. time = models.DateTimeField(
  726. auto_now_add=True,
  727. editable=False,
  728. db_index=True
  729. )
  730. user = models.ForeignKey(
  731. to=User,
  732. on_delete=models.SET_NULL,
  733. related_name='changes',
  734. blank=True,
  735. null=True
  736. )
  737. user_name = models.CharField(
  738. max_length=150,
  739. editable=False
  740. )
  741. request_id = models.UUIDField(
  742. editable=False
  743. )
  744. action = models.CharField(
  745. max_length=50,
  746. choices=ObjectChangeActionChoices
  747. )
  748. changed_object_type = models.ForeignKey(
  749. to=ContentType,
  750. on_delete=models.PROTECT,
  751. related_name='+'
  752. )
  753. changed_object_id = models.PositiveIntegerField()
  754. changed_object = GenericForeignKey(
  755. ct_field='changed_object_type',
  756. fk_field='changed_object_id'
  757. )
  758. related_object_type = models.ForeignKey(
  759. to=ContentType,
  760. on_delete=models.PROTECT,
  761. related_name='+',
  762. blank=True,
  763. null=True
  764. )
  765. related_object_id = models.PositiveIntegerField(
  766. blank=True,
  767. null=True
  768. )
  769. related_object = GenericForeignKey(
  770. ct_field='related_object_type',
  771. fk_field='related_object_id'
  772. )
  773. object_repr = models.CharField(
  774. max_length=200,
  775. editable=False
  776. )
  777. object_data = JSONField(
  778. editable=False
  779. )
  780. csv_headers = [
  781. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  782. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  783. ]
  784. class Meta:
  785. ordering = ['-time']
  786. def __str__(self):
  787. return '{} {} {} by {}'.format(
  788. self.changed_object_type,
  789. self.object_repr,
  790. self.get_action_display().lower(),
  791. self.user_name
  792. )
  793. def save(self, *args, **kwargs):
  794. # Record the user's name and the object's representation as static strings
  795. if not self.user_name:
  796. self.user_name = self.user.username
  797. if not self.object_repr:
  798. self.object_repr = str(self.changed_object)
  799. return super().save(*args, **kwargs)
  800. def get_absolute_url(self):
  801. return reverse('extras:objectchange', args=[self.pk])
  802. def to_csv(self):
  803. return (
  804. self.time,
  805. self.user,
  806. self.user_name,
  807. self.request_id,
  808. self.get_action_display(),
  809. self.changed_object_type,
  810. self.changed_object_id,
  811. self.related_object_type,
  812. self.related_object_id,
  813. self.object_repr,
  814. self.object_data,
  815. )
  816. #
  817. # Tags
  818. #
  819. # TODO: figure out a way around this circular import for ObjectChange
  820. from utilities.models import ChangeLoggedModel # noqa: E402
  821. class Tag(TagBase, ChangeLoggedModel):
  822. color = ColorField(
  823. default='9e9e9e'
  824. )
  825. comments = models.TextField(
  826. blank=True,
  827. default=''
  828. )
  829. def get_absolute_url(self):
  830. return reverse('extras:tag', args=[self.slug])
  831. def slugify(self, tag, i=None):
  832. # Allow Unicode in Tag slugs (avoids empty slugs for Tags with all-Unicode names)
  833. slug = slugify(tag, allow_unicode=True)
  834. if i is not None:
  835. slug += "_%d" % i
  836. return slug
  837. class TaggedItem(GenericTaggedItemBase):
  838. tag = models.ForeignKey(
  839. to=Tag,
  840. related_name="%(app_label)s_%(class)s_items",
  841. on_delete=models.CASCADE
  842. )
  843. class Meta:
  844. index_together = (
  845. ("content_type", "object_id")
  846. )