models.py 28 KB

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