models.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. When S3 storage is used
  526. ClientError is suppressed instead.
  527. """
  528. from django.conf import settings
  529. if settings.MEDIA_STORAGE and settings.MEDIA_STORAGE['BACKEND'] == 'S3':
  530. from botocore.exceptions import ClientError as AccessError
  531. else:
  532. AccessError = OSError
  533. try:
  534. return self.image.size
  535. except AccessError:
  536. return None
  537. #
  538. # Config contexts
  539. #
  540. class ConfigContext(models.Model):
  541. """
  542. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  543. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  544. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  545. """
  546. name = models.CharField(
  547. max_length=100,
  548. unique=True
  549. )
  550. weight = models.PositiveSmallIntegerField(
  551. default=1000
  552. )
  553. description = models.CharField(
  554. max_length=100,
  555. blank=True
  556. )
  557. is_active = models.BooleanField(
  558. default=True,
  559. )
  560. regions = models.ManyToManyField(
  561. to='dcim.Region',
  562. related_name='+',
  563. blank=True
  564. )
  565. sites = models.ManyToManyField(
  566. to='dcim.Site',
  567. related_name='+',
  568. blank=True
  569. )
  570. roles = models.ManyToManyField(
  571. to='dcim.DeviceRole',
  572. related_name='+',
  573. blank=True
  574. )
  575. platforms = models.ManyToManyField(
  576. to='dcim.Platform',
  577. related_name='+',
  578. blank=True
  579. )
  580. tenant_groups = models.ManyToManyField(
  581. to='tenancy.TenantGroup',
  582. related_name='+',
  583. blank=True
  584. )
  585. tenants = models.ManyToManyField(
  586. to='tenancy.Tenant',
  587. related_name='+',
  588. blank=True
  589. )
  590. data = JSONField()
  591. objects = ConfigContextQuerySet.as_manager()
  592. class Meta:
  593. ordering = ['weight', 'name']
  594. def __str__(self):
  595. return self.name
  596. def get_absolute_url(self):
  597. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  598. def clean(self):
  599. # Verify that JSON data is provided as an object
  600. if type(self.data) is not dict:
  601. raise ValidationError(
  602. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  603. )
  604. class ConfigContextModel(models.Model):
  605. """
  606. A model which includes local configuration context data. This local data will override any inherited data from
  607. ConfigContexts.
  608. """
  609. local_context_data = JSONField(
  610. blank=True,
  611. null=True,
  612. )
  613. class Meta:
  614. abstract = True
  615. def get_config_context(self):
  616. """
  617. Return the rendered configuration context for a device or VM.
  618. """
  619. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  620. data = OrderedDict()
  621. for context in ConfigContext.objects.get_for_object(self):
  622. data = deepmerge(data, context.data)
  623. # If the object has local config context data defined, merge it last
  624. if self.local_context_data:
  625. data = deepmerge(data, self.local_context_data)
  626. return data
  627. def clean(self):
  628. super().clean()
  629. # Verify that JSON data is provided as an object
  630. if self.local_context_data and type(self.local_context_data) is not dict:
  631. raise ValidationError(
  632. {'local_context_data': 'JSON data must be in object form. Example: {"foo": 123}'}
  633. )
  634. #
  635. # Custom scripts
  636. #
  637. class Script(models.Model):
  638. """
  639. Dummy model used to generate permissions for custom scripts. Does not exist in the database.
  640. """
  641. class Meta:
  642. managed = False
  643. permissions = (
  644. ('run_script', 'Can run script'),
  645. )
  646. #
  647. # Report results
  648. #
  649. class ReportResult(models.Model):
  650. """
  651. This model stores the results from running a user-defined report.
  652. """
  653. report = models.CharField(
  654. max_length=255,
  655. unique=True
  656. )
  657. created = models.DateTimeField(
  658. auto_now_add=True
  659. )
  660. user = models.ForeignKey(
  661. to=User,
  662. on_delete=models.SET_NULL,
  663. related_name='+',
  664. blank=True,
  665. null=True
  666. )
  667. failed = models.BooleanField()
  668. data = JSONField()
  669. class Meta:
  670. ordering = ['report']
  671. #
  672. # Change logging
  673. #
  674. class ObjectChange(models.Model):
  675. """
  676. Record a change to an object and the user account associated with that change. A change record may optionally
  677. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  678. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  679. """
  680. time = models.DateTimeField(
  681. auto_now_add=True,
  682. editable=False,
  683. db_index=True
  684. )
  685. user = models.ForeignKey(
  686. to=User,
  687. on_delete=models.SET_NULL,
  688. related_name='changes',
  689. blank=True,
  690. null=True
  691. )
  692. user_name = models.CharField(
  693. max_length=150,
  694. editable=False
  695. )
  696. request_id = models.UUIDField(
  697. editable=False
  698. )
  699. action = models.CharField(
  700. max_length=50,
  701. choices=ObjectChangeActionChoices
  702. )
  703. changed_object_type = models.ForeignKey(
  704. to=ContentType,
  705. on_delete=models.PROTECT,
  706. related_name='+'
  707. )
  708. changed_object_id = models.PositiveIntegerField()
  709. changed_object = GenericForeignKey(
  710. ct_field='changed_object_type',
  711. fk_field='changed_object_id'
  712. )
  713. related_object_type = models.ForeignKey(
  714. to=ContentType,
  715. on_delete=models.PROTECT,
  716. related_name='+',
  717. blank=True,
  718. null=True
  719. )
  720. related_object_id = models.PositiveIntegerField(
  721. blank=True,
  722. null=True
  723. )
  724. related_object = GenericForeignKey(
  725. ct_field='related_object_type',
  726. fk_field='related_object_id'
  727. )
  728. object_repr = models.CharField(
  729. max_length=200,
  730. editable=False
  731. )
  732. object_data = JSONField(
  733. editable=False
  734. )
  735. csv_headers = [
  736. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  737. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  738. ]
  739. class Meta:
  740. ordering = ['-time']
  741. def __str__(self):
  742. return '{} {} {} by {}'.format(
  743. self.changed_object_type,
  744. self.object_repr,
  745. self.get_action_display().lower(),
  746. self.user_name
  747. )
  748. def save(self, *args, **kwargs):
  749. # Record the user's name and the object's representation as static strings
  750. if not self.user_name:
  751. self.user_name = self.user.username
  752. if not self.object_repr:
  753. self.object_repr = str(self.changed_object)
  754. return super().save(*args, **kwargs)
  755. def get_absolute_url(self):
  756. return reverse('extras:objectchange', args=[self.pk])
  757. def to_csv(self):
  758. return (
  759. self.time,
  760. self.user,
  761. self.user_name,
  762. self.request_id,
  763. self.get_action_display(),
  764. self.changed_object_type,
  765. self.changed_object_id,
  766. self.related_object_type,
  767. self.related_object_id,
  768. self.object_repr,
  769. self.object_data,
  770. )
  771. #
  772. # Tags
  773. #
  774. # TODO: figure out a way around this circular import for ObjectChange
  775. from utilities.models import ChangeLoggedModel # noqa: E402
  776. class Tag(TagBase, ChangeLoggedModel):
  777. color = ColorField(
  778. default='9e9e9e'
  779. )
  780. comments = models.TextField(
  781. blank=True,
  782. default=''
  783. )
  784. def get_absolute_url(self):
  785. return reverse('extras:tag', args=[self.slug])
  786. class TaggedItem(GenericTaggedItemBase):
  787. tag = models.ForeignKey(
  788. to=Tag,
  789. related_name="%(app_label)s_%(class)s_items",
  790. on_delete=models.CASCADE
  791. )
  792. class Meta:
  793. index_together = (
  794. ("content_type", "object_id")
  795. )