models.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. try:
  140. return self.choices.get(pk=int(serialized_value))
  141. except CustomFieldChoice.DoesNotExist:
  142. return None
  143. return serialized_value
  144. @python_2_unicode_compatible
  145. class CustomFieldValue(models.Model):
  146. field = models.ForeignKey('CustomField', related_name='values')
  147. obj_type = models.ForeignKey(ContentType, related_name='+', on_delete=models.PROTECT)
  148. obj_id = models.PositiveIntegerField()
  149. obj = GenericForeignKey('obj_type', 'obj_id')
  150. serialized_value = models.CharField(max_length=255)
  151. class Meta:
  152. ordering = ['obj_type', 'obj_id']
  153. unique_together = ['field', 'obj_type', 'obj_id']
  154. def __str__(self):
  155. return u'{} {}'.format(self.obj, self.field)
  156. @property
  157. def value(self):
  158. return self.field.deserialize_value(self.serialized_value)
  159. @value.setter
  160. def value(self, value):
  161. self.serialized_value = self.field.serialize_value(value)
  162. def save(self, *args, **kwargs):
  163. # Delete this object if it no longer has a value to store
  164. if self.pk and self.value is None:
  165. self.delete()
  166. else:
  167. super(CustomFieldValue, self).save(*args, **kwargs)
  168. @python_2_unicode_compatible
  169. class CustomFieldChoice(models.Model):
  170. field = models.ForeignKey('CustomField', related_name='choices', limit_choices_to={'type': CF_TYPE_SELECT},
  171. on_delete=models.CASCADE)
  172. value = models.CharField(max_length=100)
  173. weight = models.PositiveSmallIntegerField(default=100, help_text="Higher weights appear lower in the list")
  174. class Meta:
  175. ordering = ['field', 'weight', 'value']
  176. unique_together = ['field', 'value']
  177. def __str__(self):
  178. return self.value
  179. def clean(self):
  180. if self.field.type != CF_TYPE_SELECT:
  181. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  182. def delete(self, using=None, keep_parents=False):
  183. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  184. pk = self.pk
  185. super(CustomFieldChoice, self).delete(using, keep_parents)
  186. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  187. #
  188. # Graphs
  189. #
  190. @python_2_unicode_compatible
  191. class Graph(models.Model):
  192. type = models.PositiveSmallIntegerField(choices=GRAPH_TYPE_CHOICES)
  193. weight = models.PositiveSmallIntegerField(default=1000)
  194. name = models.CharField(max_length=100, verbose_name='Name')
  195. source = models.CharField(max_length=500, verbose_name='Source URL')
  196. link = models.URLField(verbose_name='Link URL', blank=True)
  197. class Meta:
  198. ordering = ['type', 'weight', 'name']
  199. def __str__(self):
  200. return self.name
  201. def embed_url(self, obj):
  202. template = Template(self.source)
  203. return template.render(Context({'obj': obj}))
  204. def embed_link(self, obj):
  205. if self.link is None:
  206. return ''
  207. template = Template(self.link)
  208. return template.render(Context({'obj': obj}))
  209. #
  210. # Export templates
  211. #
  212. @python_2_unicode_compatible
  213. class ExportTemplate(models.Model):
  214. content_type = models.ForeignKey(ContentType, limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS})
  215. name = models.CharField(max_length=100)
  216. description = models.CharField(max_length=200, blank=True)
  217. template_code = models.TextField()
  218. mime_type = models.CharField(max_length=15, blank=True)
  219. file_extension = models.CharField(max_length=15, blank=True)
  220. class Meta:
  221. ordering = ['content_type', 'name']
  222. unique_together = [
  223. ['content_type', 'name']
  224. ]
  225. def __str__(self):
  226. return u'{}: {}'.format(self.content_type, self.name)
  227. def to_response(self, context_dict, filename):
  228. """
  229. Render the template to an HTTP response, delivered as a named file attachment
  230. """
  231. template = Template(self.template_code)
  232. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  233. output = template.render(Context(context_dict))
  234. # Replace CRLF-style line terminators
  235. output = output.replace('\r\n', '\n')
  236. response = HttpResponse(output, content_type=mime_type)
  237. if self.file_extension:
  238. filename += '.{}'.format(self.file_extension)
  239. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  240. return response
  241. #
  242. # Topology maps
  243. #
  244. @python_2_unicode_compatible
  245. class TopologyMap(models.Model):
  246. name = models.CharField(max_length=50, unique=True)
  247. slug = models.SlugField(unique=True)
  248. site = models.ForeignKey('dcim.Site', related_name='topology_maps', blank=True, null=True)
  249. device_patterns = models.TextField(
  250. help_text="Identify devices to include in the diagram using regular expressions, one per line. Each line will "
  251. "result in a new tier of the drawing. Separate multiple regexes within a line using semicolons. "
  252. "Devices will be rendered in the order they are defined."
  253. )
  254. description = models.CharField(max_length=100, blank=True)
  255. class Meta:
  256. ordering = ['name']
  257. def __str__(self):
  258. return self.name
  259. @property
  260. def device_sets(self):
  261. if not self.device_patterns:
  262. return None
  263. return [line.strip() for line in self.device_patterns.split('\n')]
  264. def render(self, img_format='png'):
  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)
  280. for d in devices:
  281. subgraph.node(d.name)
  282. # Add an invisible connection to each successive device in a set to enforce horizontal order
  283. for j in range(0, len(devices) - 1):
  284. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  285. graph.subgraph(subgraph)
  286. # Compile list of all devices
  287. device_superset = Q()
  288. for device_set in self.device_sets:
  289. for query in device_set.split(';'): # Split regexes on semicolons
  290. device_superset = device_superset | Q(name__regex=query)
  291. # Add all connections to the graph
  292. devices = Device.objects.filter(*(device_superset,))
  293. connections = InterfaceConnection.objects.filter(
  294. interface_a__device__in=devices, interface_b__device__in=devices
  295. )
  296. for c in connections:
  297. graph.edge(c.interface_a.device.name, c.interface_b.device.name)
  298. return graph.pipe(format=img_format)
  299. #
  300. # Image attachments
  301. #
  302. def image_upload(instance, filename):
  303. path = 'image-attachments/'
  304. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  305. extension = filename.rsplit('.')[-1]
  306. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  307. filename = '.'.join([instance.name, extension])
  308. elif instance.name:
  309. filename = instance.name
  310. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  311. @python_2_unicode_compatible
  312. class ImageAttachment(models.Model):
  313. """
  314. An uploaded image which is associated with an object.
  315. """
  316. content_type = models.ForeignKey(ContentType)
  317. object_id = models.PositiveIntegerField()
  318. parent = GenericForeignKey('content_type', 'object_id')
  319. image = models.ImageField(upload_to=image_upload, height_field='image_height', width_field='image_width')
  320. image_height = models.PositiveSmallIntegerField()
  321. image_width = models.PositiveSmallIntegerField()
  322. name = models.CharField(max_length=50, blank=True)
  323. created = models.DateTimeField(auto_now_add=True)
  324. class Meta:
  325. ordering = ['name']
  326. def __str__(self):
  327. if self.name:
  328. return self.name
  329. filename = self.image.name.rsplit('/', 1)[-1]
  330. return filename.split('_', 2)[2]
  331. def delete(self, *args, **kwargs):
  332. _name = self.image.name
  333. super(ImageAttachment, self).delete(*args, **kwargs)
  334. # Delete file from disk
  335. self.image.delete(save=False)
  336. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  337. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  338. self.image.name = _name
  339. #
  340. # User actions
  341. #
  342. class UserActionManager(models.Manager):
  343. # Actions affecting a single object
  344. def log_action(self, user, obj, action, message):
  345. self.model.objects.create(
  346. content_type=ContentType.objects.get_for_model(obj),
  347. object_id=obj.pk,
  348. user=user,
  349. action=action,
  350. message=message,
  351. )
  352. def log_create(self, user, obj, message=''):
  353. self.log_action(user, obj, ACTION_CREATE, message)
  354. def log_edit(self, user, obj, message=''):
  355. self.log_action(user, obj, ACTION_EDIT, message)
  356. def log_delete(self, user, obj, message=''):
  357. self.log_action(user, obj, ACTION_DELETE, message)
  358. # Actions affecting multiple objects
  359. def log_bulk_action(self, user, content_type, action, message):
  360. self.model.objects.create(
  361. content_type=content_type,
  362. user=user,
  363. action=action,
  364. message=message,
  365. )
  366. def log_import(self, user, content_type, message=''):
  367. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  368. def log_bulk_create(self, user, content_type, message=''):
  369. self.log_bulk_action(user, content_type, ACTION_BULK_CREATE, message)
  370. def log_bulk_edit(self, user, content_type, message=''):
  371. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  372. def log_bulk_delete(self, user, content_type, message=''):
  373. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  374. @python_2_unicode_compatible
  375. class UserAction(models.Model):
  376. """
  377. A record of an action (add, edit, or delete) performed on an object by a User.
  378. """
  379. time = models.DateTimeField(auto_now_add=True, editable=False)
  380. user = models.ForeignKey(User, related_name='actions', on_delete=models.CASCADE)
  381. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  382. object_id = models.PositiveIntegerField(blank=True, null=True)
  383. action = models.PositiveSmallIntegerField(choices=ACTION_CHOICES)
  384. message = models.TextField(blank=True)
  385. objects = UserActionManager()
  386. class Meta:
  387. ordering = ['-time']
  388. def __str__(self):
  389. if self.message:
  390. return u'{} {}'.format(self.user, self.message)
  391. return u'{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  392. def icon(self):
  393. if self.action in [ACTION_CREATE, ACTION_BULK_CREATE, ACTION_IMPORT]:
  394. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  395. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  396. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  397. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  398. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  399. else:
  400. return ''