models.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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.contrib.postgres.fields import JSONField
  7. from django.core.validators import ValidationError
  8. from django.db import models
  9. from django.db.models import F, Q
  10. from django.http import HttpResponse
  11. from django.template import Template, Context
  12. from django.urls import reverse
  13. import graphviz
  14. from jinja2 import Environment
  15. from taggit.models import TagBase, GenericTaggedItemBase
  16. from dcim.constants import CONNECTION_STATUS_CONNECTED
  17. from utilities.fields import ColorField
  18. from utilities.utils import deepmerge, foreground_color
  19. from .constants import *
  20. from .querysets import ConfigContextQuerySet
  21. #
  22. # Webhooks
  23. #
  24. class Webhook(models.Model):
  25. """
  26. A Webhook defines a request that will be sent to a remote application when an object is created, updated, and/or
  27. delete in NetBox. The request will contain a representation of the object, which the remote application can act on.
  28. Each Webhook can be limited to firing only on certain actions or certain object types.
  29. """
  30. obj_type = models.ManyToManyField(
  31. to=ContentType,
  32. related_name='webhooks',
  33. verbose_name='Object types',
  34. limit_choices_to={'model__in': WEBHOOK_MODELS},
  35. help_text="The object(s) to which this Webhook applies."
  36. )
  37. name = models.CharField(
  38. max_length=150,
  39. unique=True
  40. )
  41. type_create = models.BooleanField(
  42. default=False,
  43. help_text="Call this webhook when a matching object is created."
  44. )
  45. type_update = models.BooleanField(
  46. default=False,
  47. help_text="Call this webhook when a matching object is updated."
  48. )
  49. type_delete = models.BooleanField(
  50. default=False,
  51. help_text="Call this webhook when a matching object is deleted."
  52. )
  53. payload_url = models.CharField(
  54. max_length=500,
  55. verbose_name='URL',
  56. help_text="A POST will be sent to this URL when the webhook is called."
  57. )
  58. http_content_type = models.PositiveSmallIntegerField(
  59. choices=WEBHOOK_CT_CHOICES,
  60. default=WEBHOOK_CT_JSON,
  61. verbose_name='HTTP content type'
  62. )
  63. secret = models.CharField(
  64. max_length=255,
  65. blank=True,
  66. help_text="When provided, the request will include a 'X-Hook-Signature' "
  67. "header containing a HMAC hex digest of the payload body using "
  68. "the secret as the key. The secret is not transmitted in "
  69. "the request."
  70. )
  71. enabled = models.BooleanField(
  72. default=True
  73. )
  74. ssl_verification = models.BooleanField(
  75. default=True,
  76. verbose_name='SSL verification',
  77. help_text="Enable SSL certificate verification. Disable with caution!"
  78. )
  79. class Meta:
  80. unique_together = ('payload_url', 'type_create', 'type_update', 'type_delete',)
  81. def __str__(self):
  82. return self.name
  83. def clean(self):
  84. """
  85. Validate model
  86. """
  87. if not self.type_create and not self.type_delete and not self.type_update:
  88. raise ValidationError(
  89. "You must select at least one type: create, update, and/or delete."
  90. )
  91. #
  92. # Custom fields
  93. #
  94. class CustomFieldModel(models.Model):
  95. class Meta:
  96. abstract = True
  97. def cf(self):
  98. """
  99. Name-based CustomFieldValue accessor for use in templates
  100. """
  101. if not hasattr(self, 'get_custom_fields'):
  102. return dict()
  103. return {field.name: value for field, value in self.get_custom_fields().items()}
  104. def get_custom_fields(self):
  105. """
  106. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  107. """
  108. # Find all custom fields applicable to this type of object
  109. content_type = ContentType.objects.get_for_model(self)
  110. fields = CustomField.objects.filter(obj_type=content_type)
  111. # If the object exists, populate its custom fields with values
  112. if hasattr(self, 'pk'):
  113. values = CustomFieldValue.objects.filter(obj_type=content_type, obj_id=self.pk).select_related('field')
  114. values_dict = {cfv.field_id: cfv.value for cfv in values}
  115. return OrderedDict([(field, values_dict.get(field.pk)) for field in fields])
  116. else:
  117. return OrderedDict([(field, None) for field in fields])
  118. class CustomField(models.Model):
  119. obj_type = models.ManyToManyField(
  120. to=ContentType,
  121. related_name='custom_fields',
  122. verbose_name='Object(s)',
  123. limit_choices_to={'model__in': CUSTOMFIELD_MODELS},
  124. help_text='The object(s) to which this field applies.'
  125. )
  126. type = models.PositiveSmallIntegerField(
  127. choices=CUSTOMFIELD_TYPE_CHOICES,
  128. default=CF_TYPE_TEXT
  129. )
  130. name = models.CharField(
  131. max_length=50,
  132. unique=True
  133. )
  134. label = models.CharField(
  135. max_length=50,
  136. blank=True,
  137. help_text='Name of the field as displayed to users (if not provided, '
  138. 'the field\'s name will be used)'
  139. )
  140. description = models.CharField(
  141. max_length=100,
  142. blank=True
  143. )
  144. required = models.BooleanField(
  145. default=False,
  146. help_text='If true, this field is required when creating new objects '
  147. 'or editing an existing object.'
  148. )
  149. filter_logic = models.PositiveSmallIntegerField(
  150. choices=CF_FILTER_CHOICES,
  151. default=CF_FILTER_LOOSE,
  152. help_text='Loose matches any instance of a given string; exact '
  153. 'matches the entire field.'
  154. )
  155. default = models.CharField(
  156. max_length=100,
  157. blank=True,
  158. help_text='Default value for the field. Use "true" or "false" for booleans.'
  159. )
  160. weight = models.PositiveSmallIntegerField(
  161. default=100,
  162. help_text='Fields with higher weights appear lower in a form.'
  163. )
  164. class Meta:
  165. ordering = ['weight', 'name']
  166. def __str__(self):
  167. return self.label or self.name.replace('_', ' ').capitalize()
  168. def serialize_value(self, value):
  169. """
  170. Serialize the given value to a string suitable for storage as a CustomFieldValue
  171. """
  172. if value is None:
  173. return ''
  174. if self.type == CF_TYPE_BOOLEAN:
  175. return str(int(bool(value)))
  176. if self.type == CF_TYPE_DATE:
  177. # Could be date/datetime object or string
  178. try:
  179. return value.strftime('%Y-%m-%d')
  180. except AttributeError:
  181. return value
  182. if self.type == CF_TYPE_SELECT:
  183. # Could be ModelChoiceField or TypedChoiceField
  184. return str(value.id) if hasattr(value, 'id') else str(value)
  185. return value
  186. def deserialize_value(self, serialized_value):
  187. """
  188. Convert a string into the object it represents depending on the type of field
  189. """
  190. if serialized_value == '':
  191. return None
  192. if self.type == CF_TYPE_INTEGER:
  193. return int(serialized_value)
  194. if self.type == CF_TYPE_BOOLEAN:
  195. return bool(int(serialized_value))
  196. if self.type == CF_TYPE_DATE:
  197. # Read date as YYYY-MM-DD
  198. return date(*[int(n) for n in serialized_value.split('-')])
  199. if self.type == CF_TYPE_SELECT:
  200. return self.choices.get(pk=int(serialized_value))
  201. return serialized_value
  202. class CustomFieldValue(models.Model):
  203. field = models.ForeignKey(
  204. to='extras.CustomField',
  205. on_delete=models.CASCADE,
  206. related_name='values'
  207. )
  208. obj_type = models.ForeignKey(
  209. to=ContentType,
  210. on_delete=models.PROTECT,
  211. related_name='+'
  212. )
  213. obj_id = models.PositiveIntegerField()
  214. obj = GenericForeignKey(
  215. ct_field='obj_type',
  216. fk_field='obj_id'
  217. )
  218. serialized_value = models.CharField(
  219. max_length=255
  220. )
  221. class Meta:
  222. ordering = ['obj_type', 'obj_id']
  223. unique_together = ['field', 'obj_type', 'obj_id']
  224. def __str__(self):
  225. return '{} {}'.format(self.obj, self.field)
  226. @property
  227. def value(self):
  228. return self.field.deserialize_value(self.serialized_value)
  229. @value.setter
  230. def value(self, value):
  231. self.serialized_value = self.field.serialize_value(value)
  232. def save(self, *args, **kwargs):
  233. # Delete this object if it no longer has a value to store
  234. if self.pk and self.value is None:
  235. self.delete()
  236. else:
  237. super().save(*args, **kwargs)
  238. class CustomFieldChoice(models.Model):
  239. field = models.ForeignKey(
  240. to='extras.CustomField',
  241. on_delete=models.CASCADE,
  242. related_name='choices',
  243. limit_choices_to={'type': CF_TYPE_SELECT}
  244. )
  245. value = models.CharField(
  246. max_length=100
  247. )
  248. weight = models.PositiveSmallIntegerField(
  249. default=100,
  250. help_text='Higher weights appear lower in the list'
  251. )
  252. class Meta:
  253. ordering = ['field', 'weight', 'value']
  254. unique_together = ['field', 'value']
  255. def __str__(self):
  256. return self.value
  257. def clean(self):
  258. if self.field.type != CF_TYPE_SELECT:
  259. raise ValidationError("Custom field choices can only be assigned to selection fields.")
  260. def delete(self, using=None, keep_parents=False):
  261. # When deleting a CustomFieldChoice, delete all CustomFieldValues which point to it
  262. pk = self.pk
  263. super().delete(using, keep_parents)
  264. CustomFieldValue.objects.filter(field__type=CF_TYPE_SELECT, serialized_value=str(pk)).delete()
  265. #
  266. # Custom links
  267. #
  268. def get_custom_link_models():
  269. # TODO: This should match on the app_label as well as the model name to avoid potential duplicate names
  270. return {
  271. 'model__in': [model.split('.')[1] for model in CUSTOM_LINK_MODELS],
  272. }
  273. class CustomLink(models.Model):
  274. """
  275. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  276. code to be rendered with an object as context.
  277. """
  278. content_type = models.ForeignKey(
  279. to=ContentType,
  280. on_delete=models.CASCADE,
  281. limit_choices_to=get_custom_link_models
  282. )
  283. name = models.CharField(
  284. max_length=100,
  285. unique=True
  286. )
  287. text = models.CharField(
  288. max_length=200,
  289. help_text="Jinja2 template code for link text"
  290. )
  291. url = models.CharField(
  292. max_length=200,
  293. verbose_name='URL',
  294. help_text="Jinja2 template code for link URL"
  295. )
  296. weight = models.PositiveSmallIntegerField(
  297. default=100
  298. )
  299. group_name = models.CharField(
  300. max_length=50,
  301. blank=True,
  302. help_text="Links with the same group will appear as a dropdown menu"
  303. )
  304. button_class = models.CharField(
  305. max_length=30,
  306. choices=BUTTON_CLASS_CHOICES,
  307. default=BUTTON_CLASS_DEFAULT,
  308. help_text="The class of the first link in a group will be used for the dropdown button"
  309. )
  310. new_window = models.BooleanField(
  311. help_text="Force link to open in a new window"
  312. )
  313. class Meta:
  314. ordering = ['group_name', 'weight', 'name']
  315. def __str__(self):
  316. return self.name
  317. #
  318. # Graphs
  319. #
  320. class Graph(models.Model):
  321. type = models.PositiveSmallIntegerField(
  322. choices=GRAPH_TYPE_CHOICES
  323. )
  324. weight = models.PositiveSmallIntegerField(
  325. default=1000
  326. )
  327. name = models.CharField(
  328. max_length=100,
  329. verbose_name='Name'
  330. )
  331. source = models.CharField(
  332. max_length=500,
  333. verbose_name='Source URL'
  334. )
  335. link = models.URLField(
  336. blank=True,
  337. verbose_name='Link URL'
  338. )
  339. class Meta:
  340. ordering = ['type', 'weight', 'name']
  341. def __str__(self):
  342. return self.name
  343. def embed_url(self, obj):
  344. template = Template(self.source)
  345. return template.render(Context({'obj': obj}))
  346. def embed_link(self, obj):
  347. if self.link is None:
  348. return ''
  349. template = Template(self.link)
  350. return template.render(Context({'obj': obj}))
  351. #
  352. # Export templates
  353. #
  354. class ExportTemplate(models.Model):
  355. content_type = models.ForeignKey(
  356. to=ContentType,
  357. on_delete=models.CASCADE,
  358. limit_choices_to={'model__in': EXPORTTEMPLATE_MODELS}
  359. )
  360. name = models.CharField(
  361. max_length=100
  362. )
  363. description = models.CharField(
  364. max_length=200,
  365. blank=True
  366. )
  367. template_language = models.PositiveSmallIntegerField(
  368. choices=TEMPLATE_LANGUAGE_CHOICES,
  369. default=TEMPLATE_LANGUAGE_JINJA2
  370. )
  371. template_code = models.TextField()
  372. mime_type = models.CharField(
  373. max_length=50,
  374. blank=True
  375. )
  376. file_extension = models.CharField(
  377. max_length=15,
  378. blank=True
  379. )
  380. class Meta:
  381. ordering = ['content_type', 'name']
  382. unique_together = [
  383. ['content_type', 'name']
  384. ]
  385. def __str__(self):
  386. return '{}: {}'.format(self.content_type, self.name)
  387. def render(self, queryset):
  388. """
  389. Render the contents of the template.
  390. """
  391. context = {
  392. 'queryset': queryset
  393. }
  394. if self.template_language == TEMPLATE_LANGUAGE_DJANGO:
  395. template = Template(self.template_code)
  396. output = template.render(Context(context))
  397. elif self.template_language == TEMPLATE_LANGUAGE_JINJA2:
  398. template = Environment().from_string(source=self.template_code)
  399. output = template.render(**context)
  400. else:
  401. return None
  402. # Replace CRLF-style line terminators
  403. output = output.replace('\r\n', '\n')
  404. return output
  405. def render_to_response(self, queryset):
  406. """
  407. Render the template to an HTTP response, delivered as a named file attachment
  408. """
  409. output = self.render(queryset)
  410. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  411. # Build the response
  412. response = HttpResponse(output, content_type=mime_type)
  413. filename = 'netbox_{}{}'.format(
  414. queryset.model._meta.verbose_name_plural,
  415. '.{}'.format(self.file_extension) if self.file_extension else ''
  416. )
  417. response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
  418. return response
  419. #
  420. # Topology maps
  421. #
  422. class TopologyMap(models.Model):
  423. name = models.CharField(
  424. max_length=50,
  425. unique=True
  426. )
  427. slug = models.SlugField(
  428. unique=True
  429. )
  430. type = models.PositiveSmallIntegerField(
  431. choices=TOPOLOGYMAP_TYPE_CHOICES,
  432. default=TOPOLOGYMAP_TYPE_NETWORK
  433. )
  434. site = models.ForeignKey(
  435. to='dcim.Site',
  436. on_delete=models.CASCADE,
  437. related_name='topology_maps',
  438. blank=True,
  439. null=True
  440. )
  441. device_patterns = models.TextField(
  442. help_text='Identify devices to include in the diagram using regular '
  443. 'expressions, one per line. Each line will result in a new '
  444. 'tier of the drawing. Separate multiple regexes within a '
  445. 'line using semicolons. Devices will be rendered in the '
  446. 'order they are defined.'
  447. )
  448. description = models.CharField(
  449. max_length=100,
  450. blank=True
  451. )
  452. class Meta:
  453. ordering = ['name']
  454. def __str__(self):
  455. return self.name
  456. @property
  457. def device_sets(self):
  458. if not self.device_patterns:
  459. return None
  460. return [line.strip() for line in self.device_patterns.split('\n')]
  461. def render(self, img_format='png'):
  462. from dcim.models import Device
  463. # Construct the graph
  464. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  465. G = graphviz.Graph
  466. else:
  467. G = graphviz.Digraph
  468. self.graph = G()
  469. self.graph.graph_attr['ranksep'] = '1'
  470. seen = set()
  471. for i, device_set in enumerate(self.device_sets):
  472. subgraph = G(name='sg{}'.format(i))
  473. subgraph.graph_attr['rank'] = 'same'
  474. subgraph.graph_attr['directed'] = 'true'
  475. # Add a pseudonode for each device_set to enforce hierarchical layout
  476. subgraph.node('set{}'.format(i), label='', shape='none', width='0')
  477. if i:
  478. self.graph.edge('set{}'.format(i - 1), 'set{}'.format(i), style='invis')
  479. # Add each device to the graph
  480. devices = []
  481. for query in device_set.strip(';').split(';'): # Split regexes on semicolons
  482. devices += Device.objects.filter(name__regex=query).select_related('device_role')
  483. # Remove duplicate devices
  484. devices = [d for d in devices if d.id not in seen]
  485. seen.update([d.id for d in devices])
  486. for d in devices:
  487. bg_color = '#{}'.format(d.device_role.color)
  488. fg_color = '#{}'.format(foreground_color(d.device_role.color))
  489. subgraph.node(d.name, style='filled', fillcolor=bg_color, fontcolor=fg_color, fontname='sans')
  490. # Add an invisible connection to each successive device in a set to enforce horizontal order
  491. for j in range(0, len(devices) - 1):
  492. subgraph.edge(devices[j].name, devices[j + 1].name, style='invis')
  493. self.graph.subgraph(subgraph)
  494. # Compile list of all devices
  495. device_superset = Q()
  496. for device_set in self.device_sets:
  497. for query in device_set.split(';'): # Split regexes on semicolons
  498. device_superset = device_superset | Q(name__regex=query)
  499. devices = Device.objects.filter(*(device_superset,))
  500. # Draw edges depending on graph type
  501. if self.type == TOPOLOGYMAP_TYPE_NETWORK:
  502. self.add_network_connections(devices)
  503. elif self.type == TOPOLOGYMAP_TYPE_CONSOLE:
  504. self.add_console_connections(devices)
  505. elif self.type == TOPOLOGYMAP_TYPE_POWER:
  506. self.add_power_connections(devices)
  507. return self.graph.pipe(format=img_format)
  508. def add_network_connections(self, devices):
  509. from circuits.models import CircuitTermination
  510. from dcim.models import Interface
  511. # Add all interface connections to the graph
  512. connected_interfaces = Interface.objects.select_related(
  513. '_connected_interface__device'
  514. ).filter(
  515. Q(device__in=devices) | Q(_connected_interface__device__in=devices),
  516. _connected_interface__isnull=False,
  517. pk__lt=F('_connected_interface')
  518. )
  519. for interface in connected_interfaces:
  520. style = 'solid' if interface.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  521. self.graph.edge(interface.device.name, interface.connected_endpoint.device.name, style=style)
  522. # Add all circuits to the graph
  523. for termination in CircuitTermination.objects.filter(term_side='A', connected_endpoint__device__in=devices):
  524. peer_termination = termination.get_peer_termination()
  525. if (peer_termination is not None and peer_termination.interface is not None and
  526. peer_termination.interface.device in devices):
  527. self.graph.edge(termination.interface.device.name, peer_termination.interface.device.name, color='blue')
  528. def add_console_connections(self, devices):
  529. from dcim.models import ConsolePort
  530. # Add all console connections to the graph
  531. for cp in ConsolePort.objects.filter(device__in=devices, connected_endpoint__device__in=devices):
  532. style = 'solid' if cp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  533. self.graph.edge(cp.connected_endpoint.device.name, cp.device.name, style=style)
  534. def add_power_connections(self, devices):
  535. from dcim.models import PowerPort
  536. # Add all power connections to the graph
  537. for pp in PowerPort.objects.filter(device__in=devices, _connected_poweroutlet__device__in=devices):
  538. style = 'solid' if pp.connection_status == CONNECTION_STATUS_CONNECTED else 'dashed'
  539. self.graph.edge(pp.connected_endpoint.device.name, pp.device.name, style=style)
  540. #
  541. # Image attachments
  542. #
  543. def image_upload(instance, filename):
  544. path = 'image-attachments/'
  545. # Rename the file to the provided name, if any. Attempt to preserve the file extension.
  546. extension = filename.rsplit('.')[-1].lower()
  547. if instance.name and extension in ['bmp', 'gif', 'jpeg', 'jpg', 'png']:
  548. filename = '.'.join([instance.name, extension])
  549. elif instance.name:
  550. filename = instance.name
  551. return '{}{}_{}_{}'.format(path, instance.content_type.name, instance.object_id, filename)
  552. class ImageAttachment(models.Model):
  553. """
  554. An uploaded image which is associated with an object.
  555. """
  556. content_type = models.ForeignKey(
  557. to=ContentType,
  558. on_delete=models.CASCADE
  559. )
  560. object_id = models.PositiveIntegerField()
  561. parent = GenericForeignKey(
  562. ct_field='content_type',
  563. fk_field='object_id'
  564. )
  565. image = models.ImageField(
  566. upload_to=image_upload,
  567. height_field='image_height',
  568. width_field='image_width'
  569. )
  570. image_height = models.PositiveSmallIntegerField()
  571. image_width = models.PositiveSmallIntegerField()
  572. name = models.CharField(
  573. max_length=50,
  574. blank=True
  575. )
  576. created = models.DateTimeField(
  577. auto_now_add=True
  578. )
  579. class Meta:
  580. ordering = ['name']
  581. def __str__(self):
  582. if self.name:
  583. return self.name
  584. filename = self.image.name.rsplit('/', 1)[-1]
  585. return filename.split('_', 2)[2]
  586. def delete(self, *args, **kwargs):
  587. _name = self.image.name
  588. super().delete(*args, **kwargs)
  589. # Delete file from disk
  590. self.image.delete(save=False)
  591. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  592. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  593. self.image.name = _name
  594. @property
  595. def size(self):
  596. """
  597. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible.
  598. """
  599. try:
  600. return self.image.size
  601. except OSError:
  602. return None
  603. #
  604. # Config contexts
  605. #
  606. class ConfigContext(models.Model):
  607. """
  608. A ConfigContext represents a set of arbitrary data available to any Device or VirtualMachine matching its assigned
  609. qualifiers (region, site, etc.). For example, the data stored in a ConfigContext assigned to site A and tenant B
  610. will be available to a Device in site A assigned to tenant B. Data is stored in JSON format.
  611. """
  612. name = models.CharField(
  613. max_length=100,
  614. unique=True
  615. )
  616. weight = models.PositiveSmallIntegerField(
  617. default=1000
  618. )
  619. description = models.CharField(
  620. max_length=100,
  621. blank=True
  622. )
  623. is_active = models.BooleanField(
  624. default=True,
  625. )
  626. regions = models.ManyToManyField(
  627. to='dcim.Region',
  628. related_name='+',
  629. blank=True
  630. )
  631. sites = models.ManyToManyField(
  632. to='dcim.Site',
  633. related_name='+',
  634. blank=True
  635. )
  636. roles = models.ManyToManyField(
  637. to='dcim.DeviceRole',
  638. related_name='+',
  639. blank=True
  640. )
  641. platforms = models.ManyToManyField(
  642. to='dcim.Platform',
  643. related_name='+',
  644. blank=True
  645. )
  646. tenant_groups = models.ManyToManyField(
  647. to='tenancy.TenantGroup',
  648. related_name='+',
  649. blank=True
  650. )
  651. tenants = models.ManyToManyField(
  652. to='tenancy.Tenant',
  653. related_name='+',
  654. blank=True
  655. )
  656. data = JSONField()
  657. objects = ConfigContextQuerySet.as_manager()
  658. class Meta:
  659. ordering = ['weight', 'name']
  660. def __str__(self):
  661. return self.name
  662. def get_absolute_url(self):
  663. return reverse('extras:configcontext', kwargs={'pk': self.pk})
  664. def clean(self):
  665. # Verify that JSON data is provided as an object
  666. if type(self.data) is not dict:
  667. raise ValidationError(
  668. {'data': 'JSON data must be in object form. Example: {"foo": 123}'}
  669. )
  670. class ConfigContextModel(models.Model):
  671. local_context_data = JSONField(
  672. blank=True,
  673. null=True,
  674. )
  675. class Meta:
  676. abstract = True
  677. def get_config_context(self):
  678. """
  679. Return the rendered configuration context for a device or VM.
  680. """
  681. # Compile all config data, overwriting lower-weight values with higher-weight values where a collision occurs
  682. data = OrderedDict()
  683. for context in ConfigContext.objects.get_for_object(self):
  684. data = deepmerge(data, context.data)
  685. # If the object has local config context data defined, merge it last
  686. if self.local_context_data:
  687. data = deepmerge(data, self.local_context_data)
  688. return data
  689. #
  690. # Report results
  691. #
  692. class ReportResult(models.Model):
  693. """
  694. This model stores the results from running a user-defined report.
  695. """
  696. report = models.CharField(
  697. max_length=255,
  698. unique=True
  699. )
  700. created = models.DateTimeField(
  701. auto_now_add=True
  702. )
  703. user = models.ForeignKey(
  704. to=User,
  705. on_delete=models.SET_NULL,
  706. related_name='+',
  707. blank=True,
  708. null=True
  709. )
  710. failed = models.BooleanField()
  711. data = JSONField()
  712. class Meta:
  713. ordering = ['report']
  714. #
  715. # Change logging
  716. #
  717. class ObjectChange(models.Model):
  718. """
  719. Record a change to an object and the user account associated with that change. A change record may optionally
  720. indicate an object related to the one being changed. For example, a change to an interface may also indicate the
  721. parent device. This will ensure changes made to component models appear in the parent model's changelog.
  722. """
  723. time = models.DateTimeField(
  724. auto_now_add=True,
  725. editable=False
  726. )
  727. user = models.ForeignKey(
  728. to=User,
  729. on_delete=models.SET_NULL,
  730. related_name='changes',
  731. blank=True,
  732. null=True
  733. )
  734. user_name = models.CharField(
  735. max_length=150,
  736. editable=False
  737. )
  738. request_id = models.UUIDField(
  739. editable=False
  740. )
  741. action = models.PositiveSmallIntegerField(
  742. choices=OBJECTCHANGE_ACTION_CHOICES
  743. )
  744. changed_object_type = models.ForeignKey(
  745. to=ContentType,
  746. on_delete=models.PROTECT,
  747. related_name='+'
  748. )
  749. changed_object_id = models.PositiveIntegerField()
  750. changed_object = GenericForeignKey(
  751. ct_field='changed_object_type',
  752. fk_field='changed_object_id'
  753. )
  754. related_object_type = models.ForeignKey(
  755. to=ContentType,
  756. on_delete=models.PROTECT,
  757. related_name='+',
  758. blank=True,
  759. null=True
  760. )
  761. related_object_id = models.PositiveIntegerField(
  762. blank=True,
  763. null=True
  764. )
  765. related_object = GenericForeignKey(
  766. ct_field='related_object_type',
  767. fk_field='related_object_id'
  768. )
  769. object_repr = models.CharField(
  770. max_length=200,
  771. editable=False
  772. )
  773. object_data = JSONField(
  774. editable=False
  775. )
  776. csv_headers = [
  777. 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id',
  778. 'related_object_type', 'related_object_id', 'object_repr', 'object_data',
  779. ]
  780. class Meta:
  781. ordering = ['-time']
  782. def __str__(self):
  783. return '{} {} {} by {}'.format(
  784. self.changed_object_type,
  785. self.object_repr,
  786. self.get_action_display().lower(),
  787. self.user_name
  788. )
  789. def save(self, *args, **kwargs):
  790. # Record the user's name and the object's representation as static strings
  791. self.user_name = self.user.username
  792. self.object_repr = str(self.changed_object)
  793. return super().save(*args, **kwargs)
  794. def get_absolute_url(self):
  795. return reverse('extras:objectchange', args=[self.pk])
  796. def to_csv(self):
  797. return (
  798. self.time,
  799. self.user,
  800. self.user_name,
  801. self.request_id,
  802. self.get_action_display(),
  803. self.changed_object_type,
  804. self.changed_object_id,
  805. self.related_object_type,
  806. self.related_object_id,
  807. self.object_repr,
  808. self.object_data,
  809. )
  810. #
  811. # Tags
  812. #
  813. # TODO: figure out a way around this circular import for ObjectChange
  814. from utilities.models import ChangeLoggedModel # noqa: E402
  815. class Tag(TagBase, ChangeLoggedModel):
  816. color = ColorField(
  817. default='9e9e9e'
  818. )
  819. comments = models.TextField(
  820. blank=True,
  821. default=''
  822. )
  823. def get_absolute_url(self):
  824. return reverse('extras:tag', args=[self.slug])
  825. class TaggedItem(GenericTaggedItemBase):
  826. tag = models.ForeignKey(
  827. to=Tag,
  828. related_name="%(app_label)s_%(class)s_items",
  829. on_delete=models.CASCADE
  830. )
  831. class Meta:
  832. index_together = (
  833. ("content_type", "object_id")
  834. )