models.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. import json
  2. import uuid
  3. import django_rq
  4. from django.conf import settings
  5. from django.contrib import admin
  6. from django.contrib.auth.models import User
  7. from django.contrib.contenttypes.fields import GenericForeignKey
  8. from django.contrib.contenttypes.models import ContentType
  9. from django.core.cache import cache
  10. from django.core.validators import MinValueValidator, ValidationError
  11. from django.db import models
  12. from django.http import HttpResponse, QueryDict
  13. from django.urls import reverse
  14. from django.urls.exceptions import NoReverseMatch
  15. from django.utils import timezone
  16. from django.utils.formats import date_format
  17. from django.utils.translation import gettext as _
  18. from rest_framework.utils.encoders import JSONEncoder
  19. from extras.choices import *
  20. from extras.conditions import ConditionSet
  21. from extras.constants import *
  22. from extras.utils import FeatureQuery, image_upload
  23. from netbox.config import get_config
  24. from netbox.constants import RQ_QUEUE_DEFAULT
  25. from netbox.models import ChangeLoggedModel
  26. from netbox.models.features import (
  27. CloningMixin, CustomFieldsMixin, CustomLinksMixin, ExportTemplatesMixin, SyncedDataMixin, TagsMixin,
  28. )
  29. from utilities.querysets import RestrictedQuerySet
  30. from utilities.rqworker import get_queue_for_model
  31. from utilities.utils import render_jinja2
  32. __all__ = (
  33. 'ConfigRevision',
  34. 'CustomLink',
  35. 'ExportTemplate',
  36. 'ImageAttachment',
  37. 'JobResult',
  38. 'JournalEntry',
  39. 'SavedFilter',
  40. 'Webhook',
  41. )
  42. class Webhook(ExportTemplatesMixin, ChangeLoggedModel):
  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. content_types = models.ManyToManyField(
  49. to=ContentType,
  50. related_name='webhooks',
  51. verbose_name='Object types',
  52. limit_choices_to=FeatureQuery('webhooks'),
  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=_("Triggers when a matching object is created.")
  62. )
  63. type_update = models.BooleanField(
  64. default=False,
  65. help_text=_("Triggers when a matching object is updated.")
  66. )
  67. type_delete = models.BooleanField(
  68. default=False,
  69. help_text=_("Triggers when a matching object is deleted.")
  70. )
  71. type_job_start = models.BooleanField(
  72. default=False,
  73. help_text=_("Triggers when a job for a matching object is started.")
  74. )
  75. type_job_end = models.BooleanField(
  76. default=False,
  77. help_text=_("Triggers when a job for a matching object terminates.")
  78. )
  79. payload_url = models.CharField(
  80. max_length=500,
  81. verbose_name='URL',
  82. help_text=_('This URL will be called using the HTTP method defined when the webhook is called. '
  83. 'Jinja2 template processing is supported with the same context as the request body.')
  84. )
  85. enabled = models.BooleanField(
  86. default=True
  87. )
  88. http_method = models.CharField(
  89. max_length=30,
  90. choices=WebhookHttpMethodChoices,
  91. default=WebhookHttpMethodChoices.METHOD_POST,
  92. verbose_name='HTTP method'
  93. )
  94. http_content_type = models.CharField(
  95. max_length=100,
  96. default=HTTP_CONTENT_TYPE_JSON,
  97. verbose_name='HTTP content type',
  98. help_text=_('The complete list of official content types is available '
  99. '<a href="https://www.iana.org/assignments/media-types/media-types.xhtml">here</a>.')
  100. )
  101. additional_headers = models.TextField(
  102. blank=True,
  103. help_text=_("User-supplied HTTP headers to be sent with the request in addition to the HTTP content type. "
  104. "Headers should be defined in the format <code>Name: Value</code>. Jinja2 template processing is "
  105. "supported with the same context as the request body (below).")
  106. )
  107. body_template = models.TextField(
  108. blank=True,
  109. help_text=_('Jinja2 template for a custom request body. If blank, a JSON object representing the change will be '
  110. 'included. Available context data includes: <code>event</code>, <code>model</code>, '
  111. '<code>timestamp</code>, <code>username</code>, <code>request_id</code>, and <code>data</code>.')
  112. )
  113. secret = models.CharField(
  114. max_length=255,
  115. blank=True,
  116. help_text=_("When provided, the request will include a 'X-Hook-Signature' "
  117. "header containing a HMAC hex digest of the payload body using "
  118. "the secret as the key. The secret is not transmitted in "
  119. "the request.")
  120. )
  121. conditions = models.JSONField(
  122. blank=True,
  123. null=True,
  124. help_text=_("A set of conditions which determine whether the webhook will be generated.")
  125. )
  126. ssl_verification = models.BooleanField(
  127. default=True,
  128. verbose_name='SSL verification',
  129. help_text=_("Enable SSL certificate verification. Disable with caution!")
  130. )
  131. ca_file_path = models.CharField(
  132. max_length=4096,
  133. null=True,
  134. blank=True,
  135. verbose_name='CA File Path',
  136. help_text=_('The specific CA certificate file to use for SSL verification. '
  137. 'Leave blank to use the system defaults.')
  138. )
  139. class Meta:
  140. ordering = ('name',)
  141. constraints = (
  142. models.UniqueConstraint(
  143. fields=('payload_url', 'type_create', 'type_update', 'type_delete'),
  144. name='%(app_label)s_%(class)s_unique_payload_url_types'
  145. ),
  146. )
  147. def __str__(self):
  148. return self.name
  149. def get_absolute_url(self):
  150. return reverse('extras:webhook', args=[self.pk])
  151. @property
  152. def docs_url(self):
  153. return f'{settings.STATIC_URL}docs/models/extras/webhook/'
  154. def clean(self):
  155. super().clean()
  156. # At least one action type must be selected
  157. if not any([
  158. self.type_create, self.type_update, self.type_delete, self.type_job_start, self.type_job_end
  159. ]):
  160. raise ValidationError(
  161. "At least one event type must be selected: create, update, delete, job_start, and/or job_end."
  162. )
  163. if self.conditions:
  164. try:
  165. ConditionSet(self.conditions)
  166. except ValueError as e:
  167. raise ValidationError({'conditions': e})
  168. # CA file path requires SSL verification enabled
  169. if not self.ssl_verification and self.ca_file_path:
  170. raise ValidationError({
  171. 'ca_file_path': 'Do not specify a CA certificate file if SSL verification is disabled.'
  172. })
  173. def render_headers(self, context):
  174. """
  175. Render additional_headers and return a dict of Header: Value pairs.
  176. """
  177. if not self.additional_headers:
  178. return {}
  179. ret = {}
  180. data = render_jinja2(self.additional_headers, context)
  181. for line in data.splitlines():
  182. header, value = line.split(':', 1)
  183. ret[header.strip()] = value.strip()
  184. return ret
  185. def render_body(self, context):
  186. """
  187. Render the body template, if defined. Otherwise, jump the context as a JSON object.
  188. """
  189. if self.body_template:
  190. return render_jinja2(self.body_template, context)
  191. else:
  192. return json.dumps(context, cls=JSONEncoder)
  193. def render_payload_url(self, context):
  194. """
  195. Render the payload URL.
  196. """
  197. return render_jinja2(self.payload_url, context)
  198. class CustomLink(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  199. """
  200. A custom link to an external representation of a NetBox object. The link text and URL fields accept Jinja2 template
  201. code to be rendered with an object as context.
  202. """
  203. content_types = models.ManyToManyField(
  204. to=ContentType,
  205. related_name='custom_links',
  206. help_text=_('The object type(s) to which this link applies.')
  207. )
  208. name = models.CharField(
  209. max_length=100,
  210. unique=True
  211. )
  212. enabled = models.BooleanField(
  213. default=True
  214. )
  215. link_text = models.TextField(
  216. help_text=_("Jinja2 template code for link text")
  217. )
  218. link_url = models.TextField(
  219. verbose_name='Link URL',
  220. help_text=_("Jinja2 template code for link URL")
  221. )
  222. weight = models.PositiveSmallIntegerField(
  223. default=100
  224. )
  225. group_name = models.CharField(
  226. max_length=50,
  227. blank=True,
  228. help_text=_("Links with the same group will appear as a dropdown menu")
  229. )
  230. button_class = models.CharField(
  231. max_length=30,
  232. choices=CustomLinkButtonClassChoices,
  233. default=CustomLinkButtonClassChoices.DEFAULT,
  234. help_text=_("The class of the first link in a group will be used for the dropdown button")
  235. )
  236. new_window = models.BooleanField(
  237. default=False,
  238. help_text=_("Force link to open in a new window")
  239. )
  240. clone_fields = (
  241. 'enabled', 'weight', 'group_name', 'button_class', 'new_window',
  242. )
  243. class Meta:
  244. ordering = ['group_name', 'weight', 'name']
  245. def __str__(self):
  246. return self.name
  247. def get_absolute_url(self):
  248. return reverse('extras:customlink', args=[self.pk])
  249. @property
  250. def docs_url(self):
  251. return f'{settings.STATIC_URL}docs/models/extras/customlink/'
  252. def render(self, context):
  253. """
  254. Render the CustomLink given the provided context, and return the text, link, and link_target.
  255. :param context: The context passed to Jinja2
  256. """
  257. text = render_jinja2(self.link_text, context)
  258. if not text:
  259. return {}
  260. link = render_jinja2(self.link_url, context)
  261. link_target = ' target="_blank"' if self.new_window else ''
  262. return {
  263. 'text': text,
  264. 'link': link,
  265. 'link_target': link_target,
  266. }
  267. class ExportTemplate(SyncedDataMixin, ExportTemplatesMixin, ChangeLoggedModel):
  268. content_types = models.ManyToManyField(
  269. to=ContentType,
  270. related_name='export_templates',
  271. help_text=_('The object type(s) to which this template applies.')
  272. )
  273. name = models.CharField(
  274. max_length=100
  275. )
  276. description = models.CharField(
  277. max_length=200,
  278. blank=True
  279. )
  280. template_code = models.TextField(
  281. help_text=_('Jinja2 template code. The list of objects being exported is passed as a context variable named '
  282. '<code>queryset</code>.')
  283. )
  284. mime_type = models.CharField(
  285. max_length=50,
  286. blank=True,
  287. verbose_name='MIME type',
  288. help_text=_('Defaults to <code>text/plain</code>')
  289. )
  290. file_extension = models.CharField(
  291. max_length=15,
  292. blank=True,
  293. help_text=_('Extension to append to the rendered filename')
  294. )
  295. as_attachment = models.BooleanField(
  296. default=True,
  297. help_text=_("Download file as attachment")
  298. )
  299. class Meta:
  300. ordering = ('name',)
  301. def __str__(self):
  302. return self.name
  303. def get_absolute_url(self):
  304. return reverse('extras:exporttemplate', args=[self.pk])
  305. @property
  306. def docs_url(self):
  307. return f'{settings.STATIC_URL}docs/models/extras/exporttemplate/'
  308. def clean(self):
  309. super().clean()
  310. if self.name.lower() == 'table':
  311. raise ValidationError({
  312. 'name': f'"{self.name}" is a reserved name. Please choose a different name.'
  313. })
  314. def sync_data(self):
  315. """
  316. Synchronize template content from the designated DataFile (if any).
  317. """
  318. self.template_code = self.data_file.data_as_string
  319. def render(self, queryset):
  320. """
  321. Render the contents of the template.
  322. """
  323. context = {
  324. 'queryset': queryset
  325. }
  326. output = render_jinja2(self.template_code, context)
  327. # Replace CRLF-style line terminators
  328. output = output.replace('\r\n', '\n')
  329. return output
  330. def render_to_response(self, queryset):
  331. """
  332. Render the template to an HTTP response, delivered as a named file attachment
  333. """
  334. output = self.render(queryset)
  335. mime_type = 'text/plain' if not self.mime_type else self.mime_type
  336. # Build the response
  337. response = HttpResponse(output, content_type=mime_type)
  338. if self.as_attachment:
  339. basename = queryset.model._meta.verbose_name_plural.replace(' ', '_')
  340. extension = f'.{self.file_extension}' if self.file_extension else ''
  341. filename = f'netbox_{basename}{extension}'
  342. response['Content-Disposition'] = f'attachment; filename="{filename}"'
  343. return response
  344. class SavedFilter(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  345. """
  346. A set of predefined keyword parameters that can be reused to filter for specific objects.
  347. """
  348. content_types = models.ManyToManyField(
  349. to=ContentType,
  350. related_name='saved_filters',
  351. help_text=_('The object type(s) to which this filter applies.')
  352. )
  353. name = models.CharField(
  354. max_length=100,
  355. unique=True
  356. )
  357. slug = models.SlugField(
  358. max_length=100,
  359. unique=True
  360. )
  361. description = models.CharField(
  362. max_length=200,
  363. blank=True
  364. )
  365. user = models.ForeignKey(
  366. to=User,
  367. on_delete=models.SET_NULL,
  368. blank=True,
  369. null=True
  370. )
  371. weight = models.PositiveSmallIntegerField(
  372. default=100
  373. )
  374. enabled = models.BooleanField(
  375. default=True
  376. )
  377. shared = models.BooleanField(
  378. default=True
  379. )
  380. parameters = models.JSONField()
  381. clone_fields = (
  382. 'enabled', 'weight',
  383. )
  384. class Meta:
  385. ordering = ('weight', 'name')
  386. def __str__(self):
  387. return self.name
  388. def get_absolute_url(self):
  389. return reverse('extras:savedfilter', args=[self.pk])
  390. @property
  391. def docs_url(self):
  392. return f'{settings.STATIC_URL}docs/models/extras/savedfilter/'
  393. def clean(self):
  394. super().clean()
  395. # Verify that `parameters` is a JSON object
  396. if type(self.parameters) is not dict:
  397. raise ValidationError(
  398. {'parameters': 'Filter parameters must be stored as a dictionary of keyword arguments.'}
  399. )
  400. @property
  401. def url_params(self):
  402. qd = QueryDict(mutable=True)
  403. qd.update(self.parameters)
  404. return qd.urlencode()
  405. class ImageAttachment(ChangeLoggedModel):
  406. """
  407. An uploaded image which is associated with an object.
  408. """
  409. content_type = models.ForeignKey(
  410. to=ContentType,
  411. on_delete=models.CASCADE
  412. )
  413. object_id = models.PositiveBigIntegerField()
  414. parent = GenericForeignKey(
  415. ct_field='content_type',
  416. fk_field='object_id'
  417. )
  418. image = models.ImageField(
  419. upload_to=image_upload,
  420. height_field='image_height',
  421. width_field='image_width'
  422. )
  423. image_height = models.PositiveSmallIntegerField()
  424. image_width = models.PositiveSmallIntegerField()
  425. name = models.CharField(
  426. max_length=50,
  427. blank=True
  428. )
  429. objects = RestrictedQuerySet.as_manager()
  430. clone_fields = ('content_type', 'object_id')
  431. class Meta:
  432. ordering = ('name', 'pk') # name may be non-unique
  433. def __str__(self):
  434. if self.name:
  435. return self.name
  436. filename = self.image.name.rsplit('/', 1)[-1]
  437. return filename.split('_', 2)[2]
  438. def delete(self, *args, **kwargs):
  439. _name = self.image.name
  440. super().delete(*args, **kwargs)
  441. # Delete file from disk
  442. self.image.delete(save=False)
  443. # Deleting the file erases its name. We restore the image's filename here in case we still need to reference it
  444. # before the request finishes. (For example, to display a message indicating the ImageAttachment was deleted.)
  445. self.image.name = _name
  446. @property
  447. def size(self):
  448. """
  449. Wrapper around `image.size` to suppress an OSError in case the file is inaccessible. Also opportunistically
  450. catch other exceptions that we know other storage back-ends to throw.
  451. """
  452. expected_exceptions = [OSError]
  453. try:
  454. from botocore.exceptions import ClientError
  455. expected_exceptions.append(ClientError)
  456. except ImportError:
  457. pass
  458. try:
  459. return self.image.size
  460. except tuple(expected_exceptions):
  461. return None
  462. def to_objectchange(self, action):
  463. objectchange = super().to_objectchange(action)
  464. objectchange.related_object = self.parent
  465. return objectchange
  466. class JournalEntry(CustomFieldsMixin, CustomLinksMixin, TagsMixin, ExportTemplatesMixin, ChangeLoggedModel):
  467. """
  468. A historical remark concerning an object; collectively, these form an object's journal. The journal is used to
  469. preserve historical context around an object, and complements NetBox's built-in change logging. For example, you
  470. might record a new journal entry when a device undergoes maintenance, or when a prefix is expanded.
  471. """
  472. assigned_object_type = models.ForeignKey(
  473. to=ContentType,
  474. on_delete=models.CASCADE
  475. )
  476. assigned_object_id = models.PositiveBigIntegerField()
  477. assigned_object = GenericForeignKey(
  478. ct_field='assigned_object_type',
  479. fk_field='assigned_object_id'
  480. )
  481. created_by = models.ForeignKey(
  482. to=User,
  483. on_delete=models.SET_NULL,
  484. blank=True,
  485. null=True
  486. )
  487. kind = models.CharField(
  488. max_length=30,
  489. choices=JournalEntryKindChoices,
  490. default=JournalEntryKindChoices.KIND_INFO
  491. )
  492. comments = models.TextField()
  493. class Meta:
  494. ordering = ('-created',)
  495. verbose_name_plural = 'journal entries'
  496. def __str__(self):
  497. created = timezone.localtime(self.created)
  498. return f"{date_format(created, format='SHORT_DATETIME_FORMAT')} ({self.get_kind_display()})"
  499. def get_absolute_url(self):
  500. return reverse('extras:journalentry', args=[self.pk])
  501. def clean(self):
  502. super().clean()
  503. # Prevent the creation of journal entries on unsupported models
  504. permitted_types = ContentType.objects.filter(FeatureQuery('journaling').get_query())
  505. if self.assigned_object_type not in permitted_types:
  506. raise ValidationError(f"Journaling is not supported for this object type ({self.assigned_object_type}).")
  507. def get_kind_color(self):
  508. return JournalEntryKindChoices.colors.get(self.kind)
  509. class JobResult(models.Model):
  510. """
  511. This model stores the results from running a user-defined report.
  512. """
  513. name = models.CharField(
  514. max_length=255
  515. )
  516. obj_type = models.ForeignKey(
  517. to=ContentType,
  518. related_name='job_results',
  519. verbose_name='Object types',
  520. limit_choices_to=FeatureQuery('jobs'),
  521. help_text=_("The object type to which this job result applies"),
  522. on_delete=models.CASCADE,
  523. )
  524. created = models.DateTimeField(
  525. auto_now_add=True
  526. )
  527. scheduled = models.DateTimeField(
  528. null=True,
  529. blank=True
  530. )
  531. interval = models.PositiveIntegerField(
  532. blank=True,
  533. null=True,
  534. validators=(
  535. MinValueValidator(1),
  536. ),
  537. help_text=_("Recurrence interval (in minutes)")
  538. )
  539. started = models.DateTimeField(
  540. null=True,
  541. blank=True
  542. )
  543. completed = models.DateTimeField(
  544. null=True,
  545. blank=True
  546. )
  547. user = models.ForeignKey(
  548. to=User,
  549. on_delete=models.SET_NULL,
  550. related_name='+',
  551. blank=True,
  552. null=True
  553. )
  554. status = models.CharField(
  555. max_length=30,
  556. choices=JobResultStatusChoices,
  557. default=JobResultStatusChoices.STATUS_PENDING
  558. )
  559. data = models.JSONField(
  560. null=True,
  561. blank=True
  562. )
  563. job_id = models.UUIDField(
  564. unique=True
  565. )
  566. objects = RestrictedQuerySet.as_manager()
  567. class Meta:
  568. ordering = ['-created']
  569. def __str__(self):
  570. return str(self.job_id)
  571. def delete(self, *args, **kwargs):
  572. super().delete(*args, **kwargs)
  573. rq_queue_name = get_config().QUEUE_MAPPINGS.get(self.obj_type.model, RQ_QUEUE_DEFAULT)
  574. queue = django_rq.get_queue(rq_queue_name)
  575. job = queue.fetch_job(str(self.job_id))
  576. if job:
  577. job.cancel()
  578. def get_absolute_url(self):
  579. try:
  580. return reverse(f'extras:{self.obj_type.model}_result', args=[self.pk])
  581. except NoReverseMatch:
  582. return None
  583. def get_status_color(self):
  584. return JobResultStatusChoices.colors.get(self.status)
  585. @property
  586. def duration(self):
  587. if not self.completed:
  588. return None
  589. start_time = self.started or self.created
  590. if not start_time:
  591. return None
  592. duration = self.completed - start_time
  593. minutes, seconds = divmod(duration.total_seconds(), 60)
  594. return f"{int(minutes)} minutes, {seconds:.2f} seconds"
  595. def start(self):
  596. """
  597. Record the job's start time and update its status to "running."
  598. """
  599. if self.started is not None:
  600. return
  601. # Start the job
  602. self.started = timezone.now()
  603. self.status = JobResultStatusChoices.STATUS_RUNNING
  604. JobResult.objects.filter(pk=self.pk).update(started=self.started, status=self.status)
  605. # Handle webhooks
  606. self.trigger_webhooks(event=EVENT_JOB_START)
  607. def terminate(self, status=JobResultStatusChoices.STATUS_COMPLETED):
  608. """
  609. Mark the job as completed, optionally specifying a particular termination status.
  610. """
  611. valid_statuses = JobResultStatusChoices.TERMINAL_STATE_CHOICES
  612. if status not in valid_statuses:
  613. raise ValueError(f"Invalid status for job termination. Choices are: {', '.join(valid_statuses)}")
  614. # Mark the job as completed
  615. self.status = status
  616. self.completed = timezone.now()
  617. JobResult.objects.filter(pk=self.pk).update(status=self.status, completed=self.completed)
  618. # Handle webhooks
  619. self.trigger_webhooks(event=EVENT_JOB_END)
  620. @classmethod
  621. def enqueue_job(cls, func, name, obj_type, user, schedule_at=None, interval=None, *args, **kwargs):
  622. """
  623. Create a JobResult instance and enqueue a job using the given callable
  624. Args:
  625. func: The callable object to be enqueued for execution
  626. name: Name for the JobResult instance
  627. obj_type: ContentType to link to the JobResult instance obj_type
  628. user: User object to link to the JobResult instance
  629. schedule_at: Schedule the job to be executed at the passed date and time
  630. interval: Recurrence interval (in minutes)
  631. """
  632. rq_queue_name = get_queue_for_model(obj_type.model)
  633. queue = django_rq.get_queue(rq_queue_name)
  634. status = JobResultStatusChoices.STATUS_SCHEDULED if schedule_at else JobResultStatusChoices.STATUS_PENDING
  635. job_result: JobResult = JobResult.objects.create(
  636. name=name,
  637. status=status,
  638. obj_type=obj_type,
  639. scheduled=schedule_at,
  640. interval=interval,
  641. user=user,
  642. job_id=uuid.uuid4()
  643. )
  644. if schedule_at:
  645. queue.enqueue_at(schedule_at, func, job_id=str(job_result.job_id), job_result=job_result, **kwargs)
  646. else:
  647. queue.enqueue(func, job_id=str(job_result.job_id), job_result=job_result, **kwargs)
  648. return job_result
  649. def trigger_webhooks(self, event):
  650. rq_queue_name = get_config().QUEUE_MAPPINGS.get('webhook', RQ_QUEUE_DEFAULT)
  651. rq_queue = django_rq.get_queue(rq_queue_name, is_async=False)
  652. # Fetch any webhooks matching this object type and action
  653. webhooks = Webhook.objects.filter(
  654. **{f'type_{event}': True},
  655. content_types=self.obj_type,
  656. enabled=True
  657. )
  658. for webhook in webhooks:
  659. rq_queue.enqueue(
  660. "extras.webhooks_worker.process_webhook",
  661. webhook=webhook,
  662. model_name=self.obj_type.model,
  663. event=event,
  664. data=self.data,
  665. timestamp=str(timezone.now()),
  666. username=self.user.username
  667. )
  668. class ConfigRevision(models.Model):
  669. """
  670. An atomic revision of NetBox's configuration.
  671. """
  672. created = models.DateTimeField(
  673. auto_now_add=True
  674. )
  675. comment = models.CharField(
  676. max_length=200,
  677. blank=True
  678. )
  679. data = models.JSONField(
  680. blank=True,
  681. null=True,
  682. verbose_name='Configuration data'
  683. )
  684. def __str__(self):
  685. return f'Config revision #{self.pk} ({self.created})'
  686. def __getattr__(self, item):
  687. if item in self.data:
  688. return self.data[item]
  689. return super().__getattribute__(item)
  690. def activate(self):
  691. """
  692. Cache the configuration data.
  693. """
  694. cache.set('config', self.data, None)
  695. cache.set('config_version', self.pk, None)
  696. @admin.display(boolean=True)
  697. def is_active(self):
  698. return cache.get('config_version') == self.pk