models.py 21 KB

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