models.py 18 KB

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