models.py 30 KB

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