models.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 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 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(CustomFieldValue, self).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(CustomFieldChoice, self).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=15,
  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. )
  444. for interface in connected_interfaces:
  445. style = 'solid' if interface.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  446. self.graph.edge(interface.device.name, interface.connected_endpoint.device.name, style=style)
  447. # Add all circuits to the graph
  448. for termination in CircuitTermination.objects.filter(term_side='A', connected_endpoint__device__in=devices):
  449. peer_termination = termination.get_peer_termination()
  450. if (peer_termination is not None and peer_termination.interface is not None and
  451. peer_termination.interface.device in devices):
  452. self.graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  453. def add_console_connections(self, devices):
  454. from dcim.models import ConsolePort
  455. # Add all console connections to the graph
  456. for cp in ConsolePort.objects.filter(device__in=devices, connected_endpoint__device__in=devices):
  457. style = 'solid' if cp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  458. self.graph.edge(cp.connected_endpoint.device.name, cp.device.name, style=style)
  459. def add_power_connections(self, devices):
  460. from dcim.models import PowerPort
  461. # Add all power connections to the graph
  462. for pp in PowerPort.objects.filter(device__in=devices, connected_endpoint__device__in=devices):
  463. style = 'solid' if pp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  464. self.graph.edge(pp.connected_endpoint.device.name, pp.device.name, style=style)
  465. #
  466. # Image attachments
  467. #
  468. def image_upload(instance, filename):
  469. path = 'image-attachments/'
  470. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  471. extension = filename.rsplit('.')[-1].lower()
  472. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  473. filename = '.'.join([instance.name, extension])
  474. elif instance.name:
  475. filename = instance.name
  476. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  477. class ImageAttachment(models.Model):
  478. """
  479. An uploaded image which is associated with an object.
  480. """
  481. content_type = models.ForeignKey(
  482. to=ContentType,
  483. on_delete=models.CASCADE
  484. )
  485. object_id = models.PositiveIntegerField()
  486. parent = GenericForeignKey(
  487. ct_field='content_type',
  488. fk_field='object_id'
  489. )
  490. image = models.ImageField(
  491. upload_to=image_upload,
  492. height_field='image_height',
  493. width_field='image_width'
  494. )
  495. image_height = models.PositiveSmallIntegerField()
  496. image_width = models.PositiveSmallIntegerField()
  497. name = models.CharField(
  498. max_length=50,
  499. blank=True
  500. )
  501. created = models.DateTimeField(
  502. auto_now_add=True
  503. )
  504. class Meta:
  505. ordering = ['name']
  506. def __str__(self):
  507. if self.name:
  508. return self.name
  509. filename = self.image.name.rsplit('/', 1)[-1]
  510. return filename.split('_', 2)[2]
  511. def delete(self, *args, **kwargs):
  512. _name = self.image.name
  513. super(ImageAttachment, self).delete(*args, **kwargs)
  514. # Delete file from disk
  515. self.image.delete(save=False)
  516. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  517. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  518. self.image.name = _name
  519. @property
  520. def size(self):
  521. """
  522. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  523. """
  524. try:
  525. return self.image.size
  526. except OSError:
  527. return None
  528. #
  529. # Config contexts
  530. #
  531. class ConfigContext(models.Model):
  532. """
  533. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  534. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  535. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  536. """
  537. name = models.CharField(
  538. max_length=100,
  539. unique=True
  540. )
  541. weight = models.PositiveSmallIntegerField(
  542. default=1000
  543. )
  544. description = models.CharField(
  545. max_length=100,
  546. blank=True
  547. )
  548. is_active = models.BooleanField(
  549. default=True,
  550. )
  551. regions = models.ManyToManyField(
  552. to='dcim.Region',
  553. related_name='+',
  554. blank=True
  555. )
  556. sites = models.ManyToManyField(
  557. to='dcim.Site',
  558. related_name='+',
  559. blank=True
  560. )
  561. roles = models.ManyToManyField(
  562. to='dcim.DeviceRole',
  563. related_name='+',
  564. blank=True
  565. )
  566. platforms = models.ManyToManyField(
  567. to='dcim.Platform',
  568. related_name='+',
  569. blank=True
  570. )
  571. tenant_groups = models.ManyToManyField(
  572. to='tenancy.TenantGroup',
  573. related_name='+',
  574. blank=True
  575. )
  576. tenants = models.ManyToManyField(
  577. to='tenancy.Tenant',
  578. related_name='+',
  579. blank=True
  580. )
  581. data = JSONField()
  582. objects = ConfigContextQuerySet.as_manager()
  583. class Meta:
  584. ordering = ['weight', 'name']
  585. def __str__(self):
  586. return self.name
  587. def get_absolute_url(self):
  588. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  589. def clean(self):
  590. # Verify that JSON data is provided as an object
  591. if type(self.data) is not dict:
  592. raise ValidationError(
  593. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  594. )
  595. class ConfigContextModel(models.Model):
  596. local_context_data = JSONField(
  597. blank=True,
  598. null=True,
  599. )
  600. class Meta:
  601. abstract = True
  602. def get_config_context(self):
  603. """
  604. Return the rendered configuration context for a device or VM.
  605. """
  606. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  607. data = OrderedDict()
  608. for context in ConfigContext.objects.get_for_object(self):
  609. data.update(context.data)
  610. # If the object has local config context data defined, that data overwrites all rendered data
  611. if self.local_context_data is not None:
  612. data.update(self.local_context_data)
  613. return data
  614. #
  615. # Report results
  616. #
  617. class ReportResult(models.Model):
  618. """
  619. This model stores the results from running a user-defined report.
  620. """
  621. report = models.CharField(
  622. max_length=255,
  623. unique=True
  624. )
  625. created = models.DateTimeField(
  626. auto_now_add=True
  627. )
  628. user = models.ForeignKey(
  629. to=User,
  630. on_delete=models.SET_NULL,
  631. related_name='+',
  632. blank=True,
  633. null=True
  634. )
  635. failed = models.BooleanField()
  636. data = JSONField()
  637. class Meta:
  638. ordering = ['report']
  639. #
  640. # Change logging
  641. #
  642. class ObjectChange(models.Model):
  643. """
  644. Record a change to an object and the user account associated with that change. A change record may optionally
  645. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  646. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  647. """
  648. time = models.DateTimeField(
  649. auto_now_add=True,
  650. editable=False
  651. )
  652. user = models.ForeignKey(
  653. to=User,
  654. on_delete=models.SET_NULL,
  655. related_name='changes',
  656. blank=True,
  657. null=True
  658. )
  659. user_name = models.CharField(
  660. max_length=150,
  661. editable=False
  662. )
  663. request_id = models.UUIDField(
  664. editable=False
  665. )
  666. action = models.PositiveSmallIntegerField(
  667. choices=OBJECTCHANGE_ACTION_CHOICES
  668. )
  669. changed_object_type = models.ForeignKey(
  670. to=ContentType,
  671. on_delete=models.PROTECT,
  672. related_name='+'
  673. )
  674. changed_object_id = models.PositiveIntegerField()
  675. changed_object = GenericForeignKey(
  676. ct_field='changed_object_type',
  677. fk_field='changed_object_id'
  678. )
  679. related_object_type = models.ForeignKey(
  680. to=ContentType,
  681. on_delete=models.PROTECT,
  682. related_name='+',
  683. blank=True,
  684. null=True
  685. )
  686. related_object_id = models.PositiveIntegerField(
  687. blank=True,
  688. null=True
  689. )
  690. related_object = GenericForeignKey(
  691. ct_field='related_object_type',
  692. fk_field='related_object_id'
  693. )
  694. object_repr = models.CharField(
  695. max_length=200,
  696. editable=False
  697. )
  698. object_data = JSONField(
  699. editable=False
  700. )
  701. csv_headers = [
  702. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  703. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  704. ]
  705. class Meta:
  706. ordering = ['-time']
  707. def __str__(self):
  708. return '{} {} {} by {}'.format(
  709. self.changed_object_type,
  710. self.object_repr,
  711. self.get_action_display().lower(),
  712. self.user_name
  713. )
  714. def save(self, *args, **kwargs):
  715. # Record the user's name and the object's representation as static strings
  716. self.user_name = self.user.username
  717. self.object_repr = str(self.changed_object)
  718. return super(ObjectChange, self).save(*args, **kwargs)
  719. def get_absolute_url(self):
  720. return reverse('extras:objectchange', args=[self.pk])
  721. def to_csv(self):
  722. return (
  723. self.time,
  724. self.user,
  725. self.user_name,
  726. self.request_id,
  727. self.get_action_display(),
  728. self.changed_object_type,
  729. self.changed_object_id,
  730. self.related_object_type,
  731. self.related_object_id,
  732. self.object_repr,
  733. self.object_data,
  734. )