scripts.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import inspect
  2. import json
  3. import logging
  4. import os
  5. import pkgutil
  6. import sys
  7. import traceback
  8. from collections import OrderedDict
  9. import yaml
  10. from django import forms
  11. from django.conf import settings
  12. from django.core.validators import RegexValidator
  13. from django.db import transaction
  14. from django.utils.functional import classproperty
  15. from django_rq import job
  16. from extras.api.serializers import ScriptOutputSerializer
  17. from extras.choices import JobResultStatusChoices, LogLevelChoices
  18. from extras.models import JobResult
  19. from ipam.formfields import IPAddressFormField, IPNetworkFormField
  20. from ipam.validators import MaxPrefixLengthValidator, MinPrefixLengthValidator, prefix_validator
  21. from utilities.exceptions import AbortTransaction
  22. from utilities.forms import DynamicModelChoiceField, DynamicModelMultipleChoiceField
  23. from .context_managers import change_logging
  24. from .forms import ScriptForm
  25. __all__ = [
  26. 'BaseScript',
  27. 'BooleanVar',
  28. 'ChoiceVar',
  29. 'FileVar',
  30. 'IntegerVar',
  31. 'IPAddressVar',
  32. 'IPAddressWithMaskVar',
  33. 'IPNetworkVar',
  34. 'MultiChoiceVar',
  35. 'MultiObjectVar',
  36. 'ObjectVar',
  37. 'Script',
  38. 'StringVar',
  39. 'TextVar',
  40. ]
  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
  137. self.field_attrs['choices'] = choices
  138. class MultiChoiceVar(ChoiceVar):
  139. """
  140. Like ChoiceVar, but allows for the selection of multiple choices.
  141. """
  142. form_field = forms.MultipleChoiceField
  143. class ObjectVar(ScriptVariable):
  144. """
  145. A single object within NetBox.
  146. :param model: The NetBox model being referenced
  147. :param query_params: A dictionary of additional query parameters to attach when making REST API requests (optional)
  148. :param null_option: The label to use as a "null" selection option (optional)
  149. """
  150. form_field = DynamicModelChoiceField
  151. def __init__(self, model, query_params=None, null_option=None, *args, **kwargs):
  152. super().__init__(*args, **kwargs)
  153. self.field_attrs.update({
  154. 'queryset': model.objects.all(),
  155. 'query_params': query_params,
  156. 'null_option': null_option,
  157. })
  158. class MultiObjectVar(ObjectVar):
  159. """
  160. Like ObjectVar, but can represent one or more objects.
  161. """
  162. form_field = DynamicModelMultipleChoiceField
  163. class FileVar(ScriptVariable):
  164. """
  165. An uploaded file.
  166. """
  167. form_field = forms.FileField
  168. class IPAddressVar(ScriptVariable):
  169. """
  170. An IPv4 or IPv6 address without a mask.
  171. """
  172. form_field = IPAddressFormField
  173. class IPAddressWithMaskVar(ScriptVariable):
  174. """
  175. An IPv4 or IPv6 address with a mask.
  176. """
  177. form_field = IPNetworkFormField
  178. class IPNetworkVar(ScriptVariable):
  179. """
  180. An IPv4 or IPv6 prefix.
  181. """
  182. form_field = IPNetworkFormField
  183. def __init__(self, min_prefix_length=None, max_prefix_length=None, *args, **kwargs):
  184. super().__init__(*args, **kwargs)
  185. # Set prefix validator and optional minimum/maximum prefix lengths
  186. self.field_attrs['validators'] = [prefix_validator]
  187. if min_prefix_length is not None:
  188. self.field_attrs['validators'].append(
  189. MinPrefixLengthValidator(min_prefix_length)
  190. )
  191. if max_prefix_length is not None:
  192. self.field_attrs['validators'].append(
  193. MaxPrefixLengthValidator(max_prefix_length)
  194. )
  195. #
  196. # Scripts
  197. #
  198. class BaseScript:
  199. """
  200. Base model for custom scripts. User classes should inherit from this model if they want to extend Script
  201. functionality for use in other subclasses.
  202. """
  203. class Meta:
  204. pass
  205. def __init__(self):
  206. # Initiate the log
  207. self.logger = logging.getLogger(f"netbox.scripts.{self.module()}.{self.__class__.__name__}")
  208. self.log = []
  209. # Declare the placeholder for the current request
  210. self.request = None
  211. # Grab some info about the script
  212. self.filename = inspect.getfile(self.__class__)
  213. self.source = inspect.getsource(self.__class__)
  214. def __str__(self):
  215. return self.name
  216. @classproperty
  217. def name(self):
  218. return getattr(self.Meta, 'name', self.__class__.__name__)
  219. @classproperty
  220. def full_name(self):
  221. return '.'.join([self.__module__, self.__name__])
  222. @classproperty
  223. def description(self):
  224. return getattr(self.Meta, 'description', '')
  225. @classmethod
  226. def module(cls):
  227. return cls.__module__
  228. @classmethod
  229. def _get_vars(cls):
  230. vars = OrderedDict()
  231. for name, attr in cls.__dict__.items():
  232. if name not in vars and issubclass(attr.__class__, ScriptVariable):
  233. vars[name] = attr
  234. return vars
  235. def run(self, data, commit):
  236. raise NotImplementedError("The script must define a run() method.")
  237. def as_form(self, data=None, files=None, initial=None):
  238. """
  239. Return a Django form suitable for populating the context data required to run this Script.
  240. """
  241. # Create a dynamic ScriptForm subclass from script variables
  242. fields = {
  243. name: var.as_field() for name, var in self._get_vars().items()
  244. }
  245. FormClass = type('ScriptForm', (ScriptForm,), fields)
  246. form = FormClass(data, files, initial=initial)
  247. # Set initial "commit" checkbox state based on the script's Meta parameter
  248. form.fields['_commit'].initial = getattr(self.Meta, 'commit_default', True)
  249. return form
  250. # Logging
  251. def log_debug(self, message):
  252. self.logger.log(logging.DEBUG, message)
  253. self.log.append((LogLevelChoices.LOG_DEFAULT, message))
  254. def log_success(self, message):
  255. self.logger.log(logging.INFO, message) # No syslog equivalent for SUCCESS
  256. self.log.append((LogLevelChoices.LOG_SUCCESS, message))
  257. def log_info(self, message):
  258. self.logger.log(logging.INFO, message)
  259. self.log.append((LogLevelChoices.LOG_INFO, message))
  260. def log_warning(self, message):
  261. self.logger.log(logging.WARNING, message)
  262. self.log.append((LogLevelChoices.LOG_WARNING, message))
  263. def log_failure(self, message):
  264. self.logger.log(logging.ERROR, message)
  265. self.log.append((LogLevelChoices.LOG_FAILURE, message))
  266. # Convenience functions
  267. def load_yaml(self, filename):
  268. """
  269. Return data from a YAML file
  270. """
  271. try:
  272. from yaml import CLoader as Loader
  273. except ImportError:
  274. from yaml import Loader
  275. file_path = os.path.join(settings.SCRIPTS_ROOT, filename)
  276. with open(file_path, 'r') as datafile:
  277. data = yaml.load(datafile, Loader=Loader)
  278. return data
  279. def load_json(self, filename):
  280. """
  281. Return data from a JSON file
  282. """
  283. file_path = os.path.join(settings.SCRIPTS_ROOT, filename)
  284. with open(file_path, 'r') as datafile:
  285. data = json.load(datafile)
  286. return data
  287. class Script(BaseScript):
  288. """
  289. Classes which inherit this model will appear in the list of available scripts.
  290. """
  291. pass
  292. #
  293. # Functions
  294. #
  295. def is_script(obj):
  296. """
  297. Returns True if the object is a Script.
  298. """
  299. try:
  300. return issubclass(obj, Script) and obj != Script
  301. except TypeError:
  302. return False
  303. def is_variable(obj):
  304. """
  305. Returns True if the object is a ScriptVariable.
  306. """
  307. return isinstance(obj, ScriptVariable)
  308. @job('default')
  309. def run_script(data, request, commit=True, *args, **kwargs):
  310. """
  311. A wrapper for calling Script.run(). This performs error handling and provides a hook for committing changes. It
  312. exists outside of the Script class to ensure it cannot be overridden by a script author.
  313. """
  314. job_result = kwargs.pop('job_result')
  315. module, script_name = job_result.name.split('.', 1)
  316. script = get_script(module, script_name)()
  317. job_result.status = JobResultStatusChoices.STATUS_RUNNING
  318. job_result.save()
  319. logger = logging.getLogger(f"netbox.scripts.{module}.{script_name}")
  320. logger.info(f"Running script (commit={commit})")
  321. # Add files to form data
  322. files = request.FILES
  323. for field_name, fileobj in files.items():
  324. data[field_name] = fileobj
  325. # Add the current request as a property of the script
  326. script.request = request
  327. def _run_script():
  328. """
  329. Core script execution task. We capture this within a subfunction to allow for conditionally wrapping it with
  330. the change_logging context manager (which is bypassed if commit == False).
  331. """
  332. try:
  333. with transaction.atomic():
  334. script.output = script.run(data=data, commit=commit)
  335. job_result.set_status(JobResultStatusChoices.STATUS_COMPLETED)
  336. if not commit:
  337. raise AbortTransaction()
  338. except AbortTransaction:
  339. script.log_info("Database changes have been reverted automatically.")
  340. except Exception as e:
  341. stacktrace = traceback.format_exc()
  342. script.log_failure(
  343. f"An exception occurred: `{type(e).__name__}: {e}`\n```\n{stacktrace}\n```"
  344. )
  345. script.log_info("Database changes have been reverted due to error.")
  346. logger.error(f"Exception raised during script execution: {e}")
  347. job_result.set_status(JobResultStatusChoices.STATUS_ERRORED)
  348. finally:
  349. job_result.data = ScriptOutputSerializer(script).data
  350. job_result.save()
  351. logger.info(f"Script completed in {job_result.duration}")
  352. # Execute the script. If commit is True, wrap it with the change_logging context manager to ensure we process
  353. # change logging, webhooks, etc.
  354. if commit:
  355. with change_logging(request):
  356. _run_script()
  357. else:
  358. _run_script()
  359. # Delete any previous terminal state results
  360. JobResult.objects.filter(
  361. obj_type=job_result.obj_type,
  362. name=job_result.name,
  363. status__in=JobResultStatusChoices.TERMINAL_STATE_CHOICES
  364. ).exclude(
  365. pk=job_result.pk
  366. ).delete()
  367. def get_scripts(use_names=False):
  368. """
  369. Return a dict of dicts mapping all scripts to their modules. Set use_names to True to use each module's human-
  370. defined name in place of the actual module name.
  371. """
  372. scripts = OrderedDict()
  373. # Iterate through all modules within the reports path. These are the user-created files in which reports are
  374. # defined.
  375. for importer, module_name, _ in pkgutil.iter_modules([settings.SCRIPTS_ROOT]):
  376. # Remove cached module to ensure consistency with filesystem
  377. if module_name in sys.modules:
  378. del sys.modules[module_name]
  379. module = importer.find_module(module_name).load_module(module_name)
  380. if use_names and hasattr(module, 'name'):
  381. module_name = module.name
  382. module_scripts = OrderedDict()
  383. script_order = getattr(module, "script_order", ())
  384. ordered_scripts = [cls for cls in script_order if is_script(cls)]
  385. unordered_scripts = [cls for _, cls in inspect.getmembers(module, is_script) if cls not in script_order]
  386. for cls in [*ordered_scripts, *unordered_scripts]:
  387. module_scripts[cls.__name__] = cls
  388. if module_scripts:
  389. scripts[module_name] = module_scripts
  390. return scripts
  391. def get_script(module_name, script_name):
  392. """
  393. Retrieve a script class by module and name. Returns None if the script does not exist.
  394. """
  395. scripts = get_scripts()
  396. module = scripts.get(module_name)
  397. if module:
  398. return module.get(script_name)