models.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. from collections import OrderedDict
  2. from datetime import date
  3. import graphviz
  4. from django.contrib.auth.models import User
  5. from django.contrib.contenttypes.fields import GenericForeignKey
  6. from django.contrib.contenttypes.models import ContentType
  7. from django.contrib.postgres.fields import JSONField
  8. from django.core.validators import ValidationError
  9. from django.db import models
  10. from django.db.models import F, Q
  11. from django.http import HttpResponse
  12. from django.template import Template, Context
  13. from django.urls import reverse
  14. from dcim.constants import CONNECTION_STATUS_CONNECTED
  15. from utilities.utils import deepmerge, foreground_color
  16. from .constants import *
  17. from .querysets import ConfigContextQuerySet
  18. #
  19. # Webhooks
  20. #
  21. class Webhook(models.Model):
  22. """
  23. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  24. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  25. Each Webhook can be limited to firing only on certain actions or certain object types.
  26. """
  27. obj_type = models.ManyToManyField(
  28. to=ContentType,
  29. related_name='webhooks',
  30. verbose_name='Object types',
  31. limit_choices_to={'model__in': WEBHOOK_MODELS},
  32. help_text="The object(s) to which this Webhook applies."
  33. )
  34. name = models.CharField(
  35. max_length=150,
  36. unique=True
  37. )
  38. type_create = models.BooleanField(
  39. default=False,
  40. help_text="Call this webhook when a matching object is created."
  41. )
  42. type_update = models.BooleanField(
  43. default=False,
  44. help_text="Call this webhook when a matching object is updated."
  45. )
  46. type_delete = models.BooleanField(
  47. default=False,
  48. help_text="Call this webhook when a matching object is deleted."
  49. )
  50. payload_url = models.CharField(
  51. max_length=500,
  52. verbose_name='URL',
  53. help_text="A POST will be sent to this URL when the webhook is called."
  54. )
  55. http_content_type = models.PositiveSmallIntegerField(
  56. choices=WEBHOOK_CT_CHOICES,
  57. default=WEBHOOK_CT_JSON,
  58. verbose_name='HTTP content type'
  59. )
  60. secret = models.CharField(
  61. max_length=255,
  62. blank=True,
  63. help_text="When provided, the request will include a 'X-Hook-Signature' "
  64. "header containing a HMAC hex digest of the payload body using "
  65. "the secret as the key. The secret is not transmitted in "
  66. "the request."
  67. )
  68. enabled = models.BooleanField(
  69. default=True
  70. )
  71. ssl_verification = models.BooleanField(
  72. default=True,
  73. verbose_name='SSL verification',
  74. help_text="Enable SSL certificate verification. Disable with caution!"
  75. )
  76. class Meta:
  77. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  78. def __str__(self):
  79. return self.name
  80. def clean(self):
  81. """
  82. Validate model
  83. """
  84. if not self.type_create and not self.type_delete and not self.type_update:
  85. raise ValidationError(
  86. "You must select at least one type: create, update, and/or delete."
  87. )
  88. #
  89. # Custom fields
  90. #
  91. class CustomFieldModel(models.Model):
  92. class Meta:
  93. abstract = True
  94. def cf(self):
  95. """
  96. Name-based CustomFieldValue accessor for use in templates
  97. """
  98. if not hasattr(self, 'get_custom_fields'):
  99. return dict()
  100. return {field.name: value for field, value in self.get_custom_fields().items()}
  101. def get_custom_fields(self):
  102. """
  103. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  104. """
  105. # Find all custom fields applicable to this type of object
  106. content_type = ContentType.objects.get_for_model(self)
  107. fields = CustomField.objects.filter(obj_type=content_type)
  108. # If the object exists, populate its custom fields with values
  109. if hasattr(self, 'pk'):
  110. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  111. values_dict = {cfv.field_id: cfv.value for cfv in values}
  112. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  113. else:
  114. return OrderedDict([(field, None) for field in fields])
  115. class CustomField(models.Model):
  116. obj_type = models.ManyToManyField(
  117. to=ContentType,
  118. related_name='custom_fields',
  119. verbose_name='Object(s)',
  120. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  121. help_text='The object(s) to which this field applies.'
  122. )
  123. type = models.PositiveSmallIntegerField(
  124. choices=CUSTOMFIELD_TYPE_CHOICES,
  125. default=CF_TYPE_TEXT
  126. )
  127. name = models.CharField(
  128. max_length=50,
  129. unique=True
  130. )
  131. label = models.CharField(
  132. max_length=50,
  133. blank=True,
  134. help_text='Name of the field as displayed to users (if not provided, '
  135. 'the field\'s name will be used)'
  136. )
  137. description = models.CharField(
  138. max_length=100,
  139. blank=True
  140. )
  141. required = models.BooleanField(
  142. default=False,
  143. help_text='If true, this field is required when creating new objects '
  144. 'or editing an existing object.'
  145. )
  146. filter_logic = models.PositiveSmallIntegerField(
  147. choices=CF_FILTER_CHOICES,
  148. default=CF_FILTER_LOOSE,
  149. help_text='Loose matches any instance of a given string; exact '
  150. 'matches the entire field.'
  151. )
  152. default = models.CharField(
  153. max_length=100,
  154. blank=True,
  155. help_text='Default value for the field. Use "true" or "false" for booleans.'
  156. )
  157. weight = models.PositiveSmallIntegerField(
  158. default=100,
  159. help_text='Fields with higher weights appear lower in a form.'
  160. )
  161. class Meta:
  162. ordering = ['weight', 'name']
  163. def __str__(self):
  164. return self.label or self.name.replace('_', ' ').capitalize()
  165. def serialize_value(self, value):
  166. """
  167. Serialize the given value to a string suitable for storage as a CustomFieldValue
  168. """
  169. if value is None:
  170. return ''
  171. if self.type == CF_TYPE_BOOLEAN:
  172. return str(int(bool(value)))
  173. if self.type == CF_TYPE_DATE:
  174. # Could be date/datetime object or string
  175. try:
  176. return value.strftime('%Y-%m-%d')
  177. except AttributeError:
  178. return value
  179. if self.type == CF_TYPE_SELECT:
  180. # Could be ModelChoiceField or TypedChoiceField
  181. return str(value.id) if hasattr(value, 'id') else str(value)
  182. return value
  183. def deserialize_value(self, serialized_value):
  184. """
  185. Convert a string into the object it represents depending on the type of field
  186. """
  187. if serialized_value == '':
  188. return None
  189. if self.type == CF_TYPE_INTEGER:
  190. return int(serialized_value)
  191. if self.type == CF_TYPE_BOOLEAN:
  192. return bool(int(serialized_value))
  193. if self.type == CF_TYPE_DATE:
  194. # Read date as YYYY-MM-DD
  195. return date(*[int(n) for n in serialized_value.split('-')])
  196. if self.type == CF_TYPE_SELECT:
  197. return self.choices.get(pk=int(serialized_value))
  198. return serialized_value
  199. class CustomFieldValue(models.Model):
  200. field = models.ForeignKey(
  201. to='extras.CustomField',
  202. on_delete=models.CASCADE,
  203. related_name='values'
  204. )
  205. obj_type = models.ForeignKey(
  206. to=ContentType,
  207. on_delete=models.PROTECT,
  208. related_name='+'
  209. )
  210. obj_id = models.PositiveIntegerField()
  211. obj = GenericForeignKey(
  212. ct_field='obj_type',
  213. fk_field='obj_id'
  214. )
  215. serialized_value = models.CharField(
  216. max_length=255
  217. )
  218. class Meta:
  219. ordering = ['obj_type', 'obj_id']
  220. unique_together = ['field', 'obj_type', 'obj_id']
  221. def __str__(self):
  222. return '{} {}'.format(self.obj, self.field)
  223. @property
  224. def value(self):
  225. return self.field.deserialize_value(self.serialized_value)
  226. @value.setter
  227. def value(self, value):
  228. self.serialized_value = self.field.serialize_value(value)
  229. def save(self, *args, **kwargs):
  230. # Delete this object if it no longer has a value to store
  231. if self.pk and self.value is None:
  232. self.delete()
  233. else:
  234. super().save(*args, **kwargs)
  235. class CustomFieldChoice(models.Model):
  236. field = models.ForeignKey(
  237. to='extras.CustomField',
  238. on_delete=models.CASCADE,
  239. related_name='choices',
  240. limit_choices_to={'type': CF_TYPE_SELECT}
  241. )
  242. value = models.CharField(
  243. max_length=100
  244. )
  245. weight = models.PositiveSmallIntegerField(
  246. default=100,
  247. help_text='Higher weights appear lower in the list'
  248. )
  249. class Meta:
  250. ordering = ['field', 'weight', 'value']
  251. unique_together = ['field', 'value']
  252. def __str__(self):
  253. return self.value
  254. def clean(self):
  255. if self.field.type != CF_TYPE_SELECT:
  256. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  257. def delete(self, using=None, keep_parents=False):
  258. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  259. pk = self.pk
  260. super().delete(using, keep_parents)
  261. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  262. #
  263. # Graphs
  264. #
  265. class Graph(models.Model):
  266. type = models.PositiveSmallIntegerField(
  267. choices=GRAPH_TYPE_CHOICES
  268. )
  269. weight = models.PositiveSmallIntegerField(
  270. default=1000
  271. )
  272. name = models.CharField(
  273. max_length=100,
  274. verbose_name='Name'
  275. )
  276. source = models.CharField(
  277. max_length=500,
  278. verbose_name='Source URL'
  279. )
  280. link = models.URLField(
  281. blank=True,
  282. verbose_name='Link URL'
  283. )
  284. class Meta:
  285. ordering = ['type', 'weight', 'name']
  286. def __str__(self):
  287. return self.name
  288. def embed_url(self, obj):
  289. template = Template(self.source)
  290. return template.render(Context({'obj': obj}))
  291. def embed_link(self, obj):
  292. if self.link is None:
  293. return ''
  294. template = Template(self.link)
  295. return template.render(Context({'obj': obj}))
  296. #
  297. # Export templates
  298. #
  299. class ExportTemplate(models.Model):
  300. content_type = models.ForeignKey(
  301. to=ContentType,
  302. on_delete=models.CASCADE,
  303. limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS}
  304. )
  305. name = models.CharField(
  306. max_length=100
  307. )
  308. description = models.CharField(
  309. max_length=200,
  310. blank=True
  311. )
  312. template_code = models.TextField()
  313. mime_type = models.CharField(
  314. max_length=50,
  315. blank=True
  316. )
  317. file_extension = models.CharField(
  318. max_length=15,
  319. blank=True
  320. )
  321. class Meta:
  322. ordering = ['content_type', 'name']
  323. unique_together = [
  324. ['content_type', 'name']
  325. ]
  326. def __str__(self):
  327. return '{}: {}'.format(self.content_type, self.name)
  328. def render_to_response(self, queryset):
  329. """
  330. Render the template to an HTTP response, delivered as a named file attachment
  331. """
  332. template = Template(self.template_code)
  333. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  334. output = template.render(Context({'queryset': queryset}))
  335. # Replace CRLF-style line terminators
  336. output = output.replace('\r\n', '\n')
  337. # Build the response
  338. response = HttpResponse(output, content_type=mime_type)
  339. filename = 'netbox_{}{}'.format(
  340. queryset.model._meta.verbose_name_plural,
  341. '.{}'.format(self.file_extension) if self.file_extension else ''
  342. )
  343. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  344. return response
  345. #
  346. # Topology maps
  347. #
  348. class TopologyMap(models.Model):
  349. name = models.CharField(
  350. max_length=50,
  351. unique=True
  352. )
  353. slug = models.SlugField(
  354. unique=True
  355. )
  356. type = models.PositiveSmallIntegerField(
  357. choices=TOPOLOGYMAP_TYPE_CHOICES,
  358. default=TOPOLOGYMAP_TYPE_NETWORK
  359. )
  360. site = models.ForeignKey(
  361. to='dcim.Site',
  362. on_delete=models.CASCADE,
  363. related_name='topology_maps',
  364. blank=True,
  365. null=True
  366. )
  367. device_patterns = models.TextField(
  368. help_text='Identify devices to include in the diagram using regular '
  369. 'expressions, one per line. Each line will result in a new '
  370. 'tier of the drawing. Separate multiple regexes within a '
  371. 'line using semicolons. Devices will be rendered in the '
  372. 'order they are defined.'
  373. )
  374. description = models.CharField(
  375. max_length=100,
  376. blank=True
  377. )
  378. class Meta:
  379. ordering = ['name']
  380. def __str__(self):
  381. return self.name
  382. @property
  383. def device_sets(self):
  384. if not self.device_patterns:
  385. return None
  386. return [line.strip() for line in self.device_patterns.split('\n')]
  387. def render(self, img_format='png'):
  388. from dcim.models import Device
  389. # Construct the graph
  390. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  391. G = graphviz.Graph
  392. else:
  393. G = graphviz.Digraph
  394. self.graph = G()
  395. self.graph.graph_attr['ranksep'] = '1'
  396. seen = set()
  397. for i, device_set in enumerate(self.device_sets):
  398. subgraph = G(name='sg{}'.format(i))
  399. subgraph.graph_attr['rank'] = 'same'
  400. subgraph.graph_attr['directed'] = 'true'
  401. # Add a pseudonode for each device_set to enforce hierarchical layout
  402. subgraph.node('set{}'.format(i), label='', shape='none', width='0')
  403. if i:
  404. self.graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
  405. # Add each device to the graph
  406. devices = []
  407. for query in device_set.strip(';').split(';'): # Split regexes on semicolons
  408. devices += Device.objects.filter(name__regex=query).select_related('device_role')
  409. # Remove duplicate devices
  410. devices = [d for d in devices if d.id not in seen]
  411. seen.update([d.id for d in devices])
  412. for d in devices:
  413. bg_color = '#{}'.format(d.device_role.color)
  414. fg_color = '#{}'.format(foreground_color(d.device_role.color))
  415. subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans')
  416. # Add an invisible connection to each successive device in a set to enforce horizontal order
  417. for j in range(0, len(devices) - 1):
  418. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  419. self.graph.subgraph(subgraph)
  420. # Compile list of all devices
  421. device_superset = Q()
  422. for device_set in self.device_sets:
  423. for query in device_set.split(';'): # Split regexes on semicolons
  424. device_superset = device_superset | Q(name__regex=query)
  425. devices = Device.objects.filter(*(device_superset,))
  426. # Draw edges depending on graph type
  427. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  428. self.add_network_connections(devices)
  429. elif self.type == TOPOLOGYMAP_TYPE_CONSOLE:
  430. self.add_console_connections(devices)
  431. elif self.type == TOPOLOGYMAP_TYPE_POWER:
  432. self.add_power_connections(devices)
  433. return self.graph.pipe(format=img_format)
  434. def add_network_connections(self, devices):
  435. from circuits.models import CircuitTermination
  436. from dcim.models import Interface
  437. # Add all interface connections to the graph
  438. connected_interfaces = Interface.objects.select_related(
  439. '_connected_interface__device'
  440. ).filter(
  441. Q(device__in=devices) | Q(_connected_interface__device__in=devices),
  442. _connected_interface__isnull=False,
  443. pk__lt=F('_connected_interface')
  444. )
  445. for interface in connected_interfaces:
  446. style = 'solid' if interface.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  447. self.graph.edge(interface.device.name, interface.connected_endpoint.device.name, style=style)
  448. # Add all circuits to the graph
  449. for termination in CircuitTermination.objects.filter(term_side='A', connected_endpoint__device__in=devices):
  450. peer_termination = termination.get_peer_termination()
  451. if (peer_termination is not None and peer_termination.interface is not None and
  452. peer_termination.interface.device in devices):
  453. self.graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  454. def add_console_connections(self, devices):
  455. from dcim.models import ConsolePort
  456. # Add all console connections to the graph
  457. for cp in ConsolePort.objects.filter(device__in=devices, connected_endpoint__device__in=devices):
  458. style = 'solid' if cp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  459. self.graph.edge(cp.connected_endpoint.device.name, cp.device.name, style=style)
  460. def add_power_connections(self, devices):
  461. from dcim.models import PowerPort
  462. # Add all power connections to the graph
  463. for pp in PowerPort.objects.filter(device__in=devices, connected_endpoint__device__in=devices):
  464. style = 'solid' if pp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  465. self.graph.edge(pp.connected_endpoint.device.name, pp.device.name, style=style)
  466. #
  467. # Image attachments
  468. #
  469. def image_upload(instance, filename):
  470. path = 'image-attachments/'
  471. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  472. extension = filename.rsplit('.')[-1].lower()
  473. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  474. filename = '.'.join([instance.name, extension])
  475. elif instance.name:
  476. filename = instance.name
  477. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  478. class ImageAttachment(models.Model):
  479. """
  480. An uploaded image which is associated with an object.
  481. """
  482. content_type = models.ForeignKey(
  483. to=ContentType,
  484. on_delete=models.CASCADE
  485. )
  486. object_id = models.PositiveIntegerField()
  487. parent = GenericForeignKey(
  488. ct_field='content_type',
  489. fk_field='object_id'
  490. )
  491. image = models.ImageField(
  492. upload_to=image_upload,
  493. height_field='image_height',
  494. width_field='image_width'
  495. )
  496. image_height = models.PositiveSmallIntegerField()
  497. image_width = models.PositiveSmallIntegerField()
  498. name = models.CharField(
  499. max_length=50,
  500. blank=True
  501. )
  502. created = models.DateTimeField(
  503. auto_now_add=True
  504. )
  505. class Meta:
  506. ordering = ['name']
  507. def __str__(self):
  508. if self.name:
  509. return self.name
  510. filename = self.image.name.rsplit('/', 1)[-1]
  511. return filename.split('_', 2)[2]
  512. def delete(self, *args, **kwargs):
  513. _name = self.image.name
  514. super().delete(*args, **kwargs)
  515. # Delete file from disk
  516. self.image.delete(save=False)
  517. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  518. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  519. self.image.name = _name
  520. @property
  521. def size(self):
  522. """
  523. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  524. """
  525. try:
  526. return self.image.size
  527. except OSError:
  528. return None
  529. #
  530. # Config contexts
  531. #
  532. class ConfigContext(models.Model):
  533. """
  534. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  535. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  536. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  537. """
  538. name = models.CharField(
  539. max_length=100,
  540. unique=True
  541. )
  542. weight = models.PositiveSmallIntegerField(
  543. default=1000
  544. )
  545. description = models.CharField(
  546. max_length=100,
  547. blank=True
  548. )
  549. is_active = models.BooleanField(
  550. default=True,
  551. )
  552. regions = models.ManyToManyField(
  553. to='dcim.Region',
  554. related_name='+',
  555. blank=True
  556. )
  557. sites = models.ManyToManyField(
  558. to='dcim.Site',
  559. related_name='+',
  560. blank=True
  561. )
  562. roles = models.ManyToManyField(
  563. to='dcim.DeviceRole',
  564. related_name='+',
  565. blank=True
  566. )
  567. platforms = models.ManyToManyField(
  568. to='dcim.Platform',
  569. related_name='+',
  570. blank=True
  571. )
  572. tenant_groups = models.ManyToManyField(
  573. to='tenancy.TenantGroup',
  574. related_name='+',
  575. blank=True
  576. )
  577. tenants = models.ManyToManyField(
  578. to='tenancy.Tenant',
  579. related_name='+',
  580. blank=True
  581. )
  582. data = JSONField()
  583. objects = ConfigContextQuerySet.as_manager()
  584. class Meta:
  585. ordering = ['weight', 'name']
  586. def __str__(self):
  587. return self.name
  588. def get_absolute_url(self):
  589. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  590. def clean(self):
  591. # Verify that JSON data is provided as an object
  592. if type(self.data) is not dict:
  593. raise ValidationError(
  594. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  595. )
  596. class ConfigContextModel(models.Model):
  597. local_context_data = JSONField(
  598. blank=True,
  599. null=True,
  600. )
  601. class Meta:
  602. abstract = True
  603. def get_config_context(self):
  604. """
  605. Return the rendered configuration context for a device or VM.
  606. """
  607. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  608. data = OrderedDict()
  609. for context in ConfigContext.objects.get_for_object(self):
  610. data = deepmerge(data, context.data)
  611. # If the object has local config context data defined, merge it last
  612. if self.local_context_data is not None:
  613. data = deepmerge(data, self.local_context_data)
  614. return data
  615. #
  616. # Report results
  617. #
  618. class ReportResult(models.Model):
  619. """
  620. This model stores the results from running a user-defined report.
  621. """
  622. report = models.CharField(
  623. max_length=255,
  624. unique=True
  625. )
  626. created = models.DateTimeField(
  627. auto_now_add=True
  628. )
  629. user = models.ForeignKey(
  630. to=User,
  631. on_delete=models.SET_NULL,
  632. related_name='+',
  633. blank=True,
  634. null=True
  635. )
  636. failed = models.BooleanField()
  637. data = JSONField()
  638. class Meta:
  639. ordering = ['report']
  640. #
  641. # Change logging
  642. #
  643. class ObjectChange(models.Model):
  644. """
  645. Record a change to an object and the user account associated with that change. A change record may optionally
  646. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  647. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  648. """
  649. time = models.DateTimeField(
  650. auto_now_add=True,
  651. editable=False
  652. )
  653. user = models.ForeignKey(
  654. to=User,
  655. on_delete=models.SET_NULL,
  656. related_name='changes',
  657. blank=True,
  658. null=True
  659. )
  660. user_name = models.CharField(
  661. max_length=150,
  662. editable=False
  663. )
  664. request_id = models.UUIDField(
  665. editable=False
  666. )
  667. action = models.PositiveSmallIntegerField(
  668. choices=OBJECTCHANGE_ACTION_CHOICES
  669. )
  670. changed_object_type = models.ForeignKey(
  671. to=ContentType,
  672. on_delete=models.PROTECT,
  673. related_name='+'
  674. )
  675. changed_object_id = models.PositiveIntegerField()
  676. changed_object = GenericForeignKey(
  677. ct_field='changed_object_type',
  678. fk_field='changed_object_id'
  679. )
  680. related_object_type = models.ForeignKey(
  681. to=ContentType,
  682. on_delete=models.PROTECT,
  683. related_name='+',
  684. blank=True,
  685. null=True
  686. )
  687. related_object_id = models.PositiveIntegerField(
  688. blank=True,
  689. null=True
  690. )
  691. related_object = GenericForeignKey(
  692. ct_field='related_object_type',
  693. fk_field='related_object_id'
  694. )
  695. object_repr = models.CharField(
  696. max_length=200,
  697. editable=False
  698. )
  699. object_data = JSONField(
  700. editable=False
  701. )
  702. csv_headers = [
  703. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  704. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  705. ]
  706. class Meta:
  707. ordering = ['-time']
  708. def __str__(self):
  709. return '{} {} {} by {}'.format(
  710. self.changed_object_type,
  711. self.object_repr,
  712. self.get_action_display().lower(),
  713. self.user_name
  714. )
  715. def save(self, *args, **kwargs):
  716. # Record the user's name and the object's representation as static strings
  717. self.user_name = self.user.username
  718. self.object_repr = str(self.changed_object)
  719. return super().save(*args, **kwargs)
  720. def get_absolute_url(self):
  721. return reverse('extras:objectchange', args=[self.pk])
  722. def to_csv(self):
  723. return (
  724. self.time,
  725. self.user,
  726. self.user_name,
  727. self.request_id,
  728. self.get_action_display(),
  729. self.changed_object_type,
  730. self.changed_object_id,
  731. self.related_object_type,
  732. self.related_object_id,
  733. self.object_repr,
  734. self.object_data,
  735. )