models.py 13 KB

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