models.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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.utils.encoding import python_2_unicode_compatible
  15. from django.utils.safestring import mark_safe
  16. from utilities.utils import foreground_color
  17. from .constants import *
  18. #
  19. # Custom fields
  20. #
  21. class CustomFieldModel(object):
  22. def cf(self):
  23. """
  24. Name-based CustomFieldValue accessor for use in templates
  25. """
  26. if not hasattr(self, 'get_custom_fields'):
  27. return dict()
  28. return {field.name: value for field, value in self.get_custom_fields().items()}
  29. def get_custom_fields(self):
  30. """
  31. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  32. """
  33. # Find all custom fields applicable to this type of object
  34. content_type = ContentType.objects.get_for_model(self)
  35. fields = CustomField.objects.filter(obj_type=content_type)
  36. # If the object exists, populate its custom fields with values
  37. if hasattr(self, 'pk'):
  38. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  39. values_dict = {cfv.field_id: cfv.value for cfv in values}
  40. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  41. else:
  42. return OrderedDict([(field, None) for field in fields])
  43. @python_2_unicode_compatible
  44. class CustomField(models.Model):
  45. obj_type = models.ManyToManyField(ContentType, related_name='custom_fields', verbose_name='Object(s)',
  46. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  47. help_text="The object(s) to which this field applies.")
  48. type = models.PositiveSmallIntegerField(choices=CUSTOMFIELD_TYPE_CHOICES, default=CF_TYPE_TEXT)
  49. name = models.CharField(max_length=50, unique=True)
  50. label = models.CharField(max_length=50, blank=True, help_text="Name of the field as displayed to users (if not "
  51. "provided, the field's name will be used)")
  52. description = models.CharField(max_length=100, blank=True)
  53. required = models.BooleanField(default=False, help_text="Determines whether this field is required when creating "
  54. "new objects or editing an existing object.")
  55. is_filterable = models.BooleanField(default=True, help_text="This field can be used to filter objects.")
  56. default = models.CharField(max_length=100, blank=True, help_text="Default value for the field. Use \"true\" or "
  57. "\"false\" for booleans. N/A for selection "
  58. "fields.")
  59. weight = models.PositiveSmallIntegerField(default=100, help_text="Fields with higher weights appear lower in a "
  60. "form")
  61. class Meta:
  62. ordering = ['weight', 'name']
  63. def __str__(self):
  64. return self.label or self.name.replace('_', ' ').capitalize()
  65. def serialize_value(self, value):
  66. """
  67. Serialize the given value to a string suitable for storage as a CustomFieldValue
  68. """
  69. if value is None:
  70. return ''
  71. if self.type == CF_TYPE_BOOLEAN:
  72. return str(int(bool(value)))
  73. if self.type == CF_TYPE_DATE:
  74. # Could be date/datetime object or string
  75. try:
  76. return value.strftime('%Y-%m-%d')
  77. except AttributeError:
  78. return value
  79. if self.type == CF_TYPE_SELECT:
  80. # Could be ModelChoiceField or TypedChoiceField
  81. return str(value.id) if hasattr(value, 'id') else str(value)
  82. return value
  83. def deserialize_value(self, serialized_value):
  84. """
  85. Convert a string into the object it represents depending on the type of field
  86. """
  87. if serialized_value is '':
  88. return None
  89. if self.type == CF_TYPE_INTEGER:
  90. return int(serialized_value)
  91. if self.type == CF_TYPE_BOOLEAN:
  92. return bool(int(serialized_value))
  93. if self.type == CF_TYPE_DATE:
  94. # Read date as YYYY-MM-DD
  95. return date(*[int(n) for n in serialized_value.split('-')])
  96. if self.type == CF_TYPE_SELECT:
  97. return self.choices.get(pk=int(serialized_value))
  98. return serialized_value
  99. @python_2_unicode_compatible
  100. class CustomFieldValue(models.Model):
  101. field = models.ForeignKey('CustomField', related_name='values', on_delete=models.CASCADE)
  102. obj_type = models.ForeignKey(ContentType, related_name='+', on_delete=models.PROTECT)
  103. obj_id = models.PositiveIntegerField()
  104. obj = GenericForeignKey('obj_type', 'obj_id')
  105. serialized_value = models.CharField(max_length=255)
  106. class Meta:
  107. ordering = ['obj_type', 'obj_id']
  108. unique_together = ['field', 'obj_type', 'obj_id']
  109. def __str__(self):
  110. return '{} {}'.format(self.obj, self.field)
  111. @property
  112. def value(self):
  113. return self.field.deserialize_value(self.serialized_value)
  114. @value.setter
  115. def value(self, value):
  116. self.serialized_value = self.field.serialize_value(value)
  117. def save(self, *args, **kwargs):
  118. # Delete this object if it no longer has a value to store
  119. if self.pk and self.value is None:
  120. self.delete()
  121. else:
  122. super(CustomFieldValue, self).save(*args, **kwargs)
  123. @python_2_unicode_compatible
  124. class CustomFieldChoice(models.Model):
  125. field = models.ForeignKey('CustomField', related_name='choices', limit_choices_to={'type': CF_TYPE_SELECT},
  126. on_delete=models.CASCADE)
  127. value = models.CharField(max_length=100)
  128. weight = models.PositiveSmallIntegerField(default=100, help_text="Higher weights appear lower in the list")
  129. class Meta:
  130. ordering = ['field', 'weight', 'value']
  131. unique_together = ['field', 'value']
  132. def __str__(self):
  133. return self.value
  134. def clean(self):
  135. if self.field.type != CF_TYPE_SELECT:
  136. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  137. def delete(self, using=None, keep_parents=False):
  138. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  139. pk = self.pk
  140. super(CustomFieldChoice, self).delete(using, keep_parents)
  141. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  142. #
  143. # Graphs
  144. #
  145. @python_2_unicode_compatible
  146. class Graph(models.Model):
  147. type = models.PositiveSmallIntegerField(choices=GRAPH_TYPE_CHOICES)
  148. weight = models.PositiveSmallIntegerField(default=1000)
  149. name = models.CharField(max_length=100, verbose_name='Name')
  150. source = models.CharField(max_length=500, verbose_name='Source URL')
  151. link = models.URLField(verbose_name='Link URL', blank=True)
  152. class Meta:
  153. ordering = ['type', 'weight', 'name']
  154. def __str__(self):
  155. return self.name
  156. def embed_url(self, obj):
  157. template = Template(self.source)
  158. return template.render(Context({'obj': obj}))
  159. def embed_link(self, obj):
  160. if self.link is None:
  161. return ''
  162. template = Template(self.link)
  163. return template.render(Context({'obj': obj}))
  164. #
  165. # Export templates
  166. #
  167. @python_2_unicode_compatible
  168. class ExportTemplate(models.Model):
  169. content_type = models.ForeignKey(
  170. ContentType, limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS}, on_delete=models.CASCADE
  171. )
  172. name = models.CharField(max_length=100)
  173. description = models.CharField(max_length=200, blank=True)
  174. template_code = models.TextField()
  175. mime_type = models.CharField(max_length=15, blank=True)
  176. file_extension = models.CharField(max_length=15, blank=True)
  177. class Meta:
  178. ordering = ['content_type', 'name']
  179. unique_together = [
  180. ['content_type', 'name']
  181. ]
  182. def __str__(self):
  183. return '{}: {}'.format(self.content_type, self.name)
  184. def to_response(self, context_dict, filename):
  185. """
  186. Render the template to an HTTP response, delivered as a named file attachment
  187. """
  188. template = Template(self.template_code)
  189. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  190. output = template.render(Context(context_dict))
  191. # Replace CRLF-style line terminators
  192. output = output.replace('\r\n', '\n')
  193. response = HttpResponse(output, content_type=mime_type)
  194. if self.file_extension:
  195. filename += '.{}'.format(self.file_extension)
  196. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  197. return response
  198. #
  199. # Topology maps
  200. #
  201. @python_2_unicode_compatible
  202. class TopologyMap(models.Model):
  203. name = models.CharField(max_length=50, unique=True)
  204. slug = models.SlugField(unique=True)
  205. site = models.ForeignKey('dcim.Site', related_name='topology_maps', blank=True, null=True, on_delete=models.CASCADE)
  206. device_patterns = models.TextField(
  207. help_text="Identify devices to include in the diagram using regular expressions, one per line. Each line will "
  208. "result in a new tier of the drawing. Separate multiple regexes within a line using semicolons. "
  209. "Devices will be rendered in the order they are defined."
  210. )
  211. description = models.CharField(max_length=100, blank=True)
  212. class Meta:
  213. ordering = ['name']
  214. def __str__(self):
  215. return self.name
  216. @property
  217. def device_sets(self):
  218. if not self.device_patterns:
  219. return None
  220. return [line.strip() for line in self.device_patterns.split('\n')]
  221. def render(self, img_format='png'):
  222. from circuits.models import CircuitTermination
  223. from dcim.models import CONNECTION_STATUS_CONNECTED, Device, InterfaceConnection
  224. # Construct the graph
  225. graph = graphviz.Graph()
  226. graph.graph_attr['ranksep'] = '1'
  227. seen = set()
  228. for i, device_set in enumerate(self.device_sets):
  229. subgraph = graphviz.Graph(name='sg{}'.format(i))
  230. subgraph.graph_attr['rank'] = 'same'
  231. # Add a pseudonode for each device_set to enforce hierarchical layout
  232. subgraph.node('set{}'.format(i), label='', shape='none', width='0')
  233. if i:
  234. graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
  235. # Add each device to the graph
  236. devices = []
  237. for query in device_set.strip(';').split(';'): # Split regexes on semicolons
  238. devices += Device.objects.filter(name__regex=query).select_related('device_role')
  239. # Remove duplicate devices
  240. devices = [d for d in devices if d.id not in seen]
  241. seen.update([d.id for d in devices])
  242. for d in devices:
  243. bg_color = '#{}'.format(d.device_role.color)
  244. fg_color = '#{}'.format(foreground_color(d.device_role.color))
  245. subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans')
  246. # Add an invisible connection to each successive device in a set to enforce horizontal order
  247. for j in range(0, len(devices) - 1):
  248. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  249. graph.subgraph(subgraph)
  250. # Compile list of all devices
  251. device_superset = Q()
  252. for device_set in self.device_sets:
  253. for query in device_set.split(';'): # Split regexes on semicolons
  254. device_superset = device_superset | Q(name__regex=query)
  255. # Add all interface connections to the graph
  256. devices = Device.objects.filter(*(device_superset,))
  257. connections = InterfaceConnection.objects.filter(
  258. interface_a__device__in=devices, interface_b__device__in=devices
  259. )
  260. for c in connections:
  261. style = 'solid' if c.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  262. graph.edge(c.interface_a.device.name, c.interface_b.device.name, style=style)
  263. # Add all circuits to the graph
  264. for termination in CircuitTermination.objects.filter(term_side='A', interface__device__in=devices):
  265. peer_termination = termination.get_peer_termination()
  266. if (peer_termination is not None and peer_termination.interface is not None and
  267. peer_termination.interface.device in devices):
  268. graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  269. return graph.pipe(format=img_format)
  270. #
  271. # Image attachments
  272. #
  273. def image_upload(instance, filename):
  274. path = 'image-attachments/'
  275. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  276. extension = filename.rsplit('.')[-1].lower()
  277. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  278. filename = '.'.join([instance.name, extension])
  279. elif instance.name:
  280. filename = instance.name
  281. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  282. @python_2_unicode_compatible
  283. class ImageAttachment(models.Model):
  284. """
  285. An uploaded image which is associated with an object.
  286. """
  287. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  288. object_id = models.PositiveIntegerField()
  289. parent = GenericForeignKey('content_type', 'object_id')
  290. image = models.ImageField(upload_to=image_upload, height_field='image_height', width_field='image_width')
  291. image_height = models.PositiveSmallIntegerField()
  292. image_width = models.PositiveSmallIntegerField()
  293. name = models.CharField(max_length=50, blank=True)
  294. created = models.DateTimeField(auto_now_add=True)
  295. class Meta:
  296. ordering = ['name']
  297. def __str__(self):
  298. if self.name:
  299. return self.name
  300. filename = self.image.name.rsplit('/', 1)[-1]
  301. return filename.split('_', 2)[2]
  302. def delete(self, *args, **kwargs):
  303. _name = self.image.name
  304. super(ImageAttachment, self).delete(*args, **kwargs)
  305. # Delete file from disk
  306. self.image.delete(save=False)
  307. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  308. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  309. self.image.name = _name
  310. @property
  311. def size(self):
  312. """
  313. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  314. """
  315. try:
  316. return self.image.size
  317. except OSError:
  318. return None
  319. #
  320. # Report results
  321. #
  322. class ReportResult(models.Model):
  323. """
  324. This model stores the results from running a user-defined report.
  325. """
  326. report = models.CharField(max_length=255, unique=True)
  327. created = models.DateTimeField(auto_now_add=True)
  328. user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='+', blank=True, null=True)
  329. failed = models.BooleanField()
  330. data = JSONField()
  331. class Meta:
  332. ordering = ['report']
  333. #
  334. # User actions
  335. #
  336. class UserActionManager(models.Manager):
  337. # Actions affecting a single object
  338. def log_action(self, user, obj, action, message):
  339. self.model.objects.create(
  340. content_type=ContentType.objects.get_for_model(obj),
  341. object_id=obj.pk,
  342. user=user,
  343. action=action,
  344. message=message,
  345. )
  346. def log_create(self, user, obj, message=''):
  347. self.log_action(user, obj, ACTION_CREATE, message)
  348. def log_edit(self, user, obj, message=''):
  349. self.log_action(user, obj, ACTION_EDIT, message)
  350. def log_delete(self, user, obj, message=''):
  351. self.log_action(user, obj, ACTION_DELETE, message)
  352. # Actions affecting multiple objects
  353. def log_bulk_action(self, user, content_type, action, message):
  354. self.model.objects.create(
  355. content_type=content_type,
  356. user=user,
  357. action=action,
  358. message=message,
  359. )
  360. def log_import(self, user, content_type, message=''):
  361. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  362. def log_bulk_create(self, user, content_type, message=''):
  363. self.log_bulk_action(user, content_type, ACTION_BULK_CREATE, message)
  364. def log_bulk_edit(self, user, content_type, message=''):
  365. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  366. def log_bulk_delete(self, user, content_type, message=''):
  367. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  368. @python_2_unicode_compatible
  369. class UserAction(models.Model):
  370. """
  371. A record of an action (add, edit, or delete) performed on an object by a User.
  372. """
  373. time = models.DateTimeField(auto_now_add=True, editable=False)
  374. user = models.ForeignKey(User, related_name='actions', on_delete=models.CASCADE)
  375. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  376. object_id = models.PositiveIntegerField(blank=True, null=True)
  377. action = models.PositiveSmallIntegerField(choices=ACTION_CHOICES)
  378. message = models.TextField(blank=True)
  379. objects = UserActionManager()
  380. class Meta:
  381. ordering = ['-time']
  382. def __str__(self):
  383. if self.message:
  384. return '{} {}'.format(self.user, self.message)
  385. return '{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  386. def icon(self):
  387. if self.action in [ACTION_CREATE, ACTION_BULK_CREATE, ACTION_IMPORT]:
  388. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  389. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  390. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  391. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  392. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  393. else:
  394. return ''