models.py 12 KB

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