scripts.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import inspect
  2. import json
  3. import logging
  4. import os
  5. import pkgutil
  6. import sys
  7. import traceback
  8. import threading
  9. from collections import OrderedDict
  10. import yaml
  11. from django import forms
  12. from django.conf import settings
  13. from django.core.validators import RegexValidator
  14. from django.db import transaction
  15. from django.utils.functional import classproperty
  16. from extras.api.serializers import ScriptOutputSerializer
  17. from extras.choices import JobResultStatusChoices, LogLevelChoices
  18. from ipam.formfields import IPAddressFormField, IPNetworkFormField
  19. from ipam.validators import MaxPrefixLengthValidator, MinPrefixLengthValidator, prefix_validator
  20. from utilities.exceptions import AbortTransaction
  21. from utilities.forms import add_blank_choice, DynamicModelChoiceField, DynamicModelMultipleChoiceField
  22. from .context_managers import change_logging
  23. from .forms import ScriptForm
  24. __all__ = [
  25. 'BaseScript',
  26. 'BooleanVar',
  27. 'ChoiceVar',
  28. 'FileVar',
  29. 'IntegerVar',
  30. 'IPAddressVar',
  31. 'IPAddressWithMaskVar',
  32. 'IPNetworkVar',
  33. 'MultiChoiceVar',
  34. 'MultiObjectVar',
  35. 'ObjectVar',
  36. 'Script',
  37. 'StringVar',
  38. 'TextVar',
  39. ]
  40. lock = threading.Lock()
  41. #
  42. # Script variables
  43. #
  44. class ScriptVariable:
  45. """
  46. Base model for script variables
  47. """
  48. form_field = forms.CharField
  49. def __init__(self, label='', description='', default=None, required=True, widget=None):
  50. # Initialize field attributes
  51. if not hasattr(self, 'field_attrs'):
  52. self.field_attrs = {}
  53. if label:
  54. self.field_attrs['label'] = label
  55. if description:
  56. self.field_attrs['help_text'] = description
  57. if default:
  58. self.field_attrs['initial'] = default
  59. if widget:
  60. self.field_attrs['widget'] = widget
  61. self.field_attrs['required'] = required
  62. def as_field(self):
  63. """
  64. Render the variable as a Django form field.
  65. """
  66. form_field = self.form_field(**self.field_attrs)
  67. if not isinstance(form_field.widget, forms.CheckboxInput):
  68. if form_field.widget.attrs and 'class' in form_field.widget.attrs.keys():
  69. form_field.widget.attrs['class'] += ' form-control'
  70. else:
  71. form_field.widget.attrs['class'] = 'form-control'
  72. return form_field
  73. class StringVar(ScriptVariable):
  74. """
  75. Character string representation. Can enforce minimum/maximum length and/or regex validation.
  76. """
  77. def __init__(self, min_length=None, max_length=None, regex=None, *args, **kwargs):
  78. super().__init__(*args, **kwargs)
  79. # Optional minimum/maximum lengths
  80. if min_length:
  81. self.field_attrs['min_length'] = min_length
  82. if max_length:
  83. self.field_attrs['max_length'] = max_length
  84. # Optional regular expression validation
  85. if regex:
  86. self.field_attrs['validators'] = [
  87. RegexValidator(
  88. regex=regex,
  89. message='Invalid value. Must match regex: {}'.format(regex),
  90. code='invalid'
  91. )
  92. ]
  93. class TextVar(ScriptVariable):
  94. """
  95. Free-form text data. Renders as a <textarea>.
  96. """
  97. form_field = forms.CharField
  98. def __init__(self, *args, **kwargs):
  99. super().__init__(*args, **kwargs)
  100. self.field_attrs['widget'] = forms.Textarea
  101. class IntegerVar(ScriptVariable):
  102. """
  103. Integer representation. Can enforce minimum/maximum values.
  104. """
  105. form_field = forms.IntegerField
  106. def __init__(self, min_value=None, max_value=None, *args, **kwargs):
  107. super().__init__(*args, **kwargs)
  108. # Optional minimum/maximum values
  109. if min_value:
  110. self.field_attrs['min_value'] = min_value
  111. if max_value:
  112. self.field_attrs['max_value'] = max_value
  113. class BooleanVar(ScriptVariable):
  114. """
  115. Boolean representation (true/false). Renders as a checkbox.
  116. """
  117. form_field = forms.BooleanField
  118. def __init__(self, *args, **kwargs):
  119. super().__init__(*args, **kwargs)
  120. # Boolean fields cannot be required
  121. self.field_attrs['required'] = False
  122. class ChoiceVar(ScriptVariable):
  123. """
  124. Select one of several predefined static choices, passed as a list of two-tuples. Example:
  125. color = ChoiceVar(
  126. choices=(
  127. ('#ff0000', 'Red'),
  128. ('#00ff00', 'Green'),
  129. ('#0000ff', 'Blue')
  130. )
  131. )
  132. """
  133. form_field = forms.ChoiceField
  134. def __init__(self, choices, *args, **kwargs):
  135. super().__init__(*args, **kwargs)
  136. # Set field choices, adding a blank choice to avoid forced selections
  137. self.field_attrs['choices'] = add_blank_choice(choices)
  138. class MultiChoiceVar(ScriptVariable):
  139. """
  140. Like ChoiceVar, but allows for the selection of multiple choices.
  141. """
  142. form_field = forms.MultipleChoiceField
  143. def __init__(self, choices, *args, **kwargs):
  144. super().__init__(*args, **kwargs)
  145. # Set field choices
  146. self.field_attrs['choices'] = choices
  147. class ObjectVar(ScriptVariable):
  148. """
  149. A single object within NetBox.
  150. :param model: The NetBox model being referenced
  151. :param query_params: A dictionary of additional query parameters to attach when making REST API requests (optional)
  152. :param null_option: The label to use as a "null" selection option (optional)
  153. """
  154. form_field = DynamicModelChoiceField
  155. def __init__(self, model, query_params=None, null_option=None, *args, **kwargs):
  156. super().__init__(*args, **kwargs)
  157. self.field_attrs.update({
  158. 'queryset': model.objects.all(),
  159. 'query_params': query_params,
  160. 'null_option': null_option,
  161. })
  162. class MultiObjectVar(ObjectVar):
  163. """
  164. Like ObjectVar, but can represent one or more objects.
  165. """
  166. form_field = DynamicModelMultipleChoiceField
  167. class FileVar(ScriptVariable):
  168. """
  169. An uploaded file.
  170. """
  171. form_field = forms.FileField
  172. class IPAddressVar(ScriptVariable):
  173. """
  174. An IPv4 or IPv6 address without a mask.
  175. """
  176. form_field = IPAddressFormField
  177. class IPAddressWithMaskVar(ScriptVariable):
  178. """
  179. An IPv4 or IPv6 address with a mask.
  180. """
  181. form_field = IPNetworkFormField
  182. class IPNetworkVar(ScriptVariable):
  183. """
  184. An IPv4 or IPv6 prefix.
  185. """
  186. form_field = IPNetworkFormField
  187. def __init__(self, min_prefix_length=None, max_prefix_length=None, *args, **kwargs):
  188. super().__init__(*args, **kwargs)
  189. # Set prefix validator and optional minimum/maximum prefix lengths
  190. self.field_attrs['validators'] = [prefix_validator]
  191. if min_prefix_length is not None:
  192. self.field_attrs['validators'].append(
  193. MinPrefixLengthValidator(min_prefix_length)
  194. )
  195. if max_prefix_length is not None:
  196. self.field_attrs['validators'].append(
  197. MaxPrefixLengthValidator(max_prefix_length)
  198. )
  199. #
  200. # Scripts
  201. #
  202. class BaseScript:
  203. """
  204. Base model for custom scripts. User classes should inherit from this model if they want to extend Script
  205. functionality for use in other subclasses.
  206. """
  207. # Prevent django from instantiating the class on all accesses
  208. do_not_call_in_templates = True
  209. class Meta:
  210. pass
  211. def __init__(self):
  212. # Initiate the log
  213. self.logger = logging.getLogger(f"netbox.scripts.{self.module()}.{self.__class__.__name__}")
  214. self.log = []
  215. # Declare the placeholder for the current request
  216. self.request = None
  217. # Grab some info about the script
  218. self.filename = inspect.getfile(self.__class__)
  219. self.source = inspect.getsource(self.__class__)
  220. def __str__(self):
  221. return self.name
  222. @classproperty
  223. def name(self):
  224. return getattr(self.Meta, 'name', self.__name__)
  225. @classproperty
  226. def full_name(self):
  227. return '.'.join([self.__module__, self.__name__])
  228. @classproperty
  229. def description(self):
  230. return getattr(self.Meta, 'description', '')
  231. @classmethod
  232. def module(cls):
  233. return cls.__module__
  234. @classproperty
  235. def job_timeout(self):
  236. return getattr(self.Meta, 'job_timeout', None)
  237. @classmethod
  238. def _get_vars(cls):
  239. vars = {}
  240. # Iterate all base classes looking for ScriptVariables
  241. for base_class in inspect.getmro(cls):
  242. # When object is reached there's no reason to continue
  243. if base_class is object:
  244. break
  245. for name, attr in base_class.__dict__.items():
  246. if name not in vars and issubclass(attr.__class__, ScriptVariable):
  247. vars[name] = attr
  248. # Order variables according to field_order
  249. field_order = getattr(cls.Meta, 'field_order', None)
  250. if not field_order:
  251. return vars
  252. ordered_vars = {
  253. field: vars.pop(field) for field in field_order if field in vars
  254. }
  255. ordered_vars.update(vars)
  256. return ordered_vars
  257. def run(self, data, commit):
  258. raise NotImplementedError("The script must define a run() method.")
  259. def as_form(self, data=None, files=None, initial=None):
  260. """
  261. Return a Django form suitable for populating the context data required to run this Script.
  262. """
  263. # Create a dynamic ScriptForm subclass from script variables
  264. fields = {
  265. name: var.as_field() for name, var in self._get_vars().items()
  266. }
  267. FormClass = type('ScriptForm', (ScriptForm,), fields)
  268. form = FormClass(data, files, initial=initial)
  269. # Set initial "commit" checkbox state based on the script's Meta parameter
  270. form.fields['_commit'].initial = getattr(self.Meta, 'commit_default', True)
  271. return form
  272. # Logging
  273. def log_debug(self, message):
  274. self.logger.log(logging.DEBUG, message)
  275. self.log.append((LogLevelChoices.LOG_DEFAULT, message))
  276. def log_success(self, message):
  277. self.logger.log(logging.INFO, message) # No syslog equivalent for SUCCESS
  278. self.log.append((LogLevelChoices.LOG_SUCCESS, message))
  279. def log_info(self, message):
  280. self.logger.log(logging.INFO, message)
  281. self.log.append((LogLevelChoices.LOG_INFO, message))
  282. def log_warning(self, message):
  283. self.logger.log(logging.WARNING, message)
  284. self.log.append((LogLevelChoices.LOG_WARNING, message))
  285. def log_failure(self, message):
  286. self.logger.log(logging.ERROR, message)
  287. self.log.append((LogLevelChoices.LOG_FAILURE, message))
  288. # Convenience functions
  289. def load_yaml(self, filename):
  290. """
  291. Return data from a YAML file
  292. """
  293. try:
  294. from yaml import CLoader as Loader
  295. except ImportError:
  296. from yaml import Loader
  297. file_path = os.path.join(settings.SCRIPTS_ROOT, filename)
  298. with open(file_path, 'r') as datafile:
  299. data = yaml.load(datafile, Loader=Loader)
  300. return data
  301. def load_json(self, filename):
  302. """
  303. Return data from a JSON file
  304. """
  305. file_path = os.path.join(settings.SCRIPTS_ROOT, filename)
  306. with open(file_path, 'r') as datafile:
  307. data = json.load(datafile)
  308. return data
  309. class Script(BaseScript):
  310. """
  311. Classes which inherit this model will appear in the list of available scripts.
  312. """
  313. pass
  314. #
  315. # Functions
  316. #
  317. def is_script(obj):
  318. """
  319. Returns True if the object is a Script.
  320. """
  321. try:
  322. return issubclass(obj, Script) and obj != Script
  323. except TypeError:
  324. return False
  325. def is_variable(obj):
  326. """
  327. Returns True if the object is a ScriptVariable.
  328. """
  329. return isinstance(obj, ScriptVariable)
  330. def run_script(data, request, commit=True, *args, **kwargs):
  331. """
  332. A wrapper for calling Script.run(). This performs error handling and provides a hook for committing changes. It
  333. exists outside of the Script class to ensure it cannot be overridden by a script author.
  334. """
  335. job_result = kwargs.pop('job_result')
  336. module, script_name = job_result.name.split('.', 1)
  337. script = get_script(module, script_name)()
  338. job_result.status = JobResultStatusChoices.STATUS_RUNNING
  339. job_result.save()
  340. logger = logging.getLogger(f"netbox.scripts.{module}.{script_name}")
  341. logger.info(f"Running script (commit={commit})")
  342. # Add files to form data
  343. files = request.FILES
  344. for field_name, fileobj in files.items():
  345. data[field_name] = fileobj
  346. # Add the current request as a property of the script
  347. script.request = request
  348. def _run_script():
  349. """
  350. Core script execution task. We capture this within a subfunction to allow for conditionally wrapping it with
  351. the change_logging context manager (which is bypassed if commit == False).
  352. """
  353. try:
  354. with transaction.atomic():
  355. script.output = script.run(data=data, commit=commit)
  356. job_result.set_status(JobResultStatusChoices.STATUS_COMPLETED)
  357. if not commit:
  358. raise AbortTransaction()
  359. except AbortTransaction:
  360. script.log_info("Database changes have been reverted automatically.")
  361. except Exception as e:
  362. stacktrace = traceback.format_exc()
  363. script.log_failure(
  364. f"An exception occurred: `{type(e).__name__}: {e}`\n```\n{stacktrace}\n```"
  365. )
  366. script.log_info("Database changes have been reverted due to error.")
  367. logger.error(f"Exception raised during script execution: {e}")
  368. job_result.set_status(JobResultStatusChoices.STATUS_ERRORED)
  369. finally:
  370. job_result.data = ScriptOutputSerializer(script).data
  371. job_result.save()
  372. logger.info(f"Script completed in {job_result.duration}")
  373. # Execute the script. If commit is True, wrap it with the change_logging context manager to ensure we process
  374. # change logging, webhooks, etc.
  375. if commit:
  376. with change_logging(request):
  377. _run_script()
  378. else:
  379. _run_script()
  380. def get_scripts(use_names=False):
  381. """
  382. Return a dict of dicts mapping all scripts to their modules. Set use_names to True to use each module's human-
  383. defined name in place of the actual module name.
  384. """
  385. scripts = OrderedDict()
  386. # Iterate through all modules within the scripts path. These are the user-created files in which reports are
  387. # defined.
  388. for importer, module_name, _ in pkgutil.iter_modules([settings.SCRIPTS_ROOT]):
  389. # Use a lock as removing and loading modules is not thread safe
  390. with lock:
  391. # Remove cached module to ensure consistency with filesystem
  392. if module_name in sys.modules:
  393. del sys.modules[module_name]
  394. module = importer.find_module(module_name).load_module(module_name)
  395. if use_names and hasattr(module, 'name'):
  396. module_name = module.name
  397. module_scripts = OrderedDict()
  398. script_order = getattr(module, "script_order", ())
  399. ordered_scripts = [cls for cls in script_order if is_script(cls)]
  400. unordered_scripts = [cls for _, cls in inspect.getmembers(module, is_script) if cls not in script_order]
  401. for cls in [*ordered_scripts, *unordered_scripts]:
  402. module_scripts[cls.__name__] = cls
  403. if module_scripts:
  404. scripts[module_name] = module_scripts
  405. return scripts
  406. def get_script(module_name, script_name):
  407. """
  408. Retrieve a script class by module and name. Returns None if the script does not exist.
  409. """
  410. scripts = get_scripts()
  411. module = scripts.get(module_name)
  412. if module:
  413. return module.get(script_name)