models.py 16 KB

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