models.py 14 KB

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