models.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. from collections import OrderedDict
  2. from datetime import date
  3. from django.contrib.auth.models import User
  4. from django.contrib.contenttypes.fields import GenericForeignKey
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.validators import ValidationError
  7. from django.db import models
  8. from django.http import HttpResponse
  9. from django.template import Template, Context
  10. from django.utils.safestring import mark_safe
  11. CUSTOMFIELD_MODELS = (
  12. 'site', 'rack', 'device', # DCIM
  13. 'aggregate', 'prefix', 'ipaddress', 'vlan', 'vrf', # IPAM
  14. 'provider', 'circuit', # Circuits
  15. 'tenant', # Tenants
  16. )
  17. CF_TYPE_TEXT = 100
  18. CF_TYPE_INTEGER = 200
  19. CF_TYPE_BOOLEAN = 300
  20. CF_TYPE_DATE = 400
  21. CF_TYPE_URL = 500
  22. CF_TYPE_SELECT = 600
  23. CUSTOMFIELD_TYPE_CHOICES = (
  24. (CF_TYPE_TEXT, 'Text'),
  25. (CF_TYPE_INTEGER, 'Integer'),
  26. (CF_TYPE_BOOLEAN, 'Boolean (true/false)'),
  27. (CF_TYPE_DATE, 'Date'),
  28. (CF_TYPE_URL, 'URL'),
  29. (CF_TYPE_SELECT, 'Selection'),
  30. )
  31. GRAPH_TYPE_INTERFACE = 100
  32. GRAPH_TYPE_PROVIDER = 200
  33. GRAPH_TYPE_SITE = 300
  34. GRAPH_TYPE_CHOICES = (
  35. (GRAPH_TYPE_INTERFACE, 'Interface'),
  36. (GRAPH_TYPE_PROVIDER, 'Provider'),
  37. (GRAPH_TYPE_SITE, 'Site'),
  38. )
  39. EXPORTTEMPLATE_MODELS = [
  40. 'site', 'rack', 'device', 'consoleport', 'powerport', 'interfaceconnection', # DCIM
  41. 'aggregate', 'prefix', 'ipaddress', 'vlan', # IPAM
  42. 'provider', 'circuit', # Circuits
  43. 'tenant', # Tenants
  44. ]
  45. ACTION_CREATE = 1
  46. ACTION_IMPORT = 2
  47. ACTION_EDIT = 3
  48. ACTION_BULK_EDIT = 4
  49. ACTION_DELETE = 5
  50. ACTION_BULK_DELETE = 6
  51. ACTION_CHOICES = (
  52. (ACTION_CREATE, 'created'),
  53. (ACTION_IMPORT, 'imported'),
  54. (ACTION_EDIT, 'modified'),
  55. (ACTION_BULK_EDIT, 'bulk edited'),
  56. (ACTION_DELETE, 'deleted'),
  57. (ACTION_BULK_DELETE, 'bulk deleted')
  58. )
  59. class CustomFieldModel(object):
  60. def cf(self):
  61. """
  62. Name-based CustomFieldValue accessor for use in templates
  63. """
  64. if not hasattr(self, 'get_custom_fields'):
  65. return dict()
  66. return {field.name: value for field, value in self.get_custom_fields().items()}
  67. def get_custom_fields(self):
  68. """
  69. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  70. """
  71. # Find all custom fields applicable to this type of object
  72. content_type = ContentType.objects.get_for_model(self)
  73. fields = CustomField.objects.filter(obj_type=content_type)
  74. # If the object exists, populate its custom fields with values
  75. if hasattr(self, 'pk'):
  76. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  77. values_dict = {cfv.field_id: cfv.value for cfv in values}
  78. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  79. else:
  80. return OrderedDict([(field, None) for field in fields])
  81. class CustomField(models.Model):
  82. obj_type = models.ManyToManyField(ContentType, related_name='custom_fields', verbose_name='Object(s)',
  83. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  84. help_text="The object(s) to which this field applies.")
  85. type = models.PositiveSmallIntegerField(choices=CUSTOMFIELD_TYPE_CHOICES, default=CF_TYPE_TEXT)
  86. name = models.CharField(max_length=50, unique=True)
  87. label = models.CharField(max_length=50, blank=True, help_text="Name of the field as displayed to users (if not "
  88. "provided, the field's name will be used)")
  89. description = models.CharField(max_length=100, blank=True)
  90. required = models.BooleanField(default=False, help_text="Determines whether this field is required when creating "
  91. "new objects or editing an existing object.")
  92. is_filterable = models.BooleanField(default=True, help_text="This field can be used to filter objects.")
  93. default = models.CharField(max_length=100, blank=True, help_text="Default value for the field. Use \"true\" or "
  94. "\"false\" for booleans. N/A for selection "
  95. "fields.")
  96. weight = models.PositiveSmallIntegerField(default=100, help_text="Fields with higher weights appear lower in a "
  97. "form")
  98. class Meta:
  99. ordering = ['weight', 'name']
  100. def __unicode__(self):
  101. return self.label or self.name.replace('_', ' ').capitalize()
  102. def serialize_value(self, value):
  103. """
  104. Serialize the given value to a string suitable for storage as a CustomFieldValue
  105. """
  106. if value is None:
  107. return ''
  108. if self.type == CF_TYPE_BOOLEAN:
  109. return str(int(bool(value)))
  110. if self.type == CF_TYPE_DATE:
  111. return value.strftime('%Y-%m-%d')
  112. if self.type == CF_TYPE_SELECT:
  113. # Could be ModelChoiceField or TypedChoiceField
  114. return str(value.id) if hasattr(value, 'id') else str(value)
  115. return value
  116. def deserialize_value(self, serialized_value):
  117. """
  118. Convert a string into the object it represents depending on the type of field
  119. """
  120. if serialized_value is '':
  121. return None
  122. if self.type == CF_TYPE_INTEGER:
  123. return int(serialized_value)
  124. if self.type == CF_TYPE_BOOLEAN:
  125. return bool(int(serialized_value))
  126. if self.type == CF_TYPE_DATE:
  127. # Read date as YYYY-MM-DD
  128. return date(*[int(n) for n in serialized_value.split('-')])
  129. if self.type == CF_TYPE_SELECT:
  130. try:
  131. return self.choices.get(pk=int(serialized_value))
  132. except CustomFieldChoice.DoesNotExist:
  133. return None
  134. return serialized_value
  135. class CustomFieldValue(models.Model):
  136. field = models.ForeignKey('CustomField', related_name='values')
  137. obj_type = models.ForeignKey(ContentType, related_name='+', on_delete=models.PROTECT)
  138. obj_id = models.PositiveIntegerField()
  139. obj = GenericForeignKey('obj_type', 'obj_id')
  140. serialized_value = models.CharField(max_length=255)
  141. class Meta:
  142. ordering = ['obj_type', 'obj_id']
  143. unique_together = ['field', 'obj_type', 'obj_id']
  144. def __unicode__(self):
  145. return '{} {}'.format(self.obj, self.field)
  146. @property
  147. def value(self):
  148. return self.field.deserialize_value(self.serialized_value)
  149. @value.setter
  150. def value(self, value):
  151. self.serialized_value = self.field.serialize_value(value)
  152. def save(self, *args, **kwargs):
  153. # Delete this object if it no longer has a value to store
  154. if self.pk and self.value is None:
  155. self.delete()
  156. else:
  157. super(CustomFieldValue, self).save(*args, **kwargs)
  158. class CustomFieldChoice(models.Model):
  159. field = models.ForeignKey('CustomField', related_name='choices', limit_choices_to={'type': CF_TYPE_SELECT},
  160. on_delete=models.CASCADE)
  161. value = models.CharField(max_length=100)
  162. weight = models.PositiveSmallIntegerField(default=100, help_text="Higher weights appear lower in the list")
  163. class Meta:
  164. ordering = ['field', 'weight', 'value']
  165. unique_together = ['field', 'value']
  166. def __unicode__(self):
  167. return self.value
  168. def clean(self):
  169. if self.field.type != CF_TYPE_SELECT:
  170. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  171. def delete(self, using=None, keep_parents=False):
  172. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  173. pk = self.pk
  174. super(CustomFieldChoice, self).delete(using, keep_parents)
  175. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  176. class Graph(models.Model):
  177. type = models.PositiveSmallIntegerField(choices=GRAPH_TYPE_CHOICES)
  178. weight = models.PositiveSmallIntegerField(default=1000)
  179. name = models.CharField(max_length=100, verbose_name='Name')
  180. source = models.CharField(max_length=500, verbose_name='Source URL')
  181. link = models.URLField(verbose_name='Link URL', blank=True)
  182. class Meta:
  183. ordering = ['type', 'weight', 'name']
  184. def __unicode__(self):
  185. return self.name
  186. def embed_url(self, obj):
  187. template = Template(self.source)
  188. return template.render(Context({'obj': obj}))
  189. def embed_link(self, obj):
  190. if self.link is None:
  191. return ''
  192. template = Template(self.link)
  193. return template.render(Context({'obj': obj}))
  194. class ExportTemplate(models.Model):
  195. content_type = models.ForeignKey(ContentType, limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS})
  196. name = models.CharField(max_length=100)
  197. description = models.CharField(max_length=200, blank=True)
  198. template_code = models.TextField()
  199. mime_type = models.CharField(max_length=15, blank=True)
  200. file_extension = models.CharField(max_length=15, blank=True)
  201. class Meta:
  202. ordering = ['content_type', 'name']
  203. unique_together = [
  204. ['content_type', 'name']
  205. ]
  206. def __unicode__(self):
  207. return u'{}: {}'.format(self.content_type, self.name)
  208. def to_response(self, context_dict, filename):
  209. """
  210. Render the template to an HTTP response, delivered as a named file attachment
  211. """
  212. template = Template(self.template_code)
  213. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  214. output = template.render(Context(context_dict))
  215. # Replace CRLF-style line terminators
  216. output = output.replace('\r\n', '\n')
  217. response = HttpResponse(output, content_type=mime_type)
  218. if self.file_extension:
  219. filename += '.{}'.format(self.file_extension)
  220. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  221. return response
  222. class TopologyMap(models.Model):
  223. name = models.CharField(max_length=50, unique=True)
  224. slug = models.SlugField(unique=True)
  225. site = models.ForeignKey('dcim.Site', related_name='topology_maps', blank=True, null=True)
  226. device_patterns = models.TextField(
  227. help_text="Identify devices to include in the diagram using regular expressions, one per line. Each line will "
  228. "result in a new tier of the drawing. Separate multiple regexes within a line using semicolons. "
  229. "Devices will be rendered in the order they are defined."
  230. )
  231. description = models.CharField(max_length=100, blank=True)
  232. class Meta:
  233. ordering = ['name']
  234. def __unicode__(self):
  235. return self.name
  236. @property
  237. def device_sets(self):
  238. if not self.device_patterns:
  239. return None
  240. return [line.strip() for line in self.device_patterns.split('\n')]
  241. class UserActionManager(models.Manager):
  242. # Actions affecting a single object
  243. def log_action(self, user, obj, action, message):
  244. self.model.objects.create(
  245. content_type=ContentType.objects.get_for_model(obj),
  246. object_id=obj.pk,
  247. user=user,
  248. action=action,
  249. message=message,
  250. )
  251. def log_create(self, user, obj, message=''):
  252. self.log_action(user, obj, ACTION_CREATE, message)
  253. def log_edit(self, user, obj, message=''):
  254. self.log_action(user, obj, ACTION_EDIT, message)
  255. def log_delete(self, user, obj, message=''):
  256. self.log_action(user, obj, ACTION_DELETE, message)
  257. # Actions affecting multiple objects
  258. def log_bulk_action(self, user, content_type, action, message):
  259. self.model.objects.create(
  260. content_type=content_type,
  261. user=user,
  262. action=action,
  263. message=message,
  264. )
  265. def log_import(self, user, content_type, message=''):
  266. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  267. def log_bulk_edit(self, user, content_type, message=''):
  268. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  269. def log_bulk_delete(self, user, content_type, message=''):
  270. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  271. class UserAction(models.Model):
  272. """
  273. A record of an action (add, edit, or delete) performed on an object by a User.
  274. """
  275. time = models.DateTimeField(auto_now_add=True, editable=False)
  276. user = models.ForeignKey(User, related_name='actions', on_delete=models.CASCADE)
  277. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  278. object_id = models.PositiveIntegerField(blank=True, null=True)
  279. action = models.PositiveSmallIntegerField(choices=ACTION_CHOICES)
  280. message = models.TextField(blank=True)
  281. objects = UserActionManager()
  282. class Meta:
  283. ordering = ['-time']
  284. def __unicode__(self):
  285. if self.message:
  286. return u'{} {}'.format(self.user, self.message)
  287. return u'{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  288. def icon(self):
  289. if self.action in [ACTION_CREATE, ACTION_IMPORT]:
  290. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  291. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  292. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  293. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  294. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  295. else:
  296. return ''