models.py 26 KB

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