models.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. from datetime import date
  4. import graphviz
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericForeignKey
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.postgres.fields import JSONField
  9. from django.core.validators import ValidationError
  10. from django.db import models
  11. from django.db.models import Q
  12. from django.http import HttpResponse
  13. from django.template import Template, Context
  14. from django.urls import reverse
  15. from django.utils.encoding import python_2_unicode_compatible
  16. from django.utils.safestring import mark_safe
  17. from dcim.constants import CONNECTION_STATUS_CONNECTED
  18. from utilities.utils import foreground_color
  19. from .constants import *
  20. from .querysets import ConfigContextQuerySet
  21. #
  22. # Webhooks
  23. #
  24. @python_2_unicode_compatible
  25. class Webhook(models.Model):
  26. """
  27. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  28. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  29. Each Webhook can be limited to firing only on certain actions or certain object types.
  30. """
  31. obj_type = models.ManyToManyField(
  32. to=ContentType,
  33. related_name='webhooks',
  34. verbose_name='Object types',
  35. limit_choices_to={'model__in': WEBHOOK_MODELS},
  36. help_text="The object(s) to which this Webhook applies."
  37. )
  38. name = models.CharField(
  39. max_length=150,
  40. unique=True
  41. )
  42. type_create = models.BooleanField(
  43. default=False,
  44. help_text="Call this webhook when a matching object is created."
  45. )
  46. type_update = models.BooleanField(
  47. default=False,
  48. help_text="Call this webhook when a matching object is updated."
  49. )
  50. type_delete = models.BooleanField(
  51. default=False,
  52. help_text="Call this webhook when a matching object is deleted."
  53. )
  54. payload_url = models.CharField(
  55. max_length=500,
  56. verbose_name='URL',
  57. help_text="A POST will be sent to this URL when the webhook is called."
  58. )
  59. http_content_type = models.PositiveSmallIntegerField(
  60. choices=WEBHOOK_CT_CHOICES,
  61. default=WEBHOOK_CT_JSON,
  62. verbose_name='HTTP content type'
  63. )
  64. secret = models.CharField(
  65. max_length=255,
  66. blank=True,
  67. help_text="When provided, the request will include a 'X-Hook-Signature' "
  68. "header containing a HMAC hex digest of the payload body using "
  69. "the secret as the key. The secret is not transmitted in "
  70. "the request."
  71. )
  72. enabled = models.BooleanField(
  73. default=True
  74. )
  75. ssl_verification = models.BooleanField(
  76. default=True,
  77. verbose_name='SSL verification',
  78. help_text="Enable SSL certificate verification. Disable with caution!"
  79. )
  80. class Meta:
  81. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  82. def __str__(self):
  83. return self.name
  84. def clean(self):
  85. """
  86. Validate model
  87. """
  88. if not self.type_create and not self.type_delete and not self.type_update:
  89. raise ValidationError(
  90. "You must select at least one type: create, update, and/or delete."
  91. )
  92. #
  93. # Custom fields
  94. #
  95. class CustomFieldModel(models.Model):
  96. class Meta:
  97. abstract = True
  98. def cf(self):
  99. """
  100. Name-based CustomFieldValue accessor for use in templates
  101. """
  102. if not hasattr(self, 'get_custom_fields'):
  103. return dict()
  104. return {field.name: value for field, value in self.get_custom_fields().items()}
  105. def get_custom_fields(self):
  106. """
  107. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  108. """
  109. # Find all custom fields applicable to this type of object
  110. content_type = ContentType.objects.get_for_model(self)
  111. fields = CustomField.objects.filter(obj_type=content_type)
  112. # If the object exists, populate its custom fields with values
  113. if hasattr(self, 'pk'):
  114. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  115. values_dict = {cfv.field_id: cfv.value for cfv in values}
  116. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  117. else:
  118. return OrderedDict([(field, None) for field in fields])
  119. @python_2_unicode_compatible
  120. class CustomField(models.Model):
  121. obj_type = models.ManyToManyField(
  122. to=ContentType,
  123. related_name='custom_fields',
  124. verbose_name='Object(s)',
  125. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  126. help_text='The object(s) to which this field applies.'
  127. )
  128. type = models.PositiveSmallIntegerField(
  129. choices=CUSTOMFIELD_TYPE_CHOICES,
  130. default=CF_TYPE_TEXT
  131. )
  132. name = models.CharField(
  133. max_length=50,
  134. unique=True
  135. )
  136. label = models.CharField(
  137. max_length=50,
  138. blank=True,
  139. help_text='Name of the field as displayed to users (if not provided, '
  140. 'the field\'s name will be used)'
  141. )
  142. description = models.CharField(
  143. max_length=100,
  144. blank=True
  145. )
  146. required = models.BooleanField(
  147. default=False,
  148. help_text='If true, this field is required when creating new objects '
  149. 'or editing an existing object.'
  150. )
  151. filter_logic = models.PositiveSmallIntegerField(
  152. choices=CF_FILTER_CHOICES,
  153. default=CF_FILTER_LOOSE,
  154. help_text='Loose matches any instance of a given string; exact '
  155. 'matches the entire field.'
  156. )
  157. default = models.CharField(
  158. max_length=100,
  159. blank=True,
  160. help_text='Default value for the field. Use "true" or "false" for booleans.'
  161. )
  162. weight = models.PositiveSmallIntegerField(
  163. default=100,
  164. help_text='Fields with higher weights appear lower in a form.'
  165. )
  166. class Meta:
  167. ordering = ['weight', 'name']
  168. def __str__(self):
  169. return self.label or self.name.replace('_', ' ').capitalize()
  170. def serialize_value(self, value):
  171. """
  172. Serialize the given value to a string suitable for storage as a CustomFieldValue
  173. """
  174. if value is None:
  175. return ''
  176. if self.type == CF_TYPE_BOOLEAN:
  177. return str(int(bool(value)))
  178. if self.type == CF_TYPE_DATE:
  179. # Could be date/datetime object or string
  180. try:
  181. return value.strftime('%Y-%m-%d')
  182. except AttributeError:
  183. return value
  184. if self.type == CF_TYPE_SELECT:
  185. # Could be ModelChoiceField or TypedChoiceField
  186. return str(value.id) if hasattr(value, 'id') else str(value)
  187. return value
  188. def deserialize_value(self, serialized_value):
  189. """
  190. Convert a string into the object it represents depending on the type of field
  191. """
  192. if serialized_value == '':
  193. return None
  194. if self.type == CF_TYPE_INTEGER:
  195. return int(serialized_value)
  196. if self.type == CF_TYPE_BOOLEAN:
  197. return bool(int(serialized_value))
  198. if self.type == CF_TYPE_DATE:
  199. # Read date as YYYY-MM-DD
  200. return date(*[int(n) for n in serialized_value.split('-')])
  201. if self.type == CF_TYPE_SELECT:
  202. return self.choices.get(pk=int(serialized_value))
  203. return serialized_value
  204. @python_2_unicode_compatible
  205. class CustomFieldValue(models.Model):
  206. field = models.ForeignKey(
  207. to='extras.CustomField',
  208. on_delete=models.CASCADE,
  209. related_name='values'
  210. )
  211. obj_type = models.ForeignKey(
  212. to=ContentType,
  213. on_delete=models.PROTECT,
  214. related_name='+'
  215. )
  216. obj_id = models.PositiveIntegerField()
  217. obj = GenericForeignKey(
  218. ct_field='obj_type',
  219. fk_field='obj_id'
  220. )
  221. serialized_value = models.CharField(
  222. max_length=255
  223. )
  224. class Meta:
  225. ordering = ['obj_type', 'obj_id']
  226. unique_together = ['field', 'obj_type', 'obj_id']
  227. def __str__(self):
  228. return '{} {}'.format(self.obj, self.field)
  229. @property
  230. def value(self):
  231. return self.field.deserialize_value(self.serialized_value)
  232. @value.setter
  233. def value(self, value):
  234. self.serialized_value = self.field.serialize_value(value)
  235. def save(self, *args, **kwargs):
  236. # Delete this object if it no longer has a value to store
  237. if self.pk and self.value is None:
  238. self.delete()
  239. else:
  240. super(CustomFieldValue, self).save(*args, **kwargs)
  241. @python_2_unicode_compatible
  242. class CustomFieldChoice(models.Model):
  243. field = models.ForeignKey(
  244. to='extras.CustomField',
  245. on_delete=models.CASCADE,
  246. related_name='choices',
  247. limit_choices_to={'type': CF_TYPE_SELECT}
  248. )
  249. value = models.CharField(
  250. max_length=100
  251. )
  252. weight = models.PositiveSmallIntegerField(
  253. default=100,
  254. help_text='Higher weights appear lower in the list'
  255. )
  256. class Meta:
  257. ordering = ['field', 'weight', 'value']
  258. unique_together = ['field', 'value']
  259. def __str__(self):
  260. return self.value
  261. def clean(self):
  262. if self.field.type != CF_TYPE_SELECT:
  263. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  264. def delete(self, using=None, keep_parents=False):
  265. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  266. pk = self.pk
  267. super(CustomFieldChoice, self).delete(using, keep_parents)
  268. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  269. #
  270. # Graphs
  271. #
  272. @python_2_unicode_compatible
  273. class Graph(models.Model):
  274. type = models.PositiveSmallIntegerField(
  275. choices=GRAPH_TYPE_CHOICES
  276. )
  277. weight = models.PositiveSmallIntegerField(
  278. default=1000
  279. )
  280. name = models.CharField(
  281. max_length=100,
  282. verbose_name='Name'
  283. )
  284. source = models.CharField(
  285. max_length=500,
  286. verbose_name='Source URL'
  287. )
  288. link = models.URLField(
  289. blank=True,
  290. verbose_name='Link URL'
  291. )
  292. class Meta:
  293. ordering = ['type', 'weight', 'name']
  294. def __str__(self):
  295. return self.name
  296. def embed_url(self, obj):
  297. template = Template(self.source)
  298. return template.render(Context({'obj': obj}))
  299. def embed_link(self, obj):
  300. if self.link is None:
  301. return ''
  302. template = Template(self.link)
  303. return template.render(Context({'obj': obj}))
  304. #
  305. # Export templates
  306. #
  307. @python_2_unicode_compatible
  308. class ExportTemplate(models.Model):
  309. content_type = models.ForeignKey(
  310. to=ContentType,
  311. on_delete=models.CASCADE,
  312. limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS}
  313. )
  314. name = models.CharField(
  315. max_length=100
  316. )
  317. description = models.CharField(
  318. max_length=200,
  319. blank=True
  320. )
  321. template_code = models.TextField()
  322. mime_type = models.CharField(
  323. max_length=15,
  324. blank=True
  325. )
  326. file_extension = models.CharField(
  327. max_length=15,
  328. blank=True
  329. )
  330. class Meta:
  331. ordering = ['content_type', 'name']
  332. unique_together = [
  333. ['content_type', 'name']
  334. ]
  335. def __str__(self):
  336. return '{}: {}'.format(self.content_type, self.name)
  337. def render_to_response(self, queryset):
  338. """
  339. Render the template to an HTTP response, delivered as a named file attachment
  340. """
  341. template = Template(self.template_code)
  342. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  343. output = template.render(Context({'queryset': queryset}))
  344. # Replace CRLF-style line terminators
  345. output = output.replace('\r\n', '\n')
  346. # Build the response
  347. response = HttpResponse(output, content_type=mime_type)
  348. filename = 'netbox_{}{}'.format(
  349. queryset.model._meta.verbose_name_plural,
  350. '.{}'.format(self.file_extension) if self.file_extension else ''
  351. )
  352. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  353. return response
  354. #
  355. # Topology maps
  356. #
  357. @python_2_unicode_compatible
  358. class TopologyMap(models.Model):
  359. name = models.CharField(
  360. max_length=50,
  361. unique=True
  362. )
  363. slug = models.SlugField(
  364. unique=True
  365. )
  366. type = models.PositiveSmallIntegerField(
  367. choices=TOPOLOGYMAP_TYPE_CHOICES,
  368. default=TOPOLOGYMAP_TYPE_NETWORK
  369. )
  370. site = models.ForeignKey(
  371. to='dcim.Site',
  372. on_delete=models.CASCADE,
  373. related_name='topology_maps',
  374. blank=True,
  375. null=True
  376. )
  377. device_patterns = models.TextField(
  378. help_text='Identify devices to include in the diagram using regular '
  379. 'expressions, one per line. Each line will result in a new '
  380. 'tier of the drawing. Separate multiple regexes within a '
  381. 'line using semicolons. Devices will be rendered in the '
  382. 'order they are defined.'
  383. )
  384. description = models.CharField(
  385. max_length=100,
  386. blank=True
  387. )
  388. class Meta:
  389. ordering = ['name']
  390. def __str__(self):
  391. return self.name
  392. @property
  393. def device_sets(self):
  394. if not self.device_patterns:
  395. return None
  396. return [line.strip() for line in self.device_patterns.split('\n')]
  397. def render(self, img_format='png'):
  398. from dcim.models import Device
  399. # Construct the graph
  400. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  401. G = graphviz.Graph
  402. else:
  403. G = graphviz.Digraph
  404. self.graph = G()
  405. self.graph.graph_attr['ranksep'] = '1'
  406. seen = set()
  407. for i, device_set in enumerate(self.device_sets):
  408. subgraph = G(name='sg{}'.format(i))
  409. subgraph.graph_attr['rank'] = 'same'
  410. subgraph.graph_attr['directed'] = 'true'
  411. # Add a pseudonode for each device_set to enforce hierarchical layout
  412. subgraph.node('set{}'.format(i), label='', shape='none', width='0')
  413. if i:
  414. self.graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
  415. # Add each device to the graph
  416. devices = []
  417. for query in device_set.strip(';').split(';'): # Split regexes on semicolons
  418. devices += Device.objects.filter(name__regex=query).select_related('device_role')
  419. # Remove duplicate devices
  420. devices = [d for d in devices if d.id not in seen]
  421. seen.update([d.id for d in devices])
  422. for d in devices:
  423. bg_color = '#{}'.format(d.device_role.color)
  424. fg_color = '#{}'.format(foreground_color(d.device_role.color))
  425. subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans')
  426. # Add an invisible connection to each successive device in a set to enforce horizontal order
  427. for j in range(0, len(devices) - 1):
  428. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  429. self.graph.subgraph(subgraph)
  430. # Compile list of all devices
  431. device_superset = Q()
  432. for device_set in self.device_sets:
  433. for query in device_set.split(';'): # Split regexes on semicolons
  434. device_superset = device_superset | Q(name__regex=query)
  435. devices = Device.objects.filter(*(device_superset,))
  436. # Draw edges depending on graph type
  437. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  438. self.add_network_connections(devices)
  439. elif self.type == TOPOLOGYMAP_TYPE_CONSOLE:
  440. self.add_console_connections(devices)
  441. elif self.type == TOPOLOGYMAP_TYPE_POWER:
  442. self.add_power_connections(devices)
  443. return self.graph.pipe(format=img_format)
  444. def add_network_connections(self, devices):
  445. from circuits.models import CircuitTermination
  446. from dcim.models import InterfaceConnection
  447. # Add all interface connections to the graph
  448. connections = InterfaceConnection.objects.filter(
  449. interface_a__device__in=devices, interface_b__device__in=devices
  450. )
  451. for c in connections:
  452. style = 'solid' if c.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  453. self.graph.edge(c.interface_a.device.name, c.interface_b.device.name, style=style)
  454. # Add all circuits to the graph
  455. for termination in CircuitTermination.objects.filter(term_side='A', interface__device__in=devices):
  456. peer_termination = termination.get_peer_termination()
  457. if (peer_termination is not None and peer_termination.interface is not None and
  458. peer_termination.interface.device in devices):
  459. self.graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  460. def add_console_connections(self, devices):
  461. from dcim.models import ConsolePort
  462. # Add all console connections to the graph
  463. console_ports = ConsolePort.objects.filter(device__in=devices, cs_port__device__in=devices)
  464. for cp in console_ports:
  465. style = 'solid' if cp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  466. self.graph.edge(cp.cs_port.device.name, cp.device.name, style=style)
  467. def add_power_connections(self, devices):
  468. from dcim.models import PowerPort
  469. # Add all power connections to the graph
  470. power_ports = PowerPort.objects.filter(device__in=devices, power_outlet__device__in=devices)
  471. for pp in power_ports:
  472. style = 'solid' if pp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  473. self.graph.edge(pp.power_outlet.device.name, pp.device.name, style=style)
  474. #
  475. # Image attachments
  476. #
  477. def image_upload(instance, filename):
  478. path = 'image-attachments/'
  479. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  480. extension = filename.rsplit('.')[-1].lower()
  481. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  482. filename = '.'.join([instance.name, extension])
  483. elif instance.name:
  484. filename = instance.name
  485. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  486. @python_2_unicode_compatible
  487. class ImageAttachment(models.Model):
  488. """
  489. An uploaded image which is associated with an object.
  490. """
  491. content_type = models.ForeignKey(
  492. to=ContentType,
  493. on_delete=models.CASCADE
  494. )
  495. object_id = models.PositiveIntegerField()
  496. parent = GenericForeignKey(
  497. ct_field='content_type',
  498. fk_field='object_id'
  499. )
  500. image = models.ImageField(
  501. upload_to=image_upload,
  502. height_field='image_height',
  503. width_field='image_width'
  504. )
  505. image_height = models.PositiveSmallIntegerField()
  506. image_width = models.PositiveSmallIntegerField()
  507. name = models.CharField(
  508. max_length=50,
  509. blank=True
  510. )
  511. created = models.DateTimeField(
  512. auto_now_add=True
  513. )
  514. class Meta:
  515. ordering = ['name']
  516. def __str__(self):
  517. if self.name:
  518. return self.name
  519. filename = self.image.name.rsplit('/', 1)[-1]
  520. return filename.split('_', 2)[2]
  521. def delete(self, *args, **kwargs):
  522. _name = self.image.name
  523. super(ImageAttachment, self).delete(*args, **kwargs)
  524. # Delete file from disk
  525. self.image.delete(save=False)
  526. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  527. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  528. self.image.name = _name
  529. @property
  530. def size(self):
  531. """
  532. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  533. """
  534. try:
  535. return self.image.size
  536. except OSError:
  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. data = JSONField()
  592. objects = ConfigContextQuerySet.as_manager()
  593. class Meta:
  594. ordering = ['weight', 'name']
  595. def __str__(self):
  596. return self.name
  597. def get_absolute_url(self):
  598. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  599. class ConfigContextModel(models.Model):
  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_config_context_data is not None:
  612. data.update(self.local_config_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. @python_2_unicode_compatible
  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(ObjectChange, self).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. )
  736. #
  737. # User actions
  738. #
  739. class UserActionManager(models.Manager):
  740. # Actions affecting a single object
  741. def log_action(self, user, obj, action, message):
  742. self.model.objects.create(
  743. content_type=ContentType.objects.get_for_model(obj),
  744. object_id=obj.pk,
  745. user=user,
  746. action=action,
  747. message=message,
  748. )
  749. def log_create(self, user, obj, message=''):
  750. self.log_action(user, obj, ACTION_CREATE, message)
  751. def log_edit(self, user, obj, message=''):
  752. self.log_action(user, obj, ACTION_EDIT, message)
  753. def log_delete(self, user, obj, message=''):
  754. self.log_action(user, obj, ACTION_DELETE, message)
  755. # Actions affecting multiple objects
  756. def log_bulk_action(self, user, content_type, action, message):
  757. self.model.objects.create(
  758. content_type=content_type,
  759. user=user,
  760. action=action,
  761. message=message,
  762. )
  763. def log_import(self, user, content_type, message=''):
  764. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  765. def log_bulk_create(self, user, content_type, message=''):
  766. self.log_bulk_action(user, content_type, ACTION_BULK_CREATE, message)
  767. def log_bulk_edit(self, user, content_type, message=''):
  768. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  769. def log_bulk_delete(self, user, content_type, message=''):
  770. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  771. # TODO: Remove UserAction, which has been replaced by ObjectChange.
  772. @python_2_unicode_compatible
  773. class UserAction(models.Model):
  774. """
  775. DEPRECATED: A record of an action (add, edit, or delete) performed on an object by a User.
  776. """
  777. time = models.DateTimeField(
  778. auto_now_add=True,
  779. editable=False
  780. )
  781. user = models.ForeignKey(
  782. to=User,
  783. on_delete=models.CASCADE,
  784. related_name='actions'
  785. )
  786. content_type = models.ForeignKey(
  787. to=ContentType,
  788. on_delete=models.CASCADE
  789. )
  790. object_id = models.PositiveIntegerField(
  791. blank=True,
  792. null=True
  793. )
  794. action = models.PositiveSmallIntegerField(
  795. choices=ACTION_CHOICES
  796. )
  797. message = models.TextField(
  798. blank=True
  799. )
  800. objects = UserActionManager()
  801. class Meta:
  802. ordering = ['-time']
  803. def __str__(self):
  804. if self.message:
  805. return '{} {}'.format(self.user, self.message)
  806. return '{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  807. def icon(self):
  808. if self.action in [ACTION_CREATE, ACTION_BULK_CREATE, ACTION_IMPORT]:
  809. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  810. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  811. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  812. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  813. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  814. else:
  815. return ''