models.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. from dcim.models import Site
  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 CustomField(models.Model):
  57. obj_type = models.ManyToManyField(ContentType, related_name='custom_fields',
  58. limit_choices_to={'model__in': CUSTOMFIELD_MODELS})
  59. type = models.PositiveSmallIntegerField(choices=CUSTOMFIELD_TYPE_CHOICES, default=CF_TYPE_TEXT)
  60. name = models.CharField(max_length=50, unique=True)
  61. label = models.CharField(max_length=50, blank=True, help_text="Name of the field as displayed to users")
  62. description = models.CharField(max_length=100, blank=True)
  63. required = models.BooleanField(default=False, help_text="This field is required when creating new objects")
  64. default = models.CharField(max_length=100, blank=True, help_text="Default value for the field")
  65. class Meta:
  66. ordering = ['name']
  67. def __unicode__(self):
  68. return self.label or self.name
  69. class CustomFieldValue(models.Model):
  70. field = models.ForeignKey('CustomField', related_name='values')
  71. obj_type = models.ForeignKey(ContentType, related_name='+', on_delete=models.PROTECT)
  72. obj_id = models.PositiveIntegerField()
  73. obj = GenericForeignKey('obj_type', 'obj_id')
  74. val_int = models.BigIntegerField(blank=True, null=True)
  75. val_char = models.CharField(max_length=100, blank=True)
  76. val_date = models.DateField(blank=True, null=True)
  77. class Meta:
  78. ordering = ['obj_type', 'obj_id']
  79. def __unicode__(self):
  80. return self.value
  81. @property
  82. def value(self):
  83. if self.field.type == CF_TYPE_INTEGER:
  84. return self.val_int
  85. if self.field.type == CF_TYPE_BOOLEAN:
  86. return bool(self.val_int) if self.val_int is not None else None
  87. if self.field.type == CF_TYPE_DATE:
  88. return self.val_date
  89. if self.field.type == CF_TYPE_SELECT:
  90. return CustomFieldChoice.objects.get(pk=self.val_int)
  91. return self.val_char
  92. @value.setter
  93. def value(self, value):
  94. if self.field.type in [CF_TYPE_INTEGER, CF_TYPE_SELECT]:
  95. self.val_int = value
  96. elif self.field.type == CF_TYPE_BOOLEAN:
  97. self.val_int = bool(value) if value else None
  98. elif self.field.type == CF_TYPE_DATE:
  99. self.val_date = value
  100. else:
  101. self.val_char = value
  102. class CustomFieldChoice(models.Model):
  103. field = models.ForeignKey('CustomField', related_name='choices', limit_choices_to={'type': CF_TYPE_SELECT},
  104. on_delete=models.CASCADE)
  105. value = models.CharField(max_length=100)
  106. weight = models.PositiveSmallIntegerField(default=100)
  107. class Meta:
  108. ordering = ['field', 'weight', 'value']
  109. unique_together = ['field', 'value']
  110. def __unicode__(self):
  111. return self.value
  112. def clean(self):
  113. if self.field.type != CF_TYPE_SELECT:
  114. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  115. class Graph(models.Model):
  116. type = models.PositiveSmallIntegerField(choices=GRAPH_TYPE_CHOICES)
  117. weight = models.PositiveSmallIntegerField(default=1000)
  118. name = models.CharField(max_length=100, verbose_name='Name')
  119. source = models.CharField(max_length=500, verbose_name='Source URL')
  120. link = models.URLField(verbose_name='Link URL', blank=True)
  121. class Meta:
  122. ordering = ['type', 'weight', 'name']
  123. def __unicode__(self):
  124. return self.name
  125. def embed_url(self, obj):
  126. template = Template(self.source)
  127. return template.render(Context({'obj': obj}))
  128. def embed_link(self, obj):
  129. if self.link is None:
  130. return ''
  131. template = Template(self.link)
  132. return template.render(Context({'obj': obj}))
  133. class ExportTemplate(models.Model):
  134. content_type = models.ForeignKey(ContentType, limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS})
  135. name = models.CharField(max_length=200)
  136. template_code = models.TextField()
  137. mime_type = models.CharField(max_length=15, blank=True)
  138. file_extension = models.CharField(max_length=15, blank=True)
  139. class Meta:
  140. ordering = ['content_type', 'name']
  141. unique_together = [
  142. ['content_type', 'name']
  143. ]
  144. def __unicode__(self):
  145. return u'{}: {}'.format(self.content_type, self.name)
  146. def to_response(self, context_dict, filename):
  147. """
  148. Render the template to an HTTP response, delivered as a named file attachment
  149. """
  150. template = Template(self.template_code)
  151. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  152. response = HttpResponse(
  153. template.render(Context(context_dict)),
  154. content_type=mime_type
  155. )
  156. if self.file_extension:
  157. filename += '.{}'.format(self.file_extension)
  158. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  159. return response
  160. class TopologyMap(models.Model):
  161. name = models.CharField(max_length=50, unique=True)
  162. slug = models.SlugField(unique=True)
  163. site = models.ForeignKey(Site, related_name='topology_maps', blank=True, null=True)
  164. device_patterns = models.TextField(help_text="Identify devices to include in the diagram using regular expressions,"
  165. "one per line. Each line will result in a new tier of the drawing. "
  166. "Separate multiple regexes on a line using commas. Devices will be "
  167. "rendered in the order they are defined.")
  168. description = models.CharField(max_length=100, blank=True)
  169. class Meta:
  170. ordering = ['name']
  171. def __unicode__(self):
  172. return self.name
  173. @property
  174. def device_sets(self):
  175. if not self.device_patterns:
  176. return None
  177. return [line.strip() for line in self.device_patterns.split('\n')]
  178. class UserActionManager(models.Manager):
  179. # Actions affecting a single object
  180. def log_action(self, user, obj, action, message):
  181. self.model.objects.create(
  182. content_type=ContentType.objects.get_for_model(obj),
  183. object_id=obj.pk,
  184. user=user,
  185. action=action,
  186. message=message,
  187. )
  188. def log_create(self, user, obj, message=''):
  189. self.log_action(user, obj, ACTION_CREATE, message)
  190. def log_edit(self, user, obj, message=''):
  191. self.log_action(user, obj, ACTION_EDIT, message)
  192. def log_delete(self, user, obj, message=''):
  193. self.log_action(user, obj, ACTION_DELETE, message)
  194. # Actions affecting multiple objects
  195. def log_bulk_action(self, user, content_type, action, message):
  196. self.model.objects.create(
  197. content_type=content_type,
  198. user=user,
  199. action=action,
  200. message=message,
  201. )
  202. def log_import(self, user, content_type, message=''):
  203. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  204. def log_bulk_edit(self, user, content_type, message=''):
  205. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  206. def log_bulk_delete(self, user, content_type, message=''):
  207. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  208. class UserAction(models.Model):
  209. """
  210. A record of an action (add, edit, or delete) performed on an object by a User.
  211. """
  212. time = models.DateTimeField(auto_now_add=True, editable=False)
  213. user = models.ForeignKey(User, related_name='actions', on_delete=models.CASCADE)
  214. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  215. object_id = models.PositiveIntegerField(blank=True, null=True)
  216. action = models.PositiveSmallIntegerField(choices=ACTION_CHOICES)
  217. message = models.TextField(blank=True)
  218. objects = UserActionManager()
  219. class Meta:
  220. ordering = ['-time']
  221. def __unicode__(self):
  222. if self.message:
  223. return u'{} {}'.format(self.user, self.message)
  224. return u'{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  225. def icon(self):
  226. if self.action in [ACTION_CREATE, ACTION_IMPORT]:
  227. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  228. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  229. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  230. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  231. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  232. else:
  233. return ''