scripts.py 19 KB

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