scripts.py 19 KB

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