scripts.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. import inspect
  2. import logging
  3. import os
  4. import re
  5. from django import forms
  6. from django.core.exceptions import ValidationError
  7. from django.core.files.storage import storages
  8. from django.core.validators import RegexValidator
  9. from django.utils import timezone
  10. from django.utils.functional import classproperty
  11. from django.utils.translation import gettext as _
  12. from rq.exceptions import TimeoutFormatError
  13. from rq.utils import parse_timeout
  14. from core.choices import JobNotificationChoices
  15. from extras.choices import LogLevelChoices
  16. from extras.constants import SCRIPT_MODULE_NAME_PREFIX
  17. from extras.models import ScriptModule
  18. from ipam.formfields import IPAddressFormField, IPNetworkFormField
  19. from ipam.validators import MaxPrefixLengthValidator, MinPrefixLengthValidator, prefix_validator
  20. from utilities.forms import add_blank_choice
  21. from utilities.forms.fields import DynamicModelChoiceField, DynamicModelMultipleChoiceField
  22. from utilities.forms.widgets import DatePicker, DateTimePicker
  23. from .forms import ScriptForm
  24. __all__ = (
  25. 'BaseScript',
  26. 'BooleanVar',
  27. 'ChoiceVar',
  28. 'DateTimeVar',
  29. 'DateVar',
  30. 'DecimalVar',
  31. 'FileVar',
  32. 'IPAddressVar',
  33. 'IPAddressWithMaskVar',
  34. 'IPNetworkVar',
  35. 'IntegerVar',
  36. 'MultiChoiceVar',
  37. 'MultiObjectVar',
  38. 'ObjectVar',
  39. 'Script',
  40. 'StringVar',
  41. 'TextVar',
  42. 'get_module_and_script',
  43. )
  44. # Sentinel distinguishing "argument not supplied" from an explicit None in validate_meta().
  45. _UNSET = object()
  46. #
  47. # Script variables
  48. #
  49. class ScriptVariable:
  50. """
  51. Base model for script variables
  52. """
  53. form_field = forms.CharField
  54. def __init__(self, label='', description='', default=None, required=True, widget=None):
  55. # Initialize field attributes
  56. if not hasattr(self, 'field_attrs'):
  57. self.field_attrs = {}
  58. if label:
  59. self.field_attrs['label'] = label
  60. if description:
  61. self.field_attrs['help_text'] = description
  62. if default is not None:
  63. self.field_attrs['initial'] = default
  64. if widget:
  65. self.field_attrs['widget'] = widget
  66. self.field_attrs['required'] = required
  67. def as_field(self):
  68. """
  69. Render the variable as a Django form field.
  70. """
  71. form_field = self.form_field(**self.field_attrs)
  72. if not isinstance(form_field.widget, forms.CheckboxInput):
  73. if form_field.widget.attrs and 'class' in form_field.widget.attrs.keys():
  74. form_field.widget.attrs['class'] += ' form-control'
  75. else:
  76. form_field.widget.attrs['class'] = 'form-control'
  77. return form_field
  78. class StringVar(ScriptVariable):
  79. """
  80. Character string representation. Can enforce minimum/maximum length and/or regex validation.
  81. """
  82. def __init__(self, min_length=None, max_length=None, regex=None, *args, **kwargs):
  83. super().__init__(*args, **kwargs)
  84. # Optional minimum/maximum lengths
  85. if min_length:
  86. self.field_attrs['min_length'] = min_length
  87. if max_length:
  88. self.field_attrs['max_length'] = max_length
  89. # Optional regular expression validation
  90. if regex:
  91. self.field_attrs['validators'] = [
  92. RegexValidator(
  93. regex=regex,
  94. message='Invalid value. Must match regex: {}'.format(regex),
  95. code='invalid'
  96. )
  97. ]
  98. class TextVar(ScriptVariable):
  99. """
  100. Free-form text data. Renders as a <textarea>.
  101. """
  102. form_field = forms.CharField
  103. def __init__(self, *args, **kwargs):
  104. super().__init__(*args, **kwargs)
  105. self.field_attrs['widget'] = forms.Textarea
  106. class IntegerVar(ScriptVariable):
  107. """
  108. Integer representation. Can enforce minimum/maximum values.
  109. """
  110. form_field = forms.IntegerField
  111. def __init__(self, min_value=None, max_value=None, *args, **kwargs):
  112. super().__init__(*args, **kwargs)
  113. # Optional minimum/maximum values
  114. if min_value:
  115. self.field_attrs['min_value'] = min_value
  116. if max_value:
  117. self.field_attrs['max_value'] = max_value
  118. class DecimalVar(ScriptVariable):
  119. """
  120. Decimal representation. Can enforce minimum/maximum values, maximum digits and decimal places.
  121. """
  122. form_field = forms.DecimalField
  123. def __init__(self, min_value=None, max_value=None, max_digits=None, decimal_places=None, *args, **kwargs,):
  124. super().__init__(*args, **kwargs)
  125. # Optional constraints
  126. if min_value:
  127. self.field_attrs["min_value"] = min_value
  128. if max_value:
  129. self.field_attrs["max_value"] = max_value
  130. if max_digits:
  131. self.field_attrs["max_digits"] = max_digits
  132. if decimal_places:
  133. self.field_attrs["decimal_places"] = decimal_places
  134. class BooleanVar(ScriptVariable):
  135. """
  136. Boolean representation (true/false). Renders as a checkbox.
  137. """
  138. form_field = forms.BooleanField
  139. def __init__(self, *args, **kwargs):
  140. super().__init__(*args, **kwargs)
  141. # Boolean fields cannot be required
  142. self.field_attrs['required'] = False
  143. class ChoiceVar(ScriptVariable):
  144. """
  145. Select one of several predefined static choices, passed as a list of two-tuples. Example:
  146. color = ChoiceVar(
  147. choices=(
  148. ('#ff0000', 'Red'),
  149. ('#00ff00', 'Green'),
  150. ('#0000ff', 'Blue')
  151. )
  152. )
  153. """
  154. form_field = forms.ChoiceField
  155. def __init__(self, choices, *args, **kwargs):
  156. super().__init__(*args, **kwargs)
  157. # Set field choices, adding a blank choice to avoid forced selections
  158. self.field_attrs['choices'] = add_blank_choice(choices)
  159. class DateVar(ScriptVariable):
  160. """
  161. A date.
  162. """
  163. form_field = forms.DateField
  164. def __init__(self, *args, **kwargs):
  165. super().__init__(*args, **kwargs)
  166. self.form_field.widget = DatePicker()
  167. class DateTimeVar(ScriptVariable):
  168. """
  169. A date and a time.
  170. """
  171. form_field = forms.DateTimeField
  172. def __init__(self, *args, **kwargs):
  173. super().__init__(*args, **kwargs)
  174. self.form_field.widget = DateTimePicker()
  175. class MultiChoiceVar(ScriptVariable):
  176. """
  177. Like ChoiceVar, but allows for the selection of multiple choices.
  178. """
  179. form_field = forms.MultipleChoiceField
  180. def __init__(self, choices, *args, **kwargs):
  181. super().__init__(*args, **kwargs)
  182. # Set field choices
  183. self.field_attrs['choices'] = choices
  184. class ObjectVar(ScriptVariable):
  185. """
  186. A single object within NetBox.
  187. :param model: The NetBox model being referenced
  188. :param query_params: A dictionary of additional query parameters to attach when making REST API requests (optional)
  189. :param context: A custom dictionary mapping template context variables to fields, used when rendering <option>
  190. elements within the dropdown menu (optional)
  191. :param null_option: The label to use as a "null" selection option (optional)
  192. :param selector: Include an advanced object selection widget to assist the user in identifying the desired
  193. object (optional)
  194. :param quick_add: Include a widget to quickly create a new related object for assignment. (optional)
  195. """
  196. form_field = DynamicModelChoiceField
  197. def __init__(self, model, query_params=None, context=None, null_option=None, selector=False, quick_add=False,
  198. *args, **kwargs):
  199. super().__init__(*args, **kwargs)
  200. self.field_attrs.update({
  201. 'queryset': model.objects.all(),
  202. 'query_params': query_params,
  203. 'context': context,
  204. 'null_option': null_option,
  205. 'selector': selector,
  206. 'quick_add': quick_add,
  207. })
  208. class MultiObjectVar(ObjectVar):
  209. """
  210. Like ObjectVar, but can represent one or more objects.
  211. """
  212. form_field = DynamicModelMultipleChoiceField
  213. class FileVar(ScriptVariable):
  214. """
  215. An uploaded file.
  216. """
  217. form_field = forms.FileField
  218. class IPAddressVar(ScriptVariable):
  219. """
  220. An IPv4 or IPv6 address without a mask.
  221. """
  222. form_field = IPAddressFormField
  223. class IPAddressWithMaskVar(ScriptVariable):
  224. """
  225. An IPv4 or IPv6 address with a mask.
  226. """
  227. form_field = IPNetworkFormField
  228. class IPNetworkVar(ScriptVariable):
  229. """
  230. An IPv4 or IPv6 prefix.
  231. """
  232. form_field = IPNetworkFormField
  233. def __init__(self, min_prefix_length=None, max_prefix_length=None, *args, **kwargs):
  234. super().__init__(*args, **kwargs)
  235. # Set prefix validator and optional minimum/maximum prefix lengths
  236. self.field_attrs['validators'] = [prefix_validator]
  237. if min_prefix_length is not None:
  238. self.field_attrs['validators'].append(
  239. MinPrefixLengthValidator(min_prefix_length)
  240. )
  241. if max_prefix_length is not None:
  242. self.field_attrs['validators'].append(
  243. MaxPrefixLengthValidator(max_prefix_length)
  244. )
  245. #
  246. # Scripts
  247. #
  248. class BaseScript:
  249. """
  250. Base model for custom scripts. User classes should inherit from this model if they want to extend Script
  251. functionality for use in other subclasses.
  252. """
  253. # Prevent django from instantiating the class on all accesses
  254. do_not_call_in_templates = True
  255. class Meta:
  256. pass
  257. def __init__(self):
  258. self.messages = [] # Primary script log
  259. self.tests = {} # Mapping of logs for test methods
  260. self.output = ''
  261. self.failed = False
  262. self._current_test = None # Tracks the current test method being run (if any)
  263. # Initiate the log
  264. self.logger = logging.getLogger(f"netbox.scripts.{self.full_name}")
  265. # Declare the placeholder for the current request
  266. self.request = None
  267. # Initiate the storage backend (local, S3, etc) as a class attr
  268. self.storage = storages.create_storage(storages.backends["scripts"])
  269. # Compile test methods and initialize results skeleton
  270. for method in dir(self):
  271. if method.startswith('test_') and callable(getattr(self, method)):
  272. self.tests[method] = {
  273. LogLevelChoices.LOG_SUCCESS: 0,
  274. LogLevelChoices.LOG_INFO: 0,
  275. LogLevelChoices.LOG_WARNING: 0,
  276. LogLevelChoices.LOG_FAILURE: 0,
  277. 'log': [],
  278. }
  279. def __str__(self):
  280. return self.name
  281. @classproperty
  282. def module(self):
  283. # Strip the internal prefix applied when the module is loaded (see #22566) so that
  284. # user-facing names (full_name, logger namespaces) reflect the original script filename.
  285. name = self.__module__
  286. if name.startswith(SCRIPT_MODULE_NAME_PREFIX):
  287. name = name[len(SCRIPT_MODULE_NAME_PREFIX):]
  288. return name
  289. @classproperty
  290. def class_name(self):
  291. return self.__name__
  292. @classproperty
  293. def full_name(self):
  294. return f'{self.module}.{self.class_name}'
  295. @classmethod
  296. def root_module(cls):
  297. return cls.module.split(".")[0]
  298. # Author-defined attributes
  299. @classproperty
  300. def name(self):
  301. return getattr(self.Meta, 'name', self.__name__)
  302. @classproperty
  303. def description(self):
  304. return getattr(self.Meta, 'description', '')
  305. @classproperty
  306. def field_order(self):
  307. return getattr(self.Meta, 'field_order', None)
  308. @classproperty
  309. def fieldsets(self):
  310. return getattr(self.Meta, 'fieldsets', None)
  311. @classproperty
  312. def commit_default(self):
  313. return getattr(self.Meta, 'commit_default', True)
  314. @classproperty
  315. def job_timeout(self):
  316. return getattr(self.Meta, 'job_timeout', None)
  317. @classproperty
  318. def scheduling_enabled(self):
  319. return getattr(self.Meta, 'scheduling_enabled', True)
  320. @classproperty
  321. def notifications_default(self):
  322. return getattr(self.Meta, 'notifications_default', JobNotificationChoices.NOTIFICATION_ALWAYS)
  323. @classmethod
  324. def validate_meta(cls, job_timeout=_UNSET, notifications=_UNSET):
  325. """
  326. Validate the execution parameters used to run this script. Raises a ValidationError if any value is invalid,
  327. so that a misconfigured script surfaces an actionable error rather than an unhandled exception when the job is
  328. enqueued (see #22872).
  329. The values actually enqueued are validated, not the raw Meta values: a caller may supply an explicit
  330. `job_timeout` or `notifications` (e.g. via the REST API), in which case that value is checked. When a caller
  331. omits a value, the corresponding Meta default is validated instead. Unset values fall back to valid defaults
  332. and are not rejected.
  333. """
  334. errors = {}
  335. job_timeout = cls.job_timeout if job_timeout is _UNSET else job_timeout
  336. if job_timeout is not None:
  337. # parse_timeout() is what RQ applies to the timeout downstream. It raises TimeoutFormatError for
  338. # malformed duration strings, but a job_timeout of an unexpected type (e.g. a list) instead raises
  339. # TypeError/ValueError/AssertionError from its internal int()/assert. Catch them all so any invalid value
  340. # surfaces as an actionable error rather than an unhandled 500.
  341. try:
  342. parsed_timeout = parse_timeout(job_timeout)
  343. except (TimeoutFormatError, TypeError, ValueError, AssertionError):
  344. parsed_timeout = None
  345. errors['job_timeout'] = _(
  346. "Invalid job_timeout value '{value}': must be an integer (seconds) or a duration string such as "
  347. "'1h' or '30m'."
  348. ).format(value=job_timeout)
  349. if parsed_timeout is not None and parsed_timeout <= 0:
  350. errors['job_timeout'] = _(
  351. "Invalid job_timeout value '{value}': must be a positive duration."
  352. ).format(value=job_timeout)
  353. # A caller may pass notifications=None to mean "use the script's default"; treat that as unset.
  354. if notifications is _UNSET or notifications is None:
  355. notifications = cls.notifications_default
  356. if notifications not in JobNotificationChoices.values():
  357. valid = ', '.join(JobNotificationChoices.values())
  358. errors['notifications_default'] = _(
  359. "Invalid notifications value '{value}': must be one of {valid}."
  360. ).format(value=notifications, valid=valid)
  361. if errors:
  362. raise ValidationError(errors)
  363. @property
  364. def filename(self):
  365. return inspect.getfile(self.__class__)
  366. def findsource(self, object):
  367. with self.storage.open(os.path.basename(self.filename), 'r') as f:
  368. data = f.read()
  369. # Break the source code into lines
  370. lines = [line + '\n' for line in data.splitlines()]
  371. # Find the class definition
  372. name = object.__name__
  373. pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
  374. # use the class definition with the least indentation
  375. candidates = []
  376. for i in range(len(lines)):
  377. match = pat.match(lines[i])
  378. if match:
  379. if lines[i][0] == 'c':
  380. return lines, i
  381. candidates.append((match.group(1), i))
  382. if not candidates:
  383. raise OSError('could not find class definition')
  384. # Sort the candidates by whitespace, and by line number
  385. candidates.sort()
  386. return lines, candidates[0][1]
  387. @property
  388. def source(self):
  389. # Can't use inspect.getsource() as it uses os to get the file
  390. # inspect uses ast, but that is overkill for this as we only do
  391. # classes.
  392. object = self.__class__
  393. try:
  394. lines, lnum = self.findsource(object)
  395. lines = inspect.getblock(lines[lnum:])
  396. return ''.join(lines)
  397. except OSError:
  398. return ''
  399. @classmethod
  400. def _get_vars(cls):
  401. vars = {}
  402. # Iterate all base classes looking for ScriptVariables
  403. for base_class in inspect.getmro(cls):
  404. # When object is reached there's no reason to continue
  405. if base_class is object:
  406. break
  407. for name, attr in base_class.__dict__.items():
  408. if name not in vars and issubclass(attr.__class__, ScriptVariable):
  409. vars[name] = attr
  410. # Order variables according to field_order
  411. if not cls.field_order:
  412. return vars
  413. ordered_vars = {
  414. field: vars.pop(field) for field in cls.field_order if field in vars
  415. }
  416. ordered_vars.update(vars)
  417. return ordered_vars
  418. def run(self, data, commit):
  419. """
  420. Override this method with custom script logic.
  421. """
  422. # Backward compatibility for legacy Reports
  423. self.pre_run()
  424. self.run_tests()
  425. self.post_run()
  426. def get_job_data(self):
  427. """
  428. Return a dictionary of data to attach to the script's Job.
  429. """
  430. return {
  431. 'log': self.messages,
  432. 'output': self.output,
  433. 'tests': self.tests,
  434. }
  435. #
  436. # Form rendering
  437. #
  438. def get_fieldsets(self):
  439. fieldsets = []
  440. if self.fieldsets:
  441. fieldsets.extend(self.fieldsets)
  442. else:
  443. fields = list(name for name, __ in self._get_vars().items())
  444. fieldsets.append((_('Script Data'), fields))
  445. # Append the default fieldset if defined in the Meta class
  446. if self.scheduling_enabled:
  447. exec_parameters = ('_schedule_at', '_interval', '_commit', '_notifications')
  448. else:
  449. exec_parameters = ('_commit', '_notifications')
  450. fieldsets.append((_('Script Execution Parameters'), exec_parameters))
  451. return fieldsets
  452. def as_form(self, data=None, files=None, initial=None):
  453. """
  454. Return a Django form suitable for populating the context data required to run this Script.
  455. """
  456. # Create a dynamic ScriptForm subclass from script variables
  457. fields = {
  458. name: var.as_field() for name, var in self._get_vars().items()
  459. }
  460. FormClass = type('ScriptForm', (ScriptForm,), fields)
  461. form = FormClass(data, files, initial=initial)
  462. # Set initial "commit" checkbox state based on the script's Meta parameter
  463. form.fields['_commit'].initial = self.commit_default
  464. # Set initial "notifications" selection based on the script's Meta parameter
  465. form.fields['_notifications'].initial = self.notifications_default
  466. # Hide fields if scheduling has been disabled
  467. if not self.scheduling_enabled:
  468. form.fields['_schedule_at'].widget = forms.HiddenInput()
  469. form.fields['_interval'].widget = forms.HiddenInput()
  470. return form
  471. #
  472. # Logging
  473. #
  474. def _log(self, message, obj=None, level=LogLevelChoices.LOG_INFO):
  475. """
  476. Log a message. Do not call this method directly; use one of the log_* wrappers below.
  477. """
  478. if level not in LogLevelChoices.values():
  479. raise ValueError(f"Invalid logging level: {level}")
  480. # A test method is currently active, so log the message using legacy Report logging
  481. if self._current_test:
  482. # Increment the event counter for this level
  483. if level in self.tests[self._current_test]:
  484. self.tests[self._current_test][level] += 1
  485. # Record message (if any) to the report log
  486. if message:
  487. # TODO: Use a dataclass for test method logs
  488. self.tests[self._current_test]['log'].append((
  489. timezone.now().isoformat(),
  490. level,
  491. str(obj) if obj else None,
  492. obj.get_absolute_url() if hasattr(obj, 'get_absolute_url') else None,
  493. str(message),
  494. ))
  495. elif message:
  496. # Record to the script's log
  497. self.messages.append({
  498. 'time': timezone.now().isoformat(),
  499. 'status': level,
  500. 'message': str(message),
  501. 'obj': str(obj) if obj else None,
  502. 'url': obj.get_absolute_url() if hasattr(obj, 'get_absolute_url') else None,
  503. })
  504. # Record to the system log
  505. if obj:
  506. message = f"{obj}: {message}"
  507. self.logger.log(LogLevelChoices.SYSTEM_LEVELS[level], message)
  508. def log_debug(self, message=None, obj=None):
  509. self._log(message, obj, level=LogLevelChoices.LOG_DEBUG)
  510. def log_success(self, message=None, obj=None):
  511. self._log(message, obj, level=LogLevelChoices.LOG_SUCCESS)
  512. def log_info(self, message=None, obj=None):
  513. self._log(message, obj, level=LogLevelChoices.LOG_INFO)
  514. def log_warning(self, message=None, obj=None):
  515. self._log(message, obj, level=LogLevelChoices.LOG_WARNING)
  516. def log_failure(self, message=None, obj=None):
  517. self._log(message, obj, level=LogLevelChoices.LOG_FAILURE)
  518. self.failed = True
  519. #
  520. # Legacy Report functionality
  521. #
  522. def run_tests(self):
  523. """
  524. Run the report and save its results. Each test method will be executed in order.
  525. """
  526. self.logger.info("Running report")
  527. try:
  528. for test_name in self.tests:
  529. self._current_test = test_name
  530. test_method = getattr(self, test_name)
  531. test_method()
  532. self._current_test = None
  533. except Exception as e:
  534. self._current_test = None
  535. self.post_run()
  536. raise e
  537. def pre_run(self):
  538. """
  539. Legacy method for operations performed immediately prior to running a Report.
  540. """
  541. pass
  542. def post_run(self):
  543. """
  544. Legacy method for operations performed immediately after running a Report.
  545. """
  546. pass
  547. class Script(BaseScript):
  548. """
  549. Classes which inherit this model will appear in the list of available scripts.
  550. """
  551. pass
  552. #
  553. # Functions
  554. #
  555. def is_variable(obj):
  556. """
  557. Returns True if the object is a ScriptVariable.
  558. """
  559. return isinstance(obj, ScriptVariable)
  560. def get_module_and_script(module_name, script_name):
  561. module = ScriptModule.objects.get(file_path=f'{module_name}.py')
  562. script = module.scripts.get(name=script_name)
  563. return module, script