models.py 28 KB

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