models.py 30 KB

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