scripts.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. import inspect
  2. import json
  3. import os
  4. import pkgutil
  5. import time
  6. import traceback
  7. from collections import OrderedDict
  8. import yaml
  9. from django import forms
  10. from django.conf import settings
  11. from django.core.validators import RegexValidator
  12. from django.db import transaction
  13. from mptt.forms import TreeNodeChoiceField, TreeNodeMultipleChoiceField
  14. from mptt.models import MPTTModel
  15. from ipam.formfields import IPAddressFormField, IPNetworkFormField
  16. from ipam.validators import MaxPrefixLengthValidator, MinPrefixLengthValidator, prefix_validator
  17. from .constants import LOG_DEFAULT, LOG_FAILURE, LOG_INFO, LOG_SUCCESS, LOG_WARNING
  18. from utilities.exceptions import AbortTransaction
  19. from .forms import ScriptForm
  20. from .signals import purge_changelog
  21. __all__ = [
  22. 'BaseScript',
  23. 'BooleanVar',
  24. 'ChoiceVar',
  25. 'FileVar',
  26. 'IntegerVar',
  27. 'IPAddressVar',
  28. 'IPAddressWithMaskVar',
  29. 'IPNetworkVar',
  30. 'MultiObjectVar',
  31. 'ObjectVar',
  32. 'Script',
  33. 'StringVar',
  34. 'TextVar',
  35. ]
  36. #
  37. # Script variables
  38. #
  39. class ScriptVariable:
  40. """
  41. Base model for script variables
  42. """
  43. form_field = forms.CharField
  44. def __init__(self, label='', description='', default=None, required=True, widget=None):
  45. # Initialize field attributes
  46. if not hasattr(self, 'field_attrs'):
  47. self.field_attrs = {}
  48. if label:
  49. self.field_attrs['label'] = label
  50. if description:
  51. self.field_attrs['help_text'] = description
  52. if default:
  53. self.field_attrs['initial'] = default
  54. if widget:
  55. self.field_attrs['widget'] = widget
  56. self.field_attrs['required'] = required
  57. def as_field(self):
  58. """
  59. Render the variable as a Django form field.
  60. """
  61. form_field = self.form_field(**self.field_attrs)
  62. if not isinstance(form_field.widget, forms.CheckboxInput):
  63. if form_field.widget.attrs and 'class' in form_field.widget.attrs.keys():
  64. form_field.widget.attrs['class'] += ' form-control'
  65. else:
  66. form_field.widget.attrs['class'] = 'form-control'
  67. return form_field
  68. class StringVar(ScriptVariable):
  69. """
  70. Character string representation. Can enforce minimum/maximum length and/or regex validation.
  71. """
  72. def __init__(self, min_length=None, max_length=None, regex=None, *args, **kwargs):
  73. super().__init__(*args, **kwargs)
  74. # Optional minimum/maximum lengths
  75. if min_length:
  76. self.field_attrs['min_length'] = min_length
  77. if max_length:
  78. self.field_attrs['max_length'] = max_length
  79. # Optional regular expression validation
  80. if regex:
  81. self.field_attrs['validators'] = [
  82. RegexValidator(
  83. regex=regex,
  84. message='Invalid value. Must match regex: {}'.format(regex),
  85. code='invalid'
  86. )
  87. ]
  88. class TextVar(ScriptVariable):
  89. """
  90. Free-form text data. Renders as a <textarea>.
  91. """
  92. form_field = forms.CharField
  93. def __init__(self, *args, **kwargs):
  94. super().__init__(*args, **kwargs)
  95. self.field_attrs['widget'] = forms.Textarea
  96. class IntegerVar(ScriptVariable):
  97. """
  98. Integer representation. Can enforce minimum/maximum values.
  99. """
  100. form_field = forms.IntegerField
  101. def __init__(self, min_value=None, max_value=None, *args, **kwargs):
  102. super().__init__(*args, **kwargs)
  103. # Optional minimum/maximum values
  104. if min_value:
  105. self.field_attrs['min_value'] = min_value
  106. if max_value:
  107. self.field_attrs['max_value'] = max_value
  108. class BooleanVar(ScriptVariable):
  109. """
  110. Boolean representation (true/false). Renders as a checkbox.
  111. """
  112. form_field = forms.BooleanField
  113. def __init__(self, *args, **kwargs):
  114. super().__init__(*args, **kwargs)
  115. # Boolean fields cannot be required
  116. self.field_attrs['required'] = False
  117. class ChoiceVar(ScriptVariable):
  118. """
  119. Select one of several predefined static choices, passed as a list of two-tuples. Example:
  120. color = ChoiceVar(
  121. choices=(
  122. ('#ff0000', 'Red'),
  123. ('#00ff00', 'Green'),
  124. ('#0000ff', 'Blue')
  125. )
  126. )
  127. """
  128. form_field = forms.ChoiceField
  129. def __init__(self, choices, *args, **kwargs):
  130. super().__init__(*args, **kwargs)
  131. # Set field choices
  132. self.field_attrs['choices'] = choices
  133. class ObjectVar(ScriptVariable):
  134. """
  135. NetBox object representation. The provided QuerySet will determine the choices available.
  136. """
  137. form_field = forms.ModelChoiceField
  138. def __init__(self, queryset, *args, **kwargs):
  139. super().__init__(*args, **kwargs)
  140. # Queryset for field choices
  141. self.field_attrs['queryset'] = queryset
  142. # Update form field for MPTT (nested) objects
  143. if issubclass(queryset.model, MPTTModel):
  144. self.form_field = TreeNodeChoiceField
  145. class MultiObjectVar(ScriptVariable):
  146. """
  147. Like ObjectVar, but can represent one or more objects.
  148. """
  149. form_field = forms.ModelMultipleChoiceField
  150. def __init__(self, queryset, *args, **kwargs):
  151. super().__init__(*args, **kwargs)
  152. # Queryset for field choices
  153. self.field_attrs['queryset'] = queryset
  154. # Update form field for MPTT (nested) objects
  155. if issubclass(queryset.model, MPTTModel):
  156. self.form_field = TreeNodeMultipleChoiceField
  157. class FileVar(ScriptVariable):
  158. """
  159. An uploaded file.
  160. """
  161. form_field = forms.FileField
  162. class IPAddressVar(ScriptVariable):
  163. """
  164. An IPv4 or IPv6 address without a mask.
  165. """
  166. form_field = IPAddressFormField
  167. class IPAddressWithMaskVar(ScriptVariable):
  168. """
  169. An IPv4 or IPv6 address with a mask.
  170. """
  171. form_field = IPNetworkFormField
  172. class IPNetworkVar(ScriptVariable):
  173. """
  174. An IPv4 or IPv6 prefix.
  175. """
  176. form_field = IPNetworkFormField
  177. def __init__(self, min_prefix_length=None, max_prefix_length=None, *args, **kwargs):
  178. super().__init__(*args, **kwargs)
  179. # Set prefix validator and optional minimum/maximum prefix lengths
  180. self.field_attrs['validators'] = [prefix_validator]
  181. if min_prefix_length is not None:
  182. self.field_attrs['validators'].append(
  183. MinPrefixLengthValidator(min_prefix_length)
  184. )
  185. if max_prefix_length is not None:
  186. self.field_attrs['validators'].append(
  187. MaxPrefixLengthValidator(max_prefix_length)
  188. )
  189. #
  190. # Scripts
  191. #
  192. class BaseScript:
  193. """
  194. Base model for custom scripts. User classes should inherit from this model if they want to extend Script
  195. functionality for use in other subclasses.
  196. """
  197. class Meta:
  198. pass
  199. def __init__(self):
  200. # Initiate the log
  201. self.log = []
  202. # Declare the placeholder for the current request
  203. self.request = None
  204. # Grab some info about the script
  205. self.filename = inspect.getfile(self.__class__)
  206. self.source = inspect.getsource(self.__class__)
  207. def __str__(self):
  208. return getattr(self.Meta, 'name', self.__class__.__name__)
  209. @classmethod
  210. def module(cls):
  211. return cls.__module__
  212. @classmethod
  213. def _get_vars(cls):
  214. vars = OrderedDict()
  215. # Infer order from Meta.field_order (Python 3.5 and lower)
  216. field_order = getattr(cls.Meta, 'field_order', [])
  217. for name in field_order:
  218. vars[name] = getattr(cls, name)
  219. # Default to order of declaration on class
  220. for name, attr in cls.__dict__.items():
  221. if name not in vars and issubclass(attr.__class__, ScriptVariable):
  222. vars[name] = attr
  223. return vars
  224. def run(self, data):
  225. raise NotImplementedError("The script must define a run() method.")
  226. def as_form(self, data=None, files=None, initial=None):
  227. """
  228. Return a Django form suitable for populating the context data required to run this Script.
  229. """
  230. vars = self._get_vars()
  231. form = ScriptForm(vars, data, files, initial=initial, commit_default=getattr(self.Meta, 'commit_default', True))
  232. return form
  233. # Logging
  234. def log_debug(self, message):
  235. self.log.append((LOG_DEFAULT, message))
  236. def log_success(self, message):
  237. self.log.append((LOG_SUCCESS, message))
  238. def log_info(self, message):
  239. self.log.append((LOG_INFO, message))
  240. def log_warning(self, message):
  241. self.log.append((LOG_WARNING, message))
  242. def log_failure(self, message):
  243. self.log.append((LOG_FAILURE, message))
  244. # Convenience functions
  245. def load_yaml(self, filename):
  246. """
  247. Return data from a YAML file
  248. """
  249. file_path = os.path.join(settings.SCRIPTS_ROOT, filename)
  250. with open(file_path, 'r') as datafile:
  251. data = yaml.load(datafile)
  252. return data
  253. def load_json(self, filename):
  254. """
  255. Return data from a JSON file
  256. """
  257. file_path = os.path.join(settings.SCRIPTS_ROOT, filename)
  258. with open(file_path, 'r') as datafile:
  259. data = json.load(datafile)
  260. return data
  261. class Script(BaseScript):
  262. """
  263. Classes which inherit this model will appear in the list of available scripts.
  264. """
  265. pass
  266. #
  267. # Functions
  268. #
  269. def is_script(obj):
  270. """
  271. Returns True if the object is a Script.
  272. """
  273. try:
  274. return issubclass(obj, Script) and obj != Script
  275. except TypeError:
  276. return False
  277. def is_variable(obj):
  278. """
  279. Returns True if the object is a ScriptVariable.
  280. """
  281. return isinstance(obj, ScriptVariable)
  282. def run_script(script, data, request, commit=True):
  283. """
  284. A wrapper for calling Script.run(). This performs error handling and provides a hook for committing changes. It
  285. exists outside of the Script class to ensure it cannot be overridden by a script author.
  286. """
  287. output = None
  288. start_time = None
  289. end_time = None
  290. # Add files to form data
  291. files = request.FILES
  292. for field_name, fileobj in files.items():
  293. data[field_name] = fileobj
  294. # Add the current request as a property of the script
  295. script.request = request
  296. try:
  297. with transaction.atomic():
  298. start_time = time.time()
  299. output = script.run(data)
  300. end_time = time.time()
  301. if not commit:
  302. raise AbortTransaction()
  303. except AbortTransaction:
  304. pass
  305. except Exception as e:
  306. stacktrace = traceback.format_exc()
  307. script.log_failure(
  308. "An exception occurred: `{}: {}`\n```\n{}\n```".format(type(e).__name__, e, stacktrace)
  309. )
  310. commit = False
  311. finally:
  312. if not commit:
  313. # Delete all pending changelog entries
  314. purge_changelog.send(Script)
  315. script.log_info(
  316. "Database changes have been reverted automatically."
  317. )
  318. # Calculate execution time
  319. if end_time is not None:
  320. execution_time = end_time - start_time
  321. else:
  322. execution_time = None
  323. return output, execution_time
  324. def get_scripts(use_names=False):
  325. """
  326. Return a dict of dicts mapping all scripts to their modules. Set use_names to True to use each module's human-
  327. defined name in place of the actual module name.
  328. """
  329. scripts = OrderedDict()
  330. # Iterate through all modules within the reports path. These are the user-created files in which reports are
  331. # defined.
  332. for importer, module_name, _ in pkgutil.iter_modules([settings.SCRIPTS_ROOT]):
  333. module = importer.find_module(module_name).load_module(module_name)
  334. if use_names and hasattr(module, 'name'):
  335. module_name = module.name
  336. module_scripts = OrderedDict()
  337. for name, cls in inspect.getmembers(module, is_script):
  338. module_scripts[name] = cls
  339. scripts[module_name] = module_scripts
  340. return scripts
  341. def get_script(module_name, script_name):
  342. """
  343. Retrieve a script class by module and name. Returns None if the script does not exist.
  344. """
  345. scripts = get_scripts()
  346. module = scripts.get(module_name)
  347. if module:
  348. return module.get(script_name)