models.py 32 KB

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