models.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. from __future__ import unicode_literals
  2. from collections import OrderedDict
  3. from datetime import date
  4. import graphviz
  5. from django.contrib.auth.models import User
  6. from django.contrib.contenttypes.fields import GenericForeignKey
  7. from django.contrib.contenttypes.models import ContentType
  8. from django.contrib.postgres.fields import JSONField
  9. from django.core.validators import ValidationError
  10. from django.db import models
  11. from django.db.models import Q
  12. from django.http import HttpResponse
  13. from django.template import Template, Context
  14. from django.utils.encoding import python_2_unicode_compatible
  15. from django.utils.safestring import mark_safe
  16. from dcim.constants import CONNECTION_STATUS_CONNECTED
  17. from utilities.utils import foreground_color
  18. from .constants import *
  19. #
  20. # Custom fields
  21. #
  22. class CustomFieldModel(object):
  23. def cf(self):
  24. """
  25. Name-based CustomFieldValue accessor for use in templates
  26. """
  27. if not hasattr(self, 'get_custom_fields'):
  28. return dict()
  29. return {field.name: value for field, value in self.get_custom_fields().items()}
  30. def get_custom_fields(self):
  31. """
  32. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  33. """
  34. # Find all custom fields applicable to this type of object
  35. content_type = ContentType.objects.get_for_model(self)
  36. fields = CustomField.objects.filter(obj_type=content_type)
  37. # If the object exists, populate its custom fields with values
  38. if hasattr(self, 'pk'):
  39. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  40. values_dict = {cfv.field_id: cfv.value for cfv in values}
  41. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  42. else:
  43. return OrderedDict([(field, None) for field in fields])
  44. @python_2_unicode_compatible
  45. class CustomField(models.Model):
  46. obj_type = models.ManyToManyField(
  47. to=ContentType,
  48. related_name='custom_fields',
  49. verbose_name='Object(s)',
  50. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  51. help_text='The object(s) to which this field applies.'
  52. )
  53. type = models.PositiveSmallIntegerField(
  54. choices=CUSTOMFIELD_TYPE_CHOICES,
  55. default=CF_TYPE_TEXT
  56. )
  57. name = models.CharField(
  58. max_length=50,
  59. unique=True
  60. )
  61. label = models.CharField(
  62. max_length=50,
  63. blank=True,
  64. help_text='Name of the field as displayed to users (if not provided, the field\'s name will be used)'
  65. )
  66. description = models.CharField(
  67. max_length=100,
  68. blank=True
  69. )
  70. required = models.BooleanField(
  71. default=False,
  72. help_text='If true, this field is required when creating new objects or editing an existing object.'
  73. )
  74. filter_logic = models.PositiveSmallIntegerField(
  75. choices=CF_FILTER_CHOICES,
  76. default=CF_FILTER_LOOSE,
  77. help_text="Loose matches any instance of a given string; exact matches the entire field."
  78. )
  79. default = models.CharField(
  80. max_length=100,
  81. blank=True,
  82. help_text='Default value for the field. Use "true" or "false" for booleans. N/A for selection fields.'
  83. )
  84. weight = models.PositiveSmallIntegerField(
  85. default=100,
  86. help_text='Fields with higher weights appear lower in a form.'
  87. )
  88. class Meta:
  89. ordering = ['weight', 'name']
  90. def __str__(self):
  91. return self.label or self.name.replace('_', ' ').capitalize()
  92. def serialize_value(self, value):
  93. """
  94. Serialize the given value to a string suitable for storage as a CustomFieldValue
  95. """
  96. if value is None:
  97. return ''
  98. if self.type == CF_TYPE_BOOLEAN:
  99. return str(int(bool(value)))
  100. if self.type == CF_TYPE_DATE:
  101. # Could be date/datetime object or string
  102. try:
  103. return value.strftime('%Y-%m-%d')
  104. except AttributeError:
  105. return value
  106. if self.type == CF_TYPE_SELECT:
  107. # Could be ModelChoiceField or TypedChoiceField
  108. return str(value.id) if hasattr(value, 'id') else str(value)
  109. return value
  110. def deserialize_value(self, serialized_value):
  111. """
  112. Convert a string into the object it represents depending on the type of field
  113. """
  114. if serialized_value is '':
  115. return None
  116. if self.type == CF_TYPE_INTEGER:
  117. return int(serialized_value)
  118. if self.type == CF_TYPE_BOOLEAN:
  119. return bool(int(serialized_value))
  120. if self.type == CF_TYPE_DATE:
  121. # Read date as YYYY-MM-DD
  122. return date(*[int(n) for n in serialized_value.split('-')])
  123. if self.type == CF_TYPE_SELECT:
  124. return self.choices.get(pk=int(serialized_value))
  125. return serialized_value
  126. @python_2_unicode_compatible
  127. class CustomFieldValue(models.Model):
  128. field = models.ForeignKey('CustomField', related_name='values', on_delete=models.CASCADE)
  129. obj_type = models.ForeignKey(ContentType, related_name='+', on_delete=models.PROTECT)
  130. obj_id = models.PositiveIntegerField()
  131. obj = GenericForeignKey('obj_type', 'obj_id')
  132. serialized_value = models.CharField(max_length=255)
  133. class Meta:
  134. ordering = ['obj_type', 'obj_id']
  135. unique_together = ['field', 'obj_type', 'obj_id']
  136. def __str__(self):
  137. return '{} {}'.format(self.obj, self.field)
  138. @property
  139. def value(self):
  140. return self.field.deserialize_value(self.serialized_value)
  141. @value.setter
  142. def value(self, value):
  143. self.serialized_value = self.field.serialize_value(value)
  144. def save(self, *args, **kwargs):
  145. # Delete this object if it no longer has a value to store
  146. if self.pk and self.value is None:
  147. self.delete()
  148. else:
  149. super(CustomFieldValue, self).save(*args, **kwargs)
  150. @python_2_unicode_compatible
  151. class CustomFieldChoice(models.Model):
  152. field = models.ForeignKey('CustomField', related_name='choices', limit_choices_to={'type': CF_TYPE_SELECT},
  153. on_delete=models.CASCADE)
  154. value = models.CharField(max_length=100)
  155. weight = models.PositiveSmallIntegerField(default=100, help_text="Higher weights appear lower in the list")
  156. class Meta:
  157. ordering = ['field', 'weight', 'value']
  158. unique_together = ['field', 'value']
  159. def __str__(self):
  160. return self.value
  161. def clean(self):
  162. if self.field.type != CF_TYPE_SELECT:
  163. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  164. def delete(self, using=None, keep_parents=False):
  165. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  166. pk = self.pk
  167. super(CustomFieldChoice, self).delete(using, keep_parents)
  168. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  169. #
  170. # Graphs
  171. #
  172. @python_2_unicode_compatible
  173. class Graph(models.Model):
  174. type = models.PositiveSmallIntegerField(choices=GRAPH_TYPE_CHOICES)
  175. weight = models.PositiveSmallIntegerField(default=1000)
  176. name = models.CharField(max_length=100, verbose_name='Name')
  177. source = models.CharField(max_length=500, verbose_name='Source URL')
  178. link = models.URLField(verbose_name='Link URL', blank=True)
  179. class Meta:
  180. ordering = ['type', 'weight', 'name']
  181. def __str__(self):
  182. return self.name
  183. def embed_url(self, obj):
  184. template = Template(self.source)
  185. return template.render(Context({'obj': obj}))
  186. def embed_link(self, obj):
  187. if self.link is None:
  188. return ''
  189. template = Template(self.link)
  190. return template.render(Context({'obj': obj}))
  191. #
  192. # Export templates
  193. #
  194. @python_2_unicode_compatible
  195. class ExportTemplate(models.Model):
  196. content_type = models.ForeignKey(
  197. ContentType, limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS}, on_delete=models.CASCADE
  198. )
  199. name = models.CharField(max_length=100)
  200. description = models.CharField(max_length=200, blank=True)
  201. template_code = models.TextField()
  202. mime_type = models.CharField(max_length=15, blank=True)
  203. file_extension = models.CharField(max_length=15, blank=True)
  204. class Meta:
  205. ordering = ['content_type', 'name']
  206. unique_together = [
  207. ['content_type', 'name']
  208. ]
  209. def __str__(self):
  210. return '{}: {}'.format(self.content_type, self.name)
  211. def render_to_response(self, queryset):
  212. """
  213. Render the template to an HTTP response, delivered as a named file attachment
  214. """
  215. template = Template(self.template_code)
  216. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  217. output = template.render(Context({'queryset': queryset}))
  218. # Replace CRLF-style line terminators
  219. output = output.replace('\r\n', '\n')
  220. # Build the response
  221. response = HttpResponse(output, content_type=mime_type)
  222. filename = 'netbox_{}{}'.format(
  223. queryset.model._meta.verbose_name_plural,
  224. '.{}'.format(self.file_extension) if self.file_extension else ''
  225. )
  226. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  227. return response
  228. #
  229. # Topology maps
  230. #
  231. @python_2_unicode_compatible
  232. class TopologyMap(models.Model):
  233. name = models.CharField(max_length=50, unique=True)
  234. slug = models.SlugField(unique=True)
  235. type = models.PositiveSmallIntegerField(
  236. choices=TOPOLOGYMAP_TYPE_CHOICES,
  237. default=TOPOLOGYMAP_TYPE_NETWORK
  238. )
  239. site = models.ForeignKey(
  240. to='dcim.Site',
  241. related_name='topology_maps',
  242. blank=True,
  243. null=True,
  244. on_delete=models.CASCADE
  245. )
  246. device_patterns = models.TextField(
  247. help_text="Identify devices to include in the diagram using regular expressions, one per line. Each line will "
  248. "result in a new tier of the drawing. Separate multiple regexes within a line using semicolons. "
  249. "Devices will be rendered in the order they are defined."
  250. )
  251. description = models.CharField(max_length=100, blank=True)
  252. class Meta:
  253. ordering = ['name']
  254. def __str__(self):
  255. return self.name
  256. @property
  257. def device_sets(self):
  258. if not self.device_patterns:
  259. return None
  260. return [line.strip() for line in self.device_patterns.split('\n')]
  261. def render(self, img_format='png'):
  262. from dcim.models import Device
  263. # Construct the graph
  264. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  265. G = graphviz.Graph
  266. else:
  267. G = graphviz.Digraph
  268. self.graph = G()
  269. self.graph.graph_attr['ranksep'] = '1'
  270. seen = set()
  271. for i, device_set in enumerate(self.device_sets):
  272. subgraph = G(name='sg{}'.format(i))
  273. subgraph.graph_attr['rank'] = 'same'
  274. subgraph.graph_attr['directed'] = 'true'
  275. # Add a pseudonode for each device_set to enforce hierarchical layout
  276. subgraph.node('set{}'.format(i), label='', shape='none', width='0')
  277. if i:
  278. self.graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
  279. # Add each device to the graph
  280. devices = []
  281. for query in device_set.strip(';').split(';'): # Split regexes on semicolons
  282. devices += Device.objects.filter(name__regex=query).select_related('device_role')
  283. # Remove duplicate devices
  284. devices = [d for d in devices if d.id not in seen]
  285. seen.update([d.id for d in devices])
  286. for d in devices:
  287. bg_color = '#{}'.format(d.device_role.color)
  288. fg_color = '#{}'.format(foreground_color(d.device_role.color))
  289. subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans')
  290. # Add an invisible connection to each successive device in a set to enforce horizontal order
  291. for j in range(0, len(devices) - 1):
  292. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  293. self.graph.subgraph(subgraph)
  294. # Compile list of all devices
  295. device_superset = Q()
  296. for device_set in self.device_sets:
  297. for query in device_set.split(';'): # Split regexes on semicolons
  298. device_superset = device_superset | Q(name__regex=query)
  299. devices = Device.objects.filter(*(device_superset,))
  300. # Draw edges depending on graph type
  301. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  302. self.add_network_connections(devices)
  303. elif self.type == TOPOLOGYMAP_TYPE_CONSOLE:
  304. self.add_console_connections(devices)
  305. elif self.type == TOPOLOGYMAP_TYPE_POWER:
  306. self.add_power_connections(devices)
  307. return self.graph.pipe(format=img_format)
  308. def add_network_connections(self, devices):
  309. from circuits.models import CircuitTermination
  310. from dcim.models import InterfaceConnection
  311. # Add all interface connections to the graph
  312. connections = InterfaceConnection.objects.filter(
  313. interface_a__device__in=devices, interface_b__device__in=devices
  314. )
  315. for c in connections:
  316. style = 'solid' if c.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  317. self.graph.edge(c.interface_a.device.name, c.interface_b.device.name, style=style)
  318. # Add all circuits to the graph
  319. for termination in CircuitTermination.objects.filter(term_side='A', interface__device__in=devices):
  320. peer_termination = termination.get_peer_termination()
  321. if (peer_termination is not None and peer_termination.interface is not None and
  322. peer_termination.interface.device in devices):
  323. self.graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  324. def add_console_connections(self, devices):
  325. from dcim.models import ConsolePort
  326. # Add all console connections to the graph
  327. console_ports = ConsolePort.objects.filter(device__in=devices, cs_port__device__in=devices)
  328. for cp in console_ports:
  329. style = 'solid' if cp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  330. self.graph.edge(cp.cs_port.device.name, cp.device.name, style=style)
  331. def add_power_connections(self, devices):
  332. from dcim.models import PowerPort
  333. # Add all power connections to the graph
  334. power_ports = PowerPort.objects.filter(device__in=devices, power_outlet__device__in=devices)
  335. for pp in power_ports:
  336. style = 'solid' if pp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  337. self.graph.edge(pp.power_outlet.device.name, pp.device.name, style=style)
  338. #
  339. # Image attachments
  340. #
  341. def image_upload(instance, filename):
  342. path = 'image-attachments/'
  343. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  344. extension = filename.rsplit('.')[-1].lower()
  345. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  346. filename = '.'.join([instance.name, extension])
  347. elif instance.name:
  348. filename = instance.name
  349. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  350. @python_2_unicode_compatible
  351. class ImageAttachment(models.Model):
  352. """
  353. An uploaded image which is associated with an object.
  354. """
  355. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  356. object_id = models.PositiveIntegerField()
  357. parent = GenericForeignKey('content_type', 'object_id')
  358. image = models.ImageField(upload_to=image_upload, height_field='image_height', width_field='image_width')
  359. image_height = models.PositiveSmallIntegerField()
  360. image_width = models.PositiveSmallIntegerField()
  361. name = models.CharField(max_length=50, blank=True)
  362. created = models.DateTimeField(auto_now_add=True)
  363. class Meta:
  364. ordering = ['name']
  365. def __str__(self):
  366. if self.name:
  367. return self.name
  368. filename = self.image.name.rsplit('/', 1)[-1]
  369. return filename.split('_', 2)[2]
  370. def delete(self, *args, **kwargs):
  371. _name = self.image.name
  372. super(ImageAttachment, self).delete(*args, **kwargs)
  373. # Delete file from disk
  374. self.image.delete(save=False)
  375. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  376. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  377. self.image.name = _name
  378. @property
  379. def size(self):
  380. """
  381. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  382. """
  383. try:
  384. return self.image.size
  385. except OSError:
  386. return None
  387. #
  388. # Report results
  389. #
  390. class ReportResult(models.Model):
  391. """
  392. This model stores the results from running a user-defined report.
  393. """
  394. report = models.CharField(max_length=255, unique=True)
  395. created = models.DateTimeField(auto_now_add=True)
  396. user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='+', blank=True, null=True)
  397. failed = models.BooleanField()
  398. data = JSONField()
  399. class Meta:
  400. ordering = ['report']
  401. #
  402. # User actions
  403. #
  404. class UserActionManager(models.Manager):
  405. # Actions affecting a single object
  406. def log_action(self, user, obj, action, message):
  407. self.model.objects.create(
  408. content_type=ContentType.objects.get_for_model(obj),
  409. object_id=obj.pk,
  410. user=user,
  411. action=action,
  412. message=message,
  413. )
  414. def log_create(self, user, obj, message=''):
  415. self.log_action(user, obj, ACTION_CREATE, message)
  416. def log_edit(self, user, obj, message=''):
  417. self.log_action(user, obj, ACTION_EDIT, message)
  418. def log_delete(self, user, obj, message=''):
  419. self.log_action(user, obj, ACTION_DELETE, message)
  420. # Actions affecting multiple objects
  421. def log_bulk_action(self, user, content_type, action, message):
  422. self.model.objects.create(
  423. content_type=content_type,
  424. user=user,
  425. action=action,
  426. message=message,
  427. )
  428. def log_import(self, user, content_type, message=''):
  429. self.log_bulk_action(user, content_type, ACTION_IMPORT, message)
  430. def log_bulk_create(self, user, content_type, message=''):
  431. self.log_bulk_action(user, content_type, ACTION_BULK_CREATE, message)
  432. def log_bulk_edit(self, user, content_type, message=''):
  433. self.log_bulk_action(user, content_type, ACTION_BULK_EDIT, message)
  434. def log_bulk_delete(self, user, content_type, message=''):
  435. self.log_bulk_action(user, content_type, ACTION_BULK_DELETE, message)
  436. @python_2_unicode_compatible
  437. class UserAction(models.Model):
  438. """
  439. A record of an action (add, edit, or delete) performed on an object by a User.
  440. """
  441. time = models.DateTimeField(auto_now_add=True, editable=False)
  442. user = models.ForeignKey(User, related_name='actions', on_delete=models.CASCADE)
  443. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  444. object_id = models.PositiveIntegerField(blank=True, null=True)
  445. action = models.PositiveSmallIntegerField(choices=ACTION_CHOICES)
  446. message = models.TextField(blank=True)
  447. objects = UserActionManager()
  448. class Meta:
  449. ordering = ['-time']
  450. def __str__(self):
  451. if self.message:
  452. return '{} {}'.format(self.user, self.message)
  453. return '{} {} {}'.format(self.user, self.get_action_display(), self.content_type)
  454. def icon(self):
  455. if self.action in [ACTION_CREATE, ACTION_BULK_CREATE, ACTION_IMPORT]:
  456. return mark_safe('<i class="glyphicon glyphicon-plus text-success"></i>')
  457. elif self.action in [ACTION_EDIT, ACTION_BULK_EDIT]:
  458. return mark_safe('<i class="glyphicon glyphicon-pencil text-warning"></i>')
  459. elif self.action in [ACTION_DELETE, ACTION_BULK_DELETE]:
  460. return mark_safe('<i class="glyphicon glyphicon-remove text-danger"></i>')
  461. else:
  462. return ''