models.py 19 KB

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