models.py 27 KB

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