1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
import inspect
from importlib import import_module
from os import listdir
from os.path import dirname, join, splitext
from django.conf import settings
from graphite.functions.params import Param, ParamTypes, ParamTypeAggFunc # noqa
from graphite.functions.aggfuncs import getAggFunc # noqa
from graphite.logger import log
customDir = join(dirname(__file__), 'custom')
customModPrefix = 'graphite.functions.custom.'
_SeriesFunctions = {}
_PieFunctions = {}
def loadFunctions(force=False):
if _SeriesFunctions and not force:
return
from graphite.render import functions
_SeriesFunctions.clear()
_SeriesFunctions.update(functions.SeriesFunctions)
_PieFunctions.clear()
_PieFunctions.update(functions.PieFunctions)
custom_modules = []
for filename in listdir(customDir):
module_name, extension = splitext(filename)
if extension != '.py' or module_name == '__init__':
continue
custom_modules.append(customModPrefix + module_name)
for module_name in custom_modules + settings.FUNCTION_PLUGINS:
try:
module = import_module(module_name)
except Exception as e:
log.warning('Error loading function plugin %s: %s' % (module_name, e))
continue
for func_name, func in getattr(module, 'SeriesFunctions', {}).items():
try:
addFunction(_SeriesFunctions, func, func_name)
except Exception as e:
log.warning('Error loading function plugin %s: %s' % (module_name, e))
for func_name, func in getattr(module, 'PieFunctions', {}).items():
try:
addFunction(_PieFunctions, func, func_name)
except Exception as e:
log.warning('Error loading function plugin %s: %s' % (module_name, e))
def addFunction(dest, func, func_name):
if not hasattr(func, 'group'):
func.group = 'Ungrouped'
if not hasattr(func, 'params'):
raise Exception('No params defined for %s' % func_name)
for param in func.params:
if not isinstance(param, Param):
raise Exception('Invalid param specified for %s' % func_name)
dest[func_name] = func
def SeriesFunctions():
loadFunctions()
return _SeriesFunctions
def SeriesFunction(name):
loadFunctions()
try:
return _SeriesFunctions[name]
except KeyError:
raise KeyError('Function "%s" not found' % name)
def PieFunctions():
loadFunctions()
return _PieFunctions
def PieFunction(name):
loadFunctions()
try:
return _PieFunctions[name]
except KeyError:
raise KeyError('Function "%s" not found' % name)
def functionInfo(name, func):
sig = inspect.signature(func)
argspec = '({})'.format(', '.join(list(map(str,
sig.parameters.values()))[1:]))
return {
'name': name,
'function': name + argspec,
'description': inspect.getdoc(func),
'module': inspect.getmodule(func).__name__,
'group': getattr(func, 'group', 'Ungrouped'),
'params': getattr(func, 'params', None),
}
|