id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
300
20c/pluginmgr
src/pluginmgr/config.py
pluginmgr.config.ConfigPluginManager
class ConfigPluginManager(pluginmgr.PluginManager): """ Plugin manager class that also handles config objects """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._instance = {} def _ctor(self, typ, config, *args, **kwargs): self.log.debug( f"ctor: self._instance={self._instance} self._class={self._class}" ) if typ in self._instance: # get class type, copy config, override with passed config obj = self._instance[typ] cp = obj.pluginmgr_config.copy() munge.util.recursive_update(cp, config) return type(obj)(cp, *args, **kwargs) # try to load return self.get_plugin_class(typ)(config, *args, **kwargs) def new_plugin(self, config, *args, **kwargs): """ instantiate a plugin creates the object, stores it in _instance """ typ = None obj = None # if type is defined, create a new instance if "type" in config: typ = config["type"] # single key is overriding an existing plugin instance elif isinstance(config, collections.abc.Mapping) and len(config) == 1: # get type name and shift out config to parent level (typ, config) = list(config.items())[0] obj = self._ctor(typ, config, *args, **kwargs) # store if named if "name" in config: self._instance[config["name"]] = obj else: # this could dupe on .name, make name=''? config["name"] = typ return obj def get_instance(self, node, *args, **kwargs): """ get plugin instance from config node *NOTE* returns an uninitialized instance if one isn't there *NOTE* instantiated plugins without names remain anonymous FIXME - why would instantiate() even process them """ # string is a ref to an existing plugin instance if isinstance(node, str): if node in self._instance: return self._instance[node] # if not an instance, try for init with empty config return self.new_plugin({"type": node}, *args, **kwargs) if isinstance(node, collections.abc.Mapping): if "type" in node: # node was a plugin config passed directly name = node.get("name", node.get("type")) elif len(node) == 1: # node was a container with a single plugin config keyed # to it typ, config = list(node.items())[0] name = config.get("name", config.get("type", typ)) # retrieve existing instance if it exists if name in self._instance: return self._instance[name] # otherwise spawn new plugin return self.new_plugin(node, *args, **kwargs) raise ValueError(f"unable to parse plugin for output {node}") def instantiate(self, config, *args, **kwargs): """ takes plugin config (list under 'plugin') and instantiates defined plugins """ for plugin_config in config: self.new_plugin(plugin_config, *args, **kwargs)
class ConfigPluginManager(pluginmgr.PluginManager): ''' Plugin manager class that also handles config objects ''' def __init__(self, *args, **kwargs): pass def _ctor(self, typ, config, *args, **kwargs): pass def new_plugin(self, config, *args, **kwargs): ''' instantiate a plugin creates the object, stores it in _instance ''' pass def get_instance(self, node, *args, **kwargs): ''' get plugin instance from config node *NOTE* returns an uninitialized instance if one isn't there *NOTE* instantiated plugins without names remain anonymous FIXME - why would instantiate() even process them ''' pass def instantiate(self, config, *args, **kwargs): ''' takes plugin config (list under 'plugin') and instantiates defined plugins ''' pass
6
4
16
2
9
6
3
0.69
1
6
0
0
5
1
5
12
90
14
45
14
39
31
40
14
34
7
1
2
16
301
20c/pluginmgr
src/pluginmgr/__init__.py
pluginmgr.SearchPathImporter
class SearchPathImporter(importlib.abc.MetaPathFinder, importlib.abc.Loader): """ import hook to dynamically load modules from a search path """ def __init__(self, namespace, searchpath, create_loader): self._searchpath = [] self.package = namespace.split(".")[0] self.namespace = namespace self.log = logging.getLogger(__name__) self.re_ns = re.compile(rf"^{re.escape(self.namespace)}\.(.*)$") self.log.debug(f"hook.compile({self.namespace})") self.searchpath = searchpath self.create_loader = create_loader def install(self): sys.meta_path.append(self) @property def searchpath(self): return getattr(self, "_searchpath") @searchpath.setter def searchpath(self, value): if not value: self._searchpath = [] elif isinstance(value, str): self._searchpath = [value] else: self._searchpath = [x for x in value if x] # import hooks def find_module(self, fullname, path=None): self.log.debug(f"hook.namespace {self.namespace}") self.log.debug(f"hook.find({fullname}, {path}) loader={self.create_loader}") if self.create_loader: # trying to import package level creates an infinite loop if fullname == self.package: return self if fullname == self.namespace: return self match = self.re_ns.match(fullname) self.log.debug(f"match {match}") if not match: return name = match.group(1) self.log.debug(f"hook match {name}") if self.find_file(name): return self def find_spec(self, fullname, path=None, target=None): self.log.debug(f"hook.find_spec({self}, {fullname}, {path}, {target})") if self.create_loader: if fullname == self.package or fullname == self.namespace: return importlib.machinery.ModuleSpec(fullname, self) match = self.re_ns.match(fullname) if match: if fq_path := self.find_file(match.group(1)): return importlib.machinery.ModuleSpec(fullname, self, origin=fq_path) return None def find_file(self, name): for each in self.searchpath: fq_path = os.path.join(each, name + ".py") self.log.debug(f"checking {fq_path}") if os.path.isfile(fq_path): return fq_path def load_module(self, fullname): self.log.debug(f"hook.load({fullname})") # For backward compatibility, delegate to exec_module. module = types.ModuleType(fullname) return self.exec_module(module) def exec_module(self, module): fullname = module.__name__ self.log.debug(f"hook.load({module}) {fullname}") # build package for loader if it doesn't exist # don't need to check for create_loader here, checks in find_module if fullname == self.package or fullname == self.namespace: self.log.debug(f"hook.create_loader({fullname})") # make a new loader module # spec = importlib.util.spec_from_loader(fullname, loader=self) # mod = importlib.util.module_from_spec(spec) mod = types.ModuleType(fullname) # set a few properties required by PEP 302 mod.__file__ = self.namespace mod.__name__ = fullname # this is the only one needed for py3.11 mod.__path__ = self.searchpath mod.__loader__ = self mod.__package__ = ".".join(fullname.split(".")[:-1]) sys.modules[fullname] = mod return mod match = self.re_ns.match(fullname) self.log.debug(f"match {match}") if not match: raise ImportError(fullname) name = match.group(1) filename = self.find_file(name) if not filename: raise ImportError(fullname) self.log.debug(f"hook.found({filename})") try: loader = importlib.machinery.SourceFileLoader(fullname, filename) mod = loader.load_module() except Exception as exc: self.log.error( "failed loading %s, %s(%s)", name, exc.__class__.__name__, str(exc) ) raise # don't need to check mod, both throw instead of returning None self.log.debug(f"hook.loaded({fullname}) - {mod}") sys.modules[fullname] = mod return mod
class SearchPathImporter(importlib.abc.MetaPathFinder, importlib.abc.Loader): ''' import hook to dynamically load modules from a search path ''' def __init__(self, namespace, searchpath, create_loader): pass def install(self): pass @property def searchpath(self): pass @searchpath.setter def searchpath(self): pass def find_module(self, fullname, path=None): pass def find_spec(self, fullname, path=None, target=None): pass def find_file(self, name): pass def load_module(self, fullname): pass def exec_module(self, module): pass
12
1
12
1
10
1
3
0.15
2
3
0
0
9
6
9
9
129
23
92
32
80
14
86
28
76
6
1
2
26
302
20c/pluginmgr
tests/data/dynload/mod0.py
mod0.Mod0
class Mod0(object): pass
class Mod0(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
303
20c/pluginmgr
src/pluginmgr/__init__.py
pluginmgr.PluginManager
class PluginManager: def __init__(self, namespace, searchpath=None, create_loader=False): """ namespace: import from (what you would type after `import`) searchpath: a directory or list of directories to search in create_loader: determines if this should create a blank loader to import through. This should be enabled if there isn't a real module path for the namespace and disabled for sharing the namespace with static modules """ self._class = {} self._imphook = None self.log = logging.getLogger(__name__) self.namespace = namespace self.create_loader = create_loader self.searchpath = searchpath @property def searchpath(self): if self._imphook: return self._imphook.searchpath return None @searchpath.setter def searchpath(self, value): if self._imphook: self._imphook.searchpath = value return if not value: return self._imphook = SearchPathImporter(self.namespace, value, self.create_loader) self._imphook.install() def import_external(self, namespace=None): if not namespace: namespace = self.namespace for entry_point in importlib_metadata.entry_points(group=namespace): module = entry_point.load() self.searchpath = (self.searchpath or []) + [ os.path.dirname(module.__file__) ] # need to mark new searchpath as already imported # to avoid re-import from new namespace sys.modules[f"{namespace}{entry_point.name}"] = sys.modules[ entry_point.module_name ] def register(self, typ): """register a plugin""" # should be able to combine class/instance namespace, and inherit from either # would need to store meta or rely on copy ctor def _func(cls): if typ in self._class: raise ValueError(f"duplicated type name '{str(typ)}'") cls.plugin_type = typ self._class[typ] = cls return cls return _func @property def registry(self): """ class dictionary of name: class """ return self._class.copy() def get_plugin_class(self, typ): """ get class by name """ if typ in self._class: return self._class[typ] # try to import by same name try: importlib.import_module(f"{self.namespace}.{typ}") if typ in self._class: return self._class[typ] except ImportError as exc: self.log.debug(f"ImportError {exc}") raise ValueError(f"unknown plugin '{typ}'")
class PluginManager: def __init__(self, namespace, searchpath=None, create_loader=False): ''' namespace: import from (what you would type after `import`) searchpath: a directory or list of directories to search in create_loader: determines if this should create a blank loader to import through. This should be enabled if there isn't a real module path for the namespace and disabled for sharing the namespace with static modules ''' pass @property def searchpath(self): pass @searchpath.setter def searchpath(self): pass def import_external(self, namespace=None): pass def register(self, typ): '''register a plugin''' pass def _func(cls): pass @property def registry(self): ''' class dictionary of name: class ''' pass def get_plugin_class(self, typ): ''' get class by name ''' pass
12
4
10
1
7
3
2
0.37
0
4
1
1
7
5
7
7
87
13
54
20
42
20
47
16
38
4
0
2
17
304
20c/pluginmgr
src/pluginmgr/config.py
pluginmgr.config.PluginBase
class PluginBase: """ Example base class for plugins, set config and call init() """ def __init__(self, config): # XXX document - pluginmgr_config is required self.pluginmgr_config = config self.init() def init(self): """ called after the plugin is initialized, plugin may define this for any other initialization code """ pass
class PluginBase: ''' Example base class for plugins, set config and call init() ''' def __init__(self, config): pass def init(self): ''' called after the plugin is initialized, plugin may define this for any other initialization code ''' pass
3
2
5
0
3
3
1
1.33
0
0
0
4
2
1
2
2
16
2
6
4
3
8
6
4
3
1
0
0
2
305
20c/pluginmgr
tests/pluginmgr_test/plugins/static0.py
pluginmgr_test.plugins.static0.PluginBase
class PluginBase(pluginmgr.config.PluginBase): def __init__(self, config, *args, **kwargs): super().__init__(config) self.args = args self.kwargs = kwargs
class PluginBase(pluginmgr.config.PluginBase): def __init__(self, config, *args, **kwargs): pass
2
0
4
0
4
0
1
0
1
1
0
1
1
2
1
3
5
0
5
4
3
0
5
4
3
1
1
0
1
306
20c/pluginmgr
tests/pluginmgr_test/plugins/static0.py
pluginmgr_test.plugins.static0.Static0
class Static0(PluginBase): pass
class Static0(PluginBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
3
2
0
2
1
1
0
2
1
1
0
2
0
0
307
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.EmitBase
class EmitBase(PluginBase): pass
class EmitBase(PluginBase): pass
1
0
0
0
0
0
0
0
1
0
0
2
0
0
0
2
2
0
2
1
1
0
2
1
1
0
1
0
0
308
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.EmitPlugin0
class EmitPlugin0(EmitBase): def emit(self, msg): pass
class EmitPlugin0(EmitBase): def emit(self, msg): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
3
0
3
2
1
0
3
2
1
1
2
0
1
309
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.EmitPluginABC
class EmitPluginABC(EmitBase): # emit not defined to test TypeError pass
class EmitPluginABC(EmitBase): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
2
3
0
2
1
1
1
2
1
1
0
2
0
0
310
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.Plugin0
class Plugin0(PluginBase): pass
class Plugin0(PluginBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
2
2
0
2
1
1
0
2
1
1
0
1
0
0
311
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.ProbeBase
class ProbeBase(PluginBase): pass
class ProbeBase(PluginBase): pass
1
0
0
0
0
0
0
0
1
0
0
2
0
0
0
2
2
0
2
1
1
0
2
1
1
0
1
0
0
312
20c/pluginmgr
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20c_pluginmgr/tests/test_plugin.py
test_plugin.test_plugin_registry.p0
class p0: pass
class p0: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
313
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.ProbePlugin1
class ProbePlugin1(ProbeBase): def probe(self): return []
class ProbePlugin1(ProbeBase): def probe(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
3
0
3
2
1
0
3
2
1
1
2
0
1
314
20c/pluginmgr
tests/test_config_plugin.py
test_config_plugin.TimedPlugin0
class TimedPlugin0(ProbeBase): pass
class TimedPlugin0(ProbeBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
2
2
0
2
1
1
0
2
1
1
0
2
0
0
315
20c/pluginmgr
tests/test_plugin.py
test_plugin.EmitBase
class EmitBase: pass
class EmitBase: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
316
20c/pluginmgr
tests/test_plugin.py
test_plugin.Plugin0
class Plugin0: pass
class Plugin0: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
317
20c/pluginmgr
tests/test_plugin.py
test_plugin.ProbeBase
class ProbeBase: pass
class ProbeBase: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
318
20c/tmpl
src/tmpl/context.py
tmpl.context.RenderError
class RenderError(Exception): pass
class RenderError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
319
20c/tmpl
src/tmpl/context.py
tmpl.context.Template
class Template: def __init__(self, **kwargs): pass # self.src = file, string, obj # self.ctx = Context def render_string(self): pass def render_file(self): pass
class Template: def __init__(self, **kwargs): pass def render_string(self): pass def render_file(self): pass
4
0
2
0
2
0
1
0.29
0
0
0
2
3
0
3
3
12
3
7
4
3
2
7
4
3
1
0
0
3
320
20c/tmpl
src/tmpl/engine.py
tmpl.engine.DjangoEngine
class DjangoEngine(context.Context): """template interface class for Django""" @staticmethod def can_load(): import imp try: imp.find_module("django") import django # noqa return True except ImportError: print("import error") return False def __init__(self, **kwargs): import django import django.template from django.conf import settings from django.template import Template if not settings.configured: settings.configure( TEMPLATES=[ {"BACKEND": "django.template.backends.django.DjangoTemplates"} ] ) django.setup() self.tmpl_ctor = Template super().__init__(**kwargs) def get_template(self, name): filename = self.find_template(name) if not filename: raise LookupError("template not found") return self.make_template(open(filename).read()) def make_template(self, tmpl_str): """makes template object from a string""" return DjangoTemplate(self.tmpl_ctor(tmpl_str)) def _render_str_to_str(self, instr, env): """ renders contents of instr with env returns string """ return self.make_template(instr).render(env)
class DjangoEngine(context.Context): '''template interface class for Django''' @staticmethod def can_load(): pass def __init__(self, **kwargs): pass def get_template(self, name): pass def make_template(self, tmpl_str): '''makes template object from a string''' pass def _render_str_to_str(self, instr, env): ''' renders contents of instr with env returns string ''' pass
7
3
8
1
6
1
2
0.18
1
4
1
0
4
1
5
18
51
12
34
15
21
6
29
14
17
2
1
1
8
321
20c/tmpl
src/tmpl/engine.py
tmpl.engine.DjangoTemplate
class DjangoTemplate(context.Template): def __init__(self, tmpl, **kwargs): self.tmpl = tmpl super().__init__(**kwargs) def render(self, env): """ renders from template, return object """ from django.template import Context return self.tmpl.render(Context(env)) def load(self): pass def loads(self): pass
class DjangoTemplate(context.Template): def __init__(self, tmpl, **kwargs): pass def render(self, env): ''' renders from template, return object ''' pass def load(self): pass def loads(self): pass
5
1
4
0
3
1
1
0.27
1
1
0
0
4
1
4
7
18
4
11
7
5
3
11
7
5
1
1
0
4
322
20c/tmpl
tests/test_engines.py
test_engines.Engine
class Engine: def __init__(self, name, scenario, env): self.name = name self.scenario = scenario self.env = env self.engine = getattr(tmpl, name, None) if not self.engine: pytest.skip("class %s not found" % (name)) if not self.engine.can_load(): pytest.skip("engine %s failed can_load" % (name)) self.src_dir = os.path.join("tests", "data", f"{self.scenario}_{self.name}") self.expected_dir = os.path.join( "tests", "data", "expected", "{}-{}".format(self.scenario, self.env["envname"]), ) print("src_dir=%s" % self.src_dir) print("expected_dir=%s" % self.expected_dir) def create_raw(self, **kwargs): return self.engine(**kwargs) def create(self, out_dir): return self.create_raw( tmpl_dir=str(self.src_dir), env=self.env, out_dir=str(out_dir) )
class Engine: def __init__(self, name, scenario, env): pass def create_raw(self, **kwargs): pass def create_raw(self, **kwargs): pass
4
0
9
1
8
0
2
0
0
1
0
0
3
6
3
3
30
5
25
10
21
0
18
10
14
3
0
1
5
323
20c/tmpl
tests/test_base.py
test_base.Empty
class Empty(Context): def __init__(self): super().__init__()
class Empty(Context): def __init__(self): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
14
3
0
3
2
1
0
3
2
1
1
1
0
1
324
20c/tmpl
src/tmpl/engine.py
tmpl.engine.Jinja2Template
class Jinja2Template(context.Template): def __init__(self, tmpl, **kwargs): self.tmpl = tmpl super().__init__(**kwargs) def render(self, env): """ renders from template, return object """ return self.tmpl.render(env) def load(self): pass def loads(self): pass
class Jinja2Template(context.Template): def __init__(self, tmpl, **kwargs): pass def render(self, env): ''' renders from template, return object ''' pass def load(self): pass def loads(self): pass
5
1
3
0
2
1
1
0.3
1
1
0
0
4
1
4
7
17
4
10
6
5
3
10
6
5
1
1
0
4
325
20c/tmpl
src/tmpl/context.py
tmpl.context.Context
class Context: """generic template interface class""" def __init__(self, **kwargs): """ tmpl_dir is the base directory templates are stored in out_dir is the output directory env is a default set of variables to use """ self._search_path = [] if "tmpl_dir" in kwargs: self._search_path = [kwargs.get("tmpl_dir")] if "search_path" in kwargs: self._search_path = kwargs.get("search_path", []) self.out_dir = kwargs.get("out_dir", None) self.env = kwargs.get("env", {}) @property def search_path(self): return self._search_path @search_path.setter def search_path(self, path_list): if isinstance(path_list, str): self._search_path = [path_list] else: self._search_path = path_list @search_path.deleter def search_path(self): self._search_path = [] # overridden if engine can handle it, otherwise we mock # def get_template(self, name): # filename = self.find_template(name) # if not filename: # raise LookupError("template not found") # return filename def find_template(self, name): for tmpl_dir in self.search_path: tmpl_file = os.path.join(tmpl_dir, name) if os.path.exists(tmpl_file): return tmpl_file return None def render(self, src, env=None, out_dir=None, out_file=None): """ renders src.tmpl with env to produce out_dir/src """ if not env: env = self.env if not out_dir: out_dir = self.out_dir if out_file: dest = out_file else: if not out_dir: raise RenderError("no output directory (out_dir) set") dest = os.path.join(str(out_dir), src) if not out_dir: raise RenderError("no output directory (out_dir) set") print(self.out_dir) print(src) print(os.getcwd()) self._render_file(src, env, dest) def render_file(self): pass # def render_env(self, env=None): # if not env: # env = self.env def render_string(self, instr, env=None): """ renders instr string with env and returns output string """ if not env: env = self.env return self._render_str_to_str(instr, env) def render_walk(self, env=None, prefix="", skip=None, tmpl_dir=None, out_dir=None): """ Walks a directory and recursively renders all files env -- override environment [default: self.env] skip -- list of regex to skip files [default: None] matches against the whole relative source path and the filename prefix -- prefix output file with this [default: ''] returns a list generated files tuples (source, output) """ if not env: env = self.env if not out_dir: out_dir = self.out_dir if tmpl_dir: return self.__render_walk(env, tmpl_dir, out_dir, prefix=prefix, skip=skip) for tmpl_dir in self.search_path: self.__render_walk(env, tmpl_dir, out_dir, prefix=prefix, skip=skip) def __render_walk(self, env, tmpl_dir, out_dir, prefix, skip): if skip: skip_re = re.compile(skip) generated = [] # self.debug_msg("rendering " + prefix + " from " + tmpl.tmpl_dir + " to " + tmpl.out_dir) for root, dirs, files in os.walk(tmpl_dir): rel_dir = os.path.relpath(root, tmpl_dir) if rel_dir == ".": rel_dir = "" elif skip and skip_re.search(rel_dir): continue out_dir = os.path.join(out_dir, prefix) for file in files: if skip and skip_re.search(file): continue # self.debug_msg("rendering from " + file) targ_dir = os.path.join(out_dir, rel_dir) if not os.path.exists(targ_dir): os.makedirs(targ_dir) dest_file = os.path.join(targ_dir, file) generated.append(dest_file) env["filename"] = os.path.join(rel_dir, prefix + file) # self.debug_msg("generating file " + env['filename']) # self.render(os.path.join(rel_dir, file), out_file=dest_file, env=env) self.render(os.path.join(rel_dir, file), out_file=dest_file, env=env) return generated def _render(self, src, env): """ renders src template file with env to return string """ abs_path = self.find_template(src) return self._render_str_to_str(open(abs_path).read(), env) def _render_file(self, src, env, dest): """ renders src template with env to produce dest file """ open(dest, "w").write(self._render(src, env)) def dump(self, src, env): tmpl = self.ctx.get_template(src) print(tmpl.render(env))
class Context: '''generic template interface class''' def __init__(self, **kwargs): ''' tmpl_dir is the base directory templates are stored in out_dir is the output directory env is a default set of variables to use ''' pass @property def search_path(self): pass @search_path.setter def search_path(self): pass @search_path.deleter def search_path(self): pass def find_template(self, name): pass def render(self, src, env=None, out_dir=None, out_file=None): ''' renders src.tmpl with env to produce out_dir/src ''' pass def render_file(self): pass def render_string(self, instr, env=None): ''' renders instr string with env and returns output string ''' pass def render_walk(self, env=None, prefix="", skip=None, tmpl_dir=None, out_dir=None): ''' Walks a directory and recursively renders all files env -- override environment [default: self.env] skip -- list of regex to skip files [default: None] matches against the whole relative source path and the filename prefix -- prefix output file with this [default: ''] returns a list generated files tuples (source, output) ''' pass def __render_walk(self, env, tmpl_dir, out_dir, prefix, skip): pass def _render(self, src, env): ''' renders src template file with env to return string ''' pass def _render_file(self, src, env, dest): ''' renders src template with env to produce dest file ''' pass def dump(self, src, env): pass
17
7
10
2
7
2
3
0.44
0
2
1
3
13
3
13
13
164
36
89
32
72
39
83
29
69
8
0
3
35
326
20c/twentyc.database
20c_twentyc.database/twentyc/database/dummydb/client.py
twentyc.database.dummydb.client.DummyDBClient
class DummyDBClient(object): meta_prefix = ":" log = None cb = None bucket = None def __init__(self, *args, **kwargs): return ############################################################################# def unset(self, key): return ############################################################################# def get(self, key): return {} ############################################################################# def set(self, key, data, retry=0): return 1 ############################################################################# def set_batch(self, data): return {} ############################################################################# def view(self, design_name, view_name, **kwargs): return [] ############################################################################# def xview(self, design_name, view_name, buffer=2000, **kwargs): return [] ############################################################################# def regenerate_view(self, design_name, view_name): return ############################################################################# def regenerate_all_views(self, design_name): return ############################################################################# def regenerate_all_views_forever(self, design_names, interval): return ############################################################################# def recent_docs(self, include_docs=True, limit=None): return [] ############################################################################# def dump(self, key): return "{}" ############################################################################# def get_design(self, design_name): return {} ############################################################################# def del_design(self, design_name): return ############################################################################# def put_design(self, design_name, design, verbose=False): return ############################################################################# def result(self, couchdb_response_text): return True
class DummyDBClient(object): def __init__(self, *args, **kwargs): pass def unset(self, key): pass def get(self, key): pass def set(self, key, data, retry=0): pass def set_batch(self, data): pass def view(self, design_name, view_name, **kwargs): pass def xview(self, design_name, view_name, buffer=2000, **kwargs): pass def regenerate_view(self, design_name, view_name): pass def regenerate_all_views(self, design_name): pass def regenerate_all_views_forever(self, design_names, interval): pass def recent_docs(self, include_docs=True, limit=None): pass def dump(self, key): pass def get_design(self, design_name): pass def del_design(self, design_name): pass def put_design(self, design_name, design, verbose=False): pass def result(self, couchdb_response_text): pass
17
0
2
0
2
0
1
0.41
1
0
0
0
16
0
16
16
85
33
37
21
20
15
37
21
20
1
1
0
16
327
20c/twentyc.database
20c_twentyc.database/twentyc/database/base.py
twentyc.database.base.InvalidEngineException
class InvalidEngineException(Exception): pass
class InvalidEngineException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
328
20c/twentyc.rpc
tests/test_client.py
test_client.DummyClient
class DummyClient(client.RestClient): testData = testData def __init__(self, **kwargs): super().__init__("http://localhost", **kwargs) def _request(self, typ, id=0, method="GET", data=None, params=None, url=None): """ Instead of requesting to a HTTP connection we retrieve pre-crafted responses from testData """ print("URL", url, typ, id) if not url: url = "/api/%s" % typ if id: url = f"{url}/{id}" else: url = url.replace("http://localhost", "") self._response = DummyResponse(**(self.testData.get(method).get(url))) return self._response
class DummyClient(client.RestClient): def __init__(self, **kwargs): pass def _request(self, typ, id=0, method="GET", data=None, params=None, url=None): ''' Instead of requesting to a HTTP connection we retrieve pre-crafted responses from testData ''' pass
3
1
10
2
6
2
2
0.29
1
2
1
0
2
1
2
16
25
7
14
5
11
4
13
5
10
3
1
2
4
329
20c/twentyc.rpc
tests/test_client.py
test_client.DummyResponse
class DummyResponse: def __init__(self, status_code, content, headers={}): self.status_code = status_code self.content = content self.headers = headers @property def data(self): return json.loads(self.content) def read(self, *args, **kwargs): return self.content def getheader(self, name): return self.headers.get(name) def json(self): return self.data
class DummyResponse: def __init__(self, status_code, content, headers={}): pass @property def data(self): pass def read(self, *args, **kwargs): pass def getheader(self, name): pass def json(self): pass
7
0
2
0
2
0
1
0
0
0
0
0
5
3
5
5
18
4
14
10
7
0
13
9
7
1
0
0
5
330
20c/twentyc.rpc
src/twentyc/rpc/client.py
twentyc.rpc.client.InvalidRequestException
class InvalidRequestException(ValueError): def __init__(self, msg, extra): super().__init__(self, msg) self.extra = extra
class InvalidRequestException(ValueError): def __init__(self, msg, extra): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
1
1
12
4
0
4
3
2
0
4
3
2
1
4
0
1
331
20c/twentyc.rpc
src/twentyc/rpc/client.py
twentyc.rpc.client.NotFoundException
class NotFoundException(LookupError): pass
class NotFoundException(LookupError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
1
1
0
2
1
1
0
4
0
0
332
20c/twentyc.rpc
src/twentyc/rpc/client.py
twentyc.rpc.client.PermissionDeniedException
class PermissionDeniedException(IOError): pass
class PermissionDeniedException(IOError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
333
20c/twentyc.rpc
src/twentyc/rpc/client.py
twentyc.rpc.client.RestClient
class RestClient: def __init__(self, url, **kwargs): """ RESTful client """ self.url = url self._url = parse.urlparse(self.url) self.user = None self.password = None self.timeout = None self.verbose = False # overwrite any param from keyword args for k in kwargs: if hasattr(self, k): setattr(self, k, kwargs[k]) def url_update(self, **kwargs): return parse.urlunparse(self._url._replace(**kwargs)) def _request(self, typ, id=0, method="GET", params=None, data=None, url=None): """ send the request, return response obj """ headers = {"Accept": "application/json"} auth = None if self.user: auth = (self.user, self.password) if not url: if id: url = f"{self.url}/{typ}/{id}" else: url = f"{self.url}/{typ}" return requests.request( method, url, params=params, data=data, auth=auth, headers=headers ) def _throw(self, res, data): self.log("=====> %s" % data) err = data.get("meta", {}).get("error", "Unknown") if res.status_code < 600: if res.status_code == 404: raise NotFoundException("%d %s" % (res.status_code, err)) elif res.status_code == 401 or res.status_code == 403: raise PermissionDeniedException("%d %s" % (res.status_code, err)) elif res.status_code == 400: raise InvalidRequestException("%d %s" % (res.status_code, err), data) # Internal raise Exception("%d Internal error: %s" % (res.status_code, err)) def _load(self, res): try: data = res.json() except ValueError: data = {} if res.status_code < 300: if not data: return [] return data.get("data", []) self._throw(res, data) def _mangle_data(self, data): if not "id" in data and "pk" in data: data["id"] = data["pk"] if "_rev" in data: del data["_rev"] if "pk" in data: del data["pk"] if "_id" in data: del data["_id"] def log(self, msg): if self.verbose: print(msg) def all(self, typ, **kwargs): """ List all of type Valid arguments: skip : number of records to skip limit : number of records to limit request to """ return self._load(self._request(typ, params=kwargs)) def get(self, typ, id, **kwargs): """ Load type by id """ return self._load(self._request(typ, id=id, params=kwargs)) def create(self, typ, data, return_response=False): """ Create new type Valid arguments: skip : number of records to skip limit : number of records to limit request to """ res = self._request(typ, method="POST", data=data) if res.status_code != 201: try: data = res.json() self._throw(res, data) except ValueError as e: if not isinstance(e, InvalidRequestException): self._throw(res, {}) else: raise loc = res.headers.get("location", None) if loc and loc.startswith("/"): return self._load(self._request(None, url=self.url_update(path=loc))) if return_response: return res.json() return self._load(self._request(None, url=loc)) def update(self, typ, id, **kwargs): """ update just fields sent by keyword args """ return self._load(self._request(typ, id=id, method="PUT", data=kwargs)) def save(self, typ, data): """ Save the dataset pointed to by data (create or update) """ if "id" in data: return self._load( self._request(typ, id=data["id"], method="PUT", data=data) ) return self.create(typ, data) def rm(self, typ, id): """ remove typ by id """ return self._load(self._request(typ, id=id, method="DELETE")) def type_wrap(self, typ): return TypeWrap(self, typ)
class RestClient: def __init__(self, url, **kwargs): ''' RESTful client ''' pass def url_update(self, **kwargs): pass def _request(self, typ, id=0, method="GET", params=None, data=None, url=None): ''' send the request, return response obj ''' pass def _throw(self, res, data): pass def _load(self, res): pass def _mangle_data(self, data): pass def log(self, msg): pass def all(self, typ, **kwargs): ''' List all of type Valid arguments: skip : number of records to skip limit : number of records to limit request to ''' pass def get(self, typ, id, **kwargs): ''' Load type by id ''' pass def create(self, typ, data, return_response=False): ''' Create new type Valid arguments: skip : number of records to skip limit : number of records to limit request to ''' pass def update(self, typ, id, **kwargs): ''' update just fields sent by keyword args ''' pass def save(self, typ, data): ''' Save the dataset pointed to by data (create or update) ''' pass def rm(self, typ, id): ''' remove typ by id ''' pass def type_wrap(self, typ): pass
15
8
10
1
7
2
3
0.35
0
6
4
1
14
6
14
14
148
24
92
29
77
32
84
28
69
6
0
3
37
334
20c/twentyc.rpc
src/twentyc/rpc/client.py
twentyc.rpc.client.TypeWrap
class TypeWrap: def __init__(self, client, typ): self.client = client self.typ = typ def all(self, **kwargs): """ List all """ return self.client.all(self.typ, **kwargs) def get(self, id): """ Load by id """ return self.client.get(self.typ, id) def save(self, data): """ Save object """ return self.client.save(self.typ, data) def rm(self, id): """ remove by id """ return self.client.rm(self.typ, id)
class TypeWrap: def __init__(self, client, typ): pass def all(self, **kwargs): ''' List all ''' pass def get(self, id): ''' Load by id ''' pass def save(self, data): ''' Save object ''' pass def rm(self, id): ''' remove by id ''' pass
6
4
5
0
2
2
1
1
0
0
0
0
5
2
5
5
28
4
12
8
6
12
12
8
6
1
0
0
5
335
20c/twentyc.tools
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20c_twentyc.tools/twentyc/tools/syslogfix.py
twentyc.tools.syslogfix.UTFFixedSysLogHandler
class UTFFixedSysLogHandler(SysLogHandler): """ A bug-fix sub-class of SysLogHandler that fixes the UTF-8 BOM syslog bug that caused UTF syslog entries to not go to the correct facility. This is fixed by over-riding the 'emit' definition with one that puts the BOM in the right place (after prio, instead of before it). Based on Python 2.7 version of logging.handlers.SysLogHandler. Bug Reference: http://bugs.python.org/issue7077 """ def emit(self, record): """ Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server. """ msg = self.format(record) + '\000' """ We need to convert record level to lowercase, maybe this will change in the future. """ prio = '<%d>' % self.encodePriority(self.facility, self.mapPriority(record.levelname)) prio = prio.encode('utf-8') # Message is a string. Convert to bytes as required by RFC 5424. msg = msg.encode('utf-8') if codecs: msg = codecs.BOM_UTF8 + msg msg = prio + msg try: if self.unixsocket: try: self.socket.send(msg) except socket.error: self._connect_unixsocket(self.address) self.socket.send(msg) elif self.socktype == socket.SOCK_DGRAM: self.socket.sendto(msg, self.address) else: self.socket.sendall(msg) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
class UTFFixedSysLogHandler(SysLogHandler): ''' A bug-fix sub-class of SysLogHandler that fixes the UTF-8 BOM syslog bug that caused UTF syslog entries to not go to the correct facility. This is fixed by over-riding the 'emit' definition with one that puts the BOM in the right place (after prio, instead of before it). Based on Python 2.7 version of logging.handlers.SysLogHandler. Bug Reference: http://bugs.python.org/issue7077 ''' def emit(self, record): ''' Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server. ''' pass
2
2
35
1
24
10
7
0.76
1
2
0
0
1
0
1
28
48
4
25
4
23
19
22
4
20
7
4
3
7
336
20c/vaping
src/vaping/config/__init__.py
vaping.config.Config
class Config(munge.Config): """ Vaping config manager """ defaults = { "config": { "vaping": { "home_dir": None, "pidfile": "vaping.pid", "plugin_path": [], }, }, "config_dir": "~/.vaping", "codec": "yaml", }
class Config(munge.Config): ''' Vaping config manager ''' pass
1
1
0
0
0
0
0
0.25
1
0
0
0
0
0
0
0
16
1
12
2
11
3
2
2
1
0
1
0
0
337
20c/vaping
src/vaping/plugins/fping_mtr.py
vaping.plugins.fping_mtr.FPingMTR
class FPingMTR(vaping.plugins.fping.FPingBase): """ Run fping on a traceroute path # Config - interval (`float`) time between pings - count (`int`) number of pings to send # Instanced Attributes - hosts (`list`) - lines_read (`int`) - mtr_host (`str`) """ def init(self): self.hosts = [] self.lines_read = 0 self.mtr_host = self.config.get("host") def parse_traceroute_line(self, line): """ parse host from verbose traceroute result format **Arguments** - line (string type): line from traceroutei result output **Returns** host (`str`) """ try: host = line.split()[1].decode("utf8") # TODO: do something else if host == "*"? if host.strip("*\n"): return host except Exception as e: logging.error(f"failed to get data {e}") def parse_traceroute(self, it): """ parse traceroute output **Arguments** - it: collection of lines to iterate through **Returns** hosts (`list<str>`): list of hosts in the traceroute result """ self.lines_read = 0 hosts = list() for line in it: self.lines_read += 1 # skip first line if self.lines_read == 1: continue host = self.parse_traceroute_line(line) if host and host not in hosts: hosts.append(host) if not len(hosts): raise Exception("no path found") return hosts def get_hosts(self): """ Run traceroute for the `mtr_host` host and return the hosts found in the route **Returns** hosts (`list<str>`): list of hosts in the route to `mtr_host` """ command = "traceroute" # first_ttl = 1 # max_ttl = 24 # timeout = 0.3 # protocol = "udp" # port = 33434 # -f first_ttl # -m max_ttl args = [ command, "-n", # -w wait time seconds "-w1", # -q number of queries "-q1", self.mtr_host, ] # get both stdout and stderr proc = self.popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) with proc.stdout: hosts = self.parse_traceroute(iter(proc.stdout.readline, b"")) return hosts def probe(self): """ Gets a list of hosts via `get_hosts` and then runs fping against all of them to build mtr data **Returns** msg (`dict`) """ self.hosts = self.get_hosts() msg = self.new_message() data = { hop["host"]: hop for hop in self._run_proc() if hop and hop["host"] in self.hosts } msg["data"] = [ dict( hops=self.hosts, host=self.mtr_host, data=data, ), ] return msg
class FPingMTR(vaping.plugins.fping.FPingBase): ''' Run fping on a traceroute path # Config - interval (`float`) time between pings - count (`int`) number of pings to send # Instanced Attributes - hosts (`list`) - lines_read (`int`) - mtr_host (`str`) ''' def init(self): pass def parse_traceroute_line(self, line): ''' parse host from verbose traceroute result format **Arguments** - line (string type): line from traceroutei result output **Returns** host (`str`) ''' pass def parse_traceroute_line(self, line): ''' parse traceroute output **Arguments** - it: collection of lines to iterate through **Returns** hosts (`list<str>`): list of hosts in the traceroute result ''' pass def get_hosts(self): ''' Run traceroute for the `mtr_host` host and return the hosts found in the route **Returns** hosts (`list<str>`): list of hosts in the route to `mtr_host` ''' pass def probe(self): ''' Gets a list of hosts via `get_hosts` and then runs fping against all of them to build mtr data **Returns** msg (`dict`) ''' pass
6
5
23
5
11
8
2
0.89
1
3
0
0
5
3
5
9
134
32
54
20
48
48
38
19
32
5
2
2
11
338
20c/vaping
src/vaping/plugins/fping.py
vaping.plugins.fping.FPingBase
class FPingBase(vaping.plugins.TimedProbe): """ FPing base plugin config: # Config - command (`str=fping`): command to run - interval (`str=1m`): time between pings - count (`int=5`): number of pings to send - period (`int=20`): time in milliseconds that fping waits between successive packets to an individual target # Instanced Attributes - count (`int`): number of fpings to send - period (`int`): time in milliseconds that fping waits between successive packets """ ConfigSchema = FPingSchema def __init__(self, config, ctx): super().__init__(config, ctx) if not which(self.config["command"]): self.log.critical( "missing fping, install it or set `command` in the fping config" ) raise RuntimeError("fping command not found - install the fping package") self.count = self.config.get("count") self.period = self.config.get("period") def hosts_args(self): """ hosts list can contain strings specifying a host directly or dicts containing a "host" key to specify the host this way we can allow passing further config details (color, name etc.) with each host as well as simply dropping in addresses for quick setup depending on the user's needs """ host_args = [] for row in self.hosts: if isinstance(row, dict): host_args.append(row["host"]) else: host_args.append(row) # using a set changes the order dedupe = list() for each in host_args: if each not in dedupe: dedupe.append(each) return dedupe def parse_verbose(self, line): """ parse output from verbose format **Returns** parsed fping result (`dict`) - `host`: host name - `cnt`: fpings sent - `loss` - `data`: list of inidivual fping times - `min`: smallest fping time - `max`: biggest fping time - `avg`: average fping time - `last`: last fping time """ try: logging.debug(line) (host, pings) = line.split(" : ") cnt = 0 lost = 0 times = [] pings = pings.strip().split(" ") cnt = len(pings) for latency in pings: if latency == "-": continue times.append(float(latency)) lost = cnt - len(times) if lost: loss = lost / float(cnt) else: loss = 0.0 rv = { "host": host.strip(), "cnt": cnt, "loss": loss, "data": times, } if times: rv["min"] = min(times) rv["max"] = max(times) rv["avg"] = sum(times) / len(times) rv["last"] = times[-1] return rv except Exception as e: logging.error(f"failed to get data: {e}") def _run_proc(self): args = [ self.config["command"], "-u", "-C%d" % self.count, "-p%d" % self.period, "-e", ] args.extend(self.hosts_args()) data = list() # get both stdout and stderr with self.popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: for line in iter(proc.stdout.readline, b""): data.append(self.parse_verbose(line.decode("utf-8"))) return data
class FPingBase(vaping.plugins.TimedProbe): ''' FPing base plugin config: # Config - command (`str=fping`): command to run - interval (`str=1m`): time between pings - count (`int=5`): number of pings to send - period (`int=20`): time in milliseconds that fping waits between successive packets to an individual target # Instanced Attributes - count (`int`): number of fpings to send - period (`int`): time in milliseconds that fping waits between successive packets ''' def __init__(self, config, ctx): pass def hosts_args(self): ''' hosts list can contain strings specifying a host directly or dicts containing a "host" key to specify the host this way we can allow passing further config details (color, name etc.) with each host as well as simply dropping in addresses for quick setup depending on the user's needs ''' pass def parse_verbose(self, line): ''' parse output from verbose format **Returns** parsed fping result (`dict`) - `host`: host name - `cnt`: fpings sent - `loss` - `data`: list of inidivual fping times - `min`: smallest fping time - `max`: biggest fping time - `avg`: average fping time - `last`: last fping time ''' pass def _run_proc(self): pass
5
3
26
3
17
6
4
0.51
1
6
0
2
4
2
4
4
127
23
69
24
64
35
54
22
49
6
1
3
15
339
20c/vaping
src/vaping/plugins/fping.py
vaping.plugins.fping.FPing
class FPing(FPingBase): """ Run fping on configured hosts # Config - command (`str=fping`): command to run - interval (`str=1m`): time between pings - count (`int=5`): number of pings to send - period (`int=20`): time in milliseconds that fping waits between successive packets to an individual target """ def init(self): self.hosts = [] for name, group_config in list(self.groups.items()): self.hosts.extend(group_config.get("hosts", [])) def probe(self): msg = self.new_message() msg["data"] = self._run_proc() return msg
class FPing(FPingBase): ''' Run fping on configured hosts # Config - command (`str=fping`): command to run - interval (`str=1m`): time between pings - count (`int=5`): number of pings to send - period (`int=20`): time in milliseconds that fping waits between successive packets to an individual target ''' def init(self): pass def probe(self): pass
3
1
5
1
4
0
2
1
1
1
0
0
2
1
2
6
23
5
9
6
6
9
9
6
6
2
2
1
3
340
20c/vaping
src/vaping/plugins/command.py
vaping.plugins.command.CommandProbe
class CommandProbe(vaping.plugins.TimedProbe): """ Probe type plugin that allows you to run an arbitrary command for each host and return the command output as data # Config - command (`str`): command to run (use `{host}` to reference the host) - interval (`float`): time between probes # Instanced Attributes - command (`str`): command to run """ default_config = { "command": None, "interval": "1m", "count": 5, } def init(self): if "command" not in self.config: raise ValueError("command is required") for name, group_config in list(self.groups.items()): self.hosts.extend(group_config.get("hosts", [])) self.command = self.config["command"] def probe(self): codec = munge.get_codec("yaml")() msg = {} msg["data"] = [] msg["ts"] = ( datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1) ).total_seconds() # FIXME use poll for host in self.hosts: args = shlex.split(self.command.format(host=host)) proc = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) # TODO poll, timeout, maybe from parent process for better control? with proc.stdout: # msg['data'].append(proc.stdout.read()) msg["data"].append(codec.load(proc.stdout)) return msg
class CommandProbe(vaping.plugins.TimedProbe): ''' Probe type plugin that allows you to run an arbitrary command for each host and return the command output as data # Config - command (`str`): command to run (use `{host}` to reference the host) - interval (`float`): time between probes # Instanced Attributes - command (`str`): command to run ''' def init(self): pass def probe(self): pass
3
1
15
3
11
2
3
0.48
1
4
0
0
2
1
2
2
53
13
27
11
24
13
19
11
16
3
1
2
5
341
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.TimedProbeSchema
class TimedProbeSchema(PluginConfigSchema): interval = confu.schema.Str()
class TimedProbeSchema(PluginConfigSchema): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
2
0
2
2
1
0
2
2
1
0
2
0
0
342
20c/vaping
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/20c_vaping/tests/test_plugin.py
test_plugin.test_plugin_registry.p0
class p0(plugins.PluginBase): pass
class p0(plugins.PluginBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
343
20c/vaping
src/vaping/config/schema.py
vaping.config.schema.HostSchema
class HostSchema(confu.schema.Schema): # host = confu.schema.IpAddress() # FPing just needs a string here host = confu.schema.Str() name = confu.schema.Str() color = confu.schema.Str()
class HostSchema(confu.schema.Schema): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
6
0
4
4
3
2
4
4
3
0
1
0
0
344
20c/vaping
src/vaping/config/schema.py
vaping.config.schema.GroupSchema
class GroupSchema(confu.schema.Schema): name = confu.schema.Str() hosts = confu.schema.List(item=HostSchema(), help="list of hosts")
class GroupSchema(confu.schema.Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
1
0
0
345
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.TimedProbe
class TimedProbe(ProbeBase): """ Probe class that calls probe every config defined interval """ ConfigSchema = TimedProbeSchema def __init__(self, config, ctx, emit=None): super().__init__(config, ctx, emit) if "interval" not in self.pluginmgr_config: raise ValueError("interval not set in config") self.interval = parse_interval(self.pluginmgr_config["interval"]) self.run_level = 0 async def _run(self): self.run_level = 1 while self.run_level: start = datetime.datetime.now() # since the TimedProbe will sleep between cycles # we need to emit all queued emissions each cycle await self.emit_all() msg = self.probe() if msg: await self.queue_emission(msg) else: self.log.debug("probe returned no data") done = datetime.datetime.now() elapsed = done - start if elapsed.total_seconds() > self.interval: self.log.warning("probe time exceeded interval") else: sleeptime = datetime.timedelta(seconds=self.interval) - elapsed await vaping.io.sleep(sleeptime.total_seconds())
class TimedProbe(ProbeBase): ''' Probe class that calls probe every config defined interval ''' def __init__(self, config, ctx, emit=None): pass async def _run(self): pass
3
1
15
3
12
1
3
0.2
1
4
0
0
2
2
2
39
38
8
25
11
22
5
23
11
20
4
4
2
6
346
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.TimeSeriesDBSchema
class TimeSeriesDBSchema(PluginConfigSchema): filename = confu.schema.Str(help="database file name template") field = confu.schema.Str(help="field name to read the value from")
class TimeSeriesDBSchema(PluginConfigSchema): pass
1
0
0
0
0
0
0
0
1
0
0
3
0
0
0
0
3
0
3
3
2
0
3
3
2
0
2
0
0
347
20c/vaping
src/vaping/plugins/graphite.py
vaping.plugins.graphite.GraphitePlugin
class GraphitePlugin(vaping.plugins.TimeSeriesDB): """ Graphite plugin that allows vaping to persist data to a graphite via line protocole """ def __init__(self, config, ctx): super().__init__(config, ctx) if not graphyte: self.log.critical( "missing graphyte, install it with `pip install graphyte`" ) raise RuntimeError("graphyte not found") # get configs # FIXME: Add help self.proto = self.config.get("proto") self.graphite_host = self.config.get("graphite_host") self.prefix = self.config.get("prefix") def start(self): graphyte.init(str(self.graphite_host), prefix=str(self.prefix)) def create(self, filename): return def update(self, filename, time, value): if value is None: return filename = munge_filename(filename) graphyte.send(f"{filename}", value, time) def get(self, filename, from_time, to_time=None): filename = munge_filename(filename) resp = requests.get( "{}://{}/render/?target={}.{}&from={}&format=raw".format( self.proto, self.graphite_host, self.prefix, filename, from_time ) ) if resp.ok: data = str(resp.text).rstrip().split("|") # create timing tuple (metric, fromstamp, tostamp, stepsize) = data[0].split(",") times = fromstamp, tostamp, stepsize # create values list values = [] for v in data[1].split(","): values.append(float(v)) return times, values else: raise ValueError("error couldn't get graphite data")
class GraphitePlugin(vaping.plugins.TimeSeriesDB): ''' Graphite plugin that allows vaping to persist data to a graphite via line protocole ''' def __init__(self, config, ctx): pass def start(self): pass def create(self, filename): pass def update(self, filename, time, value): pass def get(self, filename, from_time, to_time=None): pass
6
1
10
2
7
1
2
0.22
1
5
0
0
5
3
5
5
60
15
37
15
31
8
30
15
24
3
1
2
9
348
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.PluginConfigSchema
class PluginConfigSchema(confu.schema.Schema): """ Configuration Schema for [PluginBase](#pluginbase) When creating new configuration schemas for extended plugins extend this. """ name = confu.schema.Str("name", help="Plugin name") type = confu.schema.Str("type", help="Plugin type")
class PluginConfigSchema(confu.schema.Schema): ''' Configuration Schema for [PluginBase](#pluginbase) When creating new configuration schemas for extended plugins extend this. ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
6
0
0
0
0
10
2
3
3
2
5
3
3
2
0
1
0
0
349
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.FileProbeSchema
class FileProbeSchema(PluginConfigSchema): path = confu.schema.Str() backlog = confu.schema.Int(default=10) max_lines = confu.schema.Int(default=1000)
class FileProbeSchema(PluginConfigSchema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
2
0
0
350
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.FileProbe
class FileProbe(ProbeBase): """ Probes a file and emits everytime a new line is read # Config - path (`str`): path to file - backlog (`int=0`): number of bytes to read from backlog - max_lines (`int=1000`): maximum number of lines to read during probe # Instanced Attributes - path (`str`): path to file - backlog (`int`): number of bytes to read from backlog - max_lines (`int`): maximum number of liens to read during probe - fh (`filehandler`): file handler for opened file (only available if `path` is set) """ ConfigSchema = FileProbeSchema def __init__(self, config, ctx, emit=None): super().__init__(config, ctx, emit) self.path = self.pluginmgr_config.get("path") self.run_level = 0 self.backlog = int(self.pluginmgr_config.get("backlog", 0)) self.max_lines = int(self.pluginmgr_config.get("max_lines", 1000)) if self.path: self.fh = open(self.path) self.fh.seek(0, 2) if self.backlog: try: self.fh.seek(self.fh.tell() - self.backlog, os.SEEK_SET) except ValueError as exc: if str(exc).find("negative seek position") > -1: self.fh.seek(0) else: raise async def _run(self): self.run_level = 1 while self.run_level: self.send_emission() for msg in self.probe(): await self.queue_emission(msg) await vaping.io.sleep(0.1) def validate_file_handler(self): """ Here we validate that our filehandler is pointing to an existing file. If it doesnt, because file has been deleted, we close the filehander and try to reopen """ if self.fh.closed: try: self.fh = open(self.path) self.fh.seek(0, 2) except OSError as err: logging.error(f"Could not reopen file: {err}") return False open_stat = os.fstat(self.fh.fileno()) try: file_stat = os.stat(self.path) except OSError as err: logging.error(f"Could not stat file: {err}") return False if open_stat != file_stat: self.log self.fh.close() return False return True def probe(self): """ Probe the file for new lines """ # make sure the filehandler is still valid # (e.g. file stat hasnt changed, file exists etc.) if not self.validate_file_handler(): return [] messages = [] # read any new lines and push them onto the stack for line in self.fh.readlines(self.max_lines): data = {"path": self.path} msg = self.new_message() # process the line - this is where parsing happens parsed = self.process_line(line, data) if not parsed: continue data.update(parsed) # process the probe - this is where data assignment # happens data = self.process_probe(data) msg["data"] = [data] messages.append(msg) # process all new messages before returning them # for emission messages = self.process_messages(messages) return messages def process_line(self, line, data): """override this - parse your line in here""" return data def process_probe(self, data): """override this - assign your data values here""" return data def process_messages(self, messages): """ override this - process your messages before they are emitted """ return messages
class FileProbe(ProbeBase): ''' Probes a file and emits everytime a new line is read # Config - path (`str`): path to file - backlog (`int=0`): number of bytes to read from backlog - max_lines (`int=1000`): maximum number of lines to read during probe # Instanced Attributes - path (`str`): path to file - backlog (`int`): number of bytes to read from backlog - max_lines (`int`): maximum number of liens to read during probe - fh (`filehandler`): file handler for opened file (only available if `path` is set) ''' def __init__(self, config, ctx, emit=None): pass async def _run(self): pass def validate_file_handler(self): ''' Here we validate that our filehandler is pointing to an existing file. If it doesnt, because file has been deleted, we close the filehander and try to reopen ''' pass def probe(self): ''' Probe the file for new lines ''' pass def process_line(self, line, data): '''override this - parse your line in here''' pass def process_probe(self, data): '''override this - assign your data values here''' pass def process_messages(self, messages): ''' override this - process your messages before they are emitted ''' pass
8
6
15
2
9
3
3
0.52
1
5
0
0
7
5
7
44
129
27
67
24
59
35
66
22
58
5
4
4
20
351
20c/vaping
src/vaping/io.py
vaping.io.Thread
class Thread: def start(self): self.started = True return
class Thread: def start(self): pass
2
0
3
0
3
0
1
0
0
0
0
1
1
1
1
1
4
0
4
3
2
0
4
3
2
1
0
0
1
352
20c/vaping
src/vaping/io.py
vaping.io.Queue
class Queue(asyncio.Queue): pass
class Queue(asyncio.Queue): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
353
20c/vaping
src/vaping/daemon.py
vaping.daemon.Vaping
class Vaping: """Vaping daemon class""" def __init__(self, config=None, config_dir=None): """ must either pass config as a dict or vaping.config.Config or config_dir as a path to where the config dir is located """ self.joins = [] self._logger = None self.load_config(config, config_dir) self.validate_config_data(self.config.data) # configure vaping logging if "logging" in self.config: logging.config.dictConfig(self.config.get("logging")) self.plugin_context = PluginContext(self.config) # GET VAPING PART OF CONFIG vcfg = self.config.get("vaping", None) if not vcfg: vcfg = dict() # GET HOME_DIR PART OF CONFIG # get either home_dir from config, or use config_dir self.home_dir = vcfg.get("home_dir", None) if not self.home_dir: # self.home_dir = self.config.meta["config_dir"] self.home_dir = self.config["config_dir"] self.home_dir = os.path.abspath(self.home_dir) if not os.path.exists(self.home_dir): raise ValueError(f"home directory '{self.home_dir}' does not exist") if not os.access(self.home_dir, os.W_OK): raise ValueError(f"home directory '{self.home_dir}' is not writable") # change to home for working dir os.chdir(self.home_dir) # instantiate all defined plugins # TODO remove and let them lazy init? plugins = self.config.get("plugins", None) if not plugins: raise ValueError("no plugins specified") plugin.instantiate(self.config["plugins"], self.plugin_context) # check that probes don't name clash with plugins for probe in self.config.get("probes", []): if plugin.exists(probe["name"]): raise ValueError( "probes may not share names with plugins ({})".format(probe["name"]) ) self.pidname = vcfg.get("pidfile", "vaping.pid") def load_config(self, config=None, config_dir=None): if config_dir and not config: config = self._extract_config_from_dir(config_dir) self._load_config(config) def _load_config(self, config): if isinstance(config, confu.config.Config): self.config = config # Check if type dict, and not empty elif isinstance(config, dict) and bool(config): self.config = confu.config.Config(VapingSchema(), config) else: raise ValueError("config was not specified or empty") def _extract_config_from_dir(self, config_dir): try: data = load_datafile("config", config_dir) except OSError: raise OSError("config dir not found") return data def validate_config_data(self, config_data): try: VapingSchema().validate(config_data) except ValidationWarning as exc: """ We do not verify logging with the schema so we can skip this error. (it will occur when a logging config IS provided) """ if "logging" in str(exc): return else: self.log.warning(exc.pretty) @property def pidfile(self): if not hasattr(self, "_pidfile"): self._pidfile = pidfile.PidFile(pidname=self.pidname, piddir=self.home_dir) return self._pidfile @property def log(self): """ logger instance """ if not self._logger: self._logger = logging.getLogger(__name__) return self._logger @property def get_logging_handles(self): handles = [] logger = self.log for handler in logger.handlers: handles.append(handler.stream.fileno()) return handles def _exec(self, detach=True): """ daemonize and exec main() """ kwargs = { "working_directory": self.home_dir, # we preserve stdin and any file logging handlers # we setup - for some reason stdin is required # to be kept to fix startup issues (#85). # # TODO: revisit this rabbit hole "files_preserve": [0] + self.get_logging_handles, } # FIXME - doesn't work if not detach: kwargs.update( { "detach_process": False, "files_preserve": [0, 1, 2], "stdout": sys.stdout, "stderr": sys.stderr, } ) ctx = daemon.DaemonContext(**kwargs) with ctx: with self.pidfile: self._main() def _main(self): """ process """ try: probes = self.config.get("probes", None) if not probes: raise ValueError("no probes specified") for probe_config in self.config["probes"]: probe = plugin.get_probe(probe_config, self.plugin_context) # get all output targets and start / join them for output_name in probe_config.get("output", []): output = plugin.get_output(output_name, self.plugin_context) if not output.started and not output.__class__.lazy_start: output.start() self.joins.append(output) probe._emit.append(output) probe.start() self.joins.append(probe) vaping.io.join_plugins(self.joins) except Exception as exc: # TODO option to log trace self.log.error(exc) raise return 0 def start(self): """start daemon""" self._exec() def stop(self): """stop daemon""" try: with self.pidfile: self.log.error("failed to stop, missing pid file or not running") except pidfile.PidFileError: # this isn't exposed in pidfile :o with open(self.pidfile.filename) as fobj: pid = int(fobj.readline().rstrip()) if not pid: self.log.error("failed to read pid from file") self.log.info("killing %d", pid) os.kill(pid, signal.SIGTERM) def run(self): """run daemon""" # FIXME - not detaching doesn't work, just run directly for now # self._exec(detach=False) try: with self.pidfile: return self._main() except pidfile.PidFileError: # this isn't exposed in pidfile :o self.log.error("failed to get pid lock, already running?") return 1 finally: # call on_stop to let them clean up for mod in self.joins: self.log.debug("stopping %s", mod.name) mod.on_stop()
class Vaping: '''Vaping daemon class''' def __init__(self, config=None, config_dir=None): ''' must either pass config as a dict or vaping.config.Config or config_dir as a path to where the config dir is located ''' pass def load_config(self, config=None, config_dir=None): pass def _load_config(self, config): pass def _extract_config_from_dir(self, config_dir): pass def validate_config_data(self, config_data): pass @property def pidfile(self): pass @property def log(self): ''' logger instance ''' pass @property def get_logging_handles(self): pass def _exec(self, detach=True): ''' daemonize and exec main() ''' pass def _main(self): ''' process ''' pass def start(self): '''start daemon''' pass def stop(self): '''stop daemon''' pass def run(self): '''run daemon''' pass
17
8
16
2
10
3
3
0.33
0
9
2
0
13
7
13
13
222
42
135
43
118
45
116
37
102
9
0
4
40
354
20c/vaping
src/vaping/daemon.py
vaping.daemon.PluginContext
class PluginContext: """ Context to pass to plugins for getting extra information """ def __init__(self, config): # probably should be a deep copy for security from plugins self.__config = config.copy() @property def config(self): """ config """ return self.__config
class PluginContext: ''' Context to pass to plugins for getting extra information ''' def __init__(self, config): pass @property def config(self): ''' config ''' pass
4
2
4
0
2
2
1
1.17
0
0
0
0
2
1
2
2
15
2
6
5
2
7
5
4
2
1
0
0
2
355
20c/vaping
src/vaping/config/schema.py
vaping.config.schema.MixedDict
class MixedDict(confu.schema.Dict): """ Extended confu.schema.Dict object that prevents validation of its interior objects. Use for dictionaries that do not need validation or will get validated other ways, like in Vodka plugin or logging. """ def validate(self, config, path=None, errors=None, warnings=None): return config
class MixedDict(confu.schema.Dict): ''' Extended confu.schema.Dict object that prevents validation of its interior objects. Use for dictionaries that do not need validation or will get validated other ways, like in Vodka plugin or logging. ''' def validate(self, config, path=None, errors=None, warnings=None): pass
2
1
2
0
2
0
1
2
1
0
0
0
1
0
1
1
10
1
3
2
1
6
3
2
1
1
1
0
1
356
20c/vaping
src/vaping/config/schema.py
vaping.config.schema.PluginProxySchema
class PluginProxySchema(confu.schema.ProxySchema): """ Will properly route plugin validation to the correct plugin schema """ def schema(self, config): import vaping try: return vaping.plugin.get_plugin_class(config["type"]).ConfigSchema() except KeyError: raise ValueError("All plugins need `type` field set in config.") def validate(self, config, path=None, errors=None, warnings=None): try: path[-1] = config["name"] except KeyError: raise ValueError("All plugins need `name` field set in config.") return self.schema(config).validate( config, path=path, errors=errors, warnings=warnings )
class PluginProxySchema(confu.schema.ProxySchema): ''' Will properly route plugin validation to the correct plugin schema ''' def schema(self, config): pass def validate(self, config, path=None, errors=None, warnings=None): pass
3
1
8
1
7
0
2
0.27
1
2
0
0
2
0
2
2
23
4
15
4
11
4
13
4
9
2
1
1
4
357
20c/vaping
src/vaping/config/schema.py
vaping.config.schema.ProbesSchema
class ProbesSchema(confu.schema.Schema): """ Configuration schema for probes """ name = confu.schema.Str() type = confu.schema.Str() output = confu.schema.List(item=confu.schema.Str(), help="list of outputs") groups = confu.schema.List(item=GroupSchema(), help="group schema")
class ProbesSchema(confu.schema.Schema): ''' Configuration schema for probes ''' pass
1
1
0
0
0
0
0
0.6
1
0
0
0
0
0
0
0
9
1
5
5
4
3
5
5
4
0
1
0
0
358
20c/vaping
src/vaping/config/schema.py
vaping.config.schema.VapingSchema
class VapingSchema(confu.schema.Schema): """ Configuration schema for vaping config """ plugin_path = confu.schema.List( item=confu.schema.Directory(), help="list of directories to search for plugins", ) probes = confu.schema.List(item=ProbesSchema(), help="list of probes") plugins = confu.schema.List( item=PluginProxySchema(), help="list of plugin config objects" ) # config_dir = confu.schema.Directory(default="~/.vaping") config_dir = confu.schema.Directory(default="") home_dir = confu.schema.Directory(default=None) pidfile = confu.schema.Str(default="vaping.pid")
class VapingSchema(confu.schema.Schema): ''' Configuration schema for vaping config ''' pass
1
1
0
0
0
0
0
0.33
1
0
0
0
0
0
0
0
20
4
12
7
11
4
7
7
6
0
1
0
0
359
20c/vaping
src/vaping/plugins/__init__.py
vaping.plugins.PluginBase
class PluginBase(vaping.io.Thread): """ Base plugin interface # Class Attributes - lazy_start (`bool`=`False`): if `True` plugin will not be started on vaping start, but when at a later point (usually when it starts emitting). Note that the plugin itself will need to call `self.start()` somewhere explicitly when this is `True`. # Instanced Attributes - config (`dict`): plugin config - vaping: reference to the main vaping object Calls `self.init()` prefork while loading all modules, init() should not do anything active, any files opened may be closed when it forks. Plugins should prefer `init()` to `__init__()` to ensure the class is completely done initializing. Calls `self.on_start()` and `self.on_stop()` before and after running in case any connections need to be created or cleaned up. """ lazy_start = False ConfigSchema = PluginConfigSchema ConfigSchema.help = "Base plugin config schema" @property def groups(self): """ `dict` - group configurations keyed by name """ group_config = {} # legacy way of threating any dict as a potential # group config (pre #44 implementation) # supported until vaping 2.0 for k, v in list(self.config.items()): if isinstance(v, collections.abc.Mapping): group_config[k] = v # explicit groups object (#44 implementation) for _group_config in self.config.get("groups", []): group_config[_group_config["name"]] = _group_config return group_config def init(self): """ called after the plugin is initialized, plugin may define this for any other initialization code """ pass def on_start(self): """ called when the daemon is starting """ pass def on_stop(self): """ called when the daemon is stopping """ pass def new_message(self): """ creates and returns new message `dict`, setting `type`, `source`, `ts`, `data` `data` is initialized to an empty array **Returns** message (`dict`) """ msg = {} msg["data"] = [] msg["type"] = self.plugin_type msg["source"] = self.name msg["ts"] = ( datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1) ).total_seconds() return msg def popen(self, args, **kwargs): """ creates a subprocess with passed args **Returns** Popen instance """ self.log.debug("popen %s", " ".join(args)) return vaping.io.subprocess.Popen(args, **kwargs) @property def log(self): """ logger instance for plugin type """ if not self._logger: self._logger = logging.getLogger("vaping.plugins." + self.plugin_type) return self._logger def __init__(self, config, ctx): """ **Arguments** - config (`dict`) - ctx: vaping context """ # FIXME: figure out what from this we want to keep if hasattr(self, "default_config"): self.config = munge.util.recursive_update( copy.deepcopy(self.default_config), copy.deepcopy(config) ) else: self.config = config if hasattr(self, "ConfigSchema"): confu.schema.apply_defaults(self.ConfigSchema(), config) # set for pluginmgr self.pluginmgr_config = self.config self.vaping = ctx self.name = self.config.get("name") self._logger = None self.lazy_start = False self.started = False super().__init__() self.init() async def _run(self): self.on_start()
class PluginBase(vaping.io.Thread): ''' Base plugin interface # Class Attributes - lazy_start (`bool`=`False`): if `True` plugin will not be started on vaping start, but when at a later point (usually when it starts emitting). Note that the plugin itself will need to call `self.start()` somewhere explicitly when this is `True`. # Instanced Attributes - config (`dict`): plugin config - vaping: reference to the main vaping object Calls `self.init()` prefork while loading all modules, init() should not do anything active, any files opened may be closed when it forks. Plugins should prefer `init()` to `__init__()` to ensure the class is completely done initializing. Calls `self.on_start()` and `self.on_stop()` before and after running in case any connections need to be created or cleaned up. ''' @property def groups(self): ''' `dict` - group configurations keyed by name ''' pass def init(self): ''' called after the plugin is initialized, plugin may define this for any other initialization code ''' pass def on_start(self): ''' called when the daemon is starting ''' pass def on_stop(self): ''' called when the daemon is stopping ''' pass def new_message(self): ''' creates and returns new message `dict`, setting `type`, `source`, `ts`, `data` `data` is initialized to an empty array **Returns** message (`dict`) ''' pass def popen(self, args, **kwargs): ''' creates a subprocess with passed args **Returns** Popen instance ''' pass @property def log(self): ''' logger instance for plugin type ''' pass def __init__(self, config, ctx): ''' **Arguments** - config (`dict`) - ctx: vaping context ''' pass async def _run(self): pass
12
9
11
2
5
4
2
1
1
5
0
2
9
6
9
10
144
34
55
24
43
55
48
22
38
4
1
2
15
360
20c/vaping
src/vaping/plugins/graphite.py
vaping.plugins.graphite.GraphiteSchema
class GraphiteSchema(TimeSeriesDBSchema): proto = confu.schema.Str(default="http") graphite_host = confu.schema.Str( default="127.0.0.1", help="IP address for graphite host." ) prefix = confu.schema.Str(default="vaping")
class GraphiteSchema(TimeSeriesDBSchema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
6
0
6
4
5
0
4
4
3
0
3
0
0
361
20c/vaping
src/vaping/plugins/fping.py
vaping.plugins.fping.FPingSchema
class FPingSchema(TimedProbeSchema): """ Define a schema for FPing and also define defaults. """ count = confu.schema.Int(default=5, help="Number of pings to send") interval = confu.schema.Str(default="1m", help="Time between pings") output = confu.schema.List( item=confu.schema.Str(), help="Determine what plugin displays output" ) period = confu.schema.Int( default=20, help="Time in milliseconds that fping waits between successive packets to an individual target", ) command = confu.schema.Str(default="fping", help="Command to run")
class FPingSchema(TimedProbeSchema): ''' Define a schema for FPing and also define defaults. '''
1
1
0
0
0
0
0
0.27
1
0
0
0
0
0
0
0
15
1
11
6
10
3
6
6
5
0
3
0
0
362
20c/vaping
src/vaping/plugins/logparse.py
vaping.plugins.logparse.FieldSchema
class FieldSchema(confu.schema.Schema): parser = confu.schema.Str( help="Regex pattern to parse field value, needs to one group in it" ) type = confu.schema.Str(help="Value type (int, float etc.)") aggregate = confu.schema.Str( help="How to aggregate the field if aggregation is turned on (sum, avg, eval)" ) eval = confu.schema.Str( help="Evaluate to create the value, other fields' values will be available in the string formatting" )
class FieldSchema(confu.schema.Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
11
0
11
4
10
0
5
4
4
0
1
0
0
363
20c/vaping
src/vaping/cli.py
vaping.cli.Context
class Context(munge.click.Context): """ Extended `click` context to use for vaping cli """ app_name = "vaping" config_class = vaping.Config
class Context(munge.click.Context): ''' Extended `click` context to use for vaping cli ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
0
7
1
3
3
2
3
3
3
2
0
1
0
0
364
20c/vaping
src/vaping/__init__.py
vaping.PluginManager
class PluginManager(ConfigPluginManager): """ Vaping plugin manager An instance of this will be instantiated automatically and be available as `vaping.plugin` """ def exists(self, name): """ Check if plugin instance exists **Arguments** - name (`str`): plugin instance name **Returns** `True` if instance exists, `False` if not """ if name in self._instance: return True return False def get_probe(self, node, pctx): obj = self.get_instance(node, pctx) check_method(obj, "probe", node) return obj def get_output(self, node, pctx): obj = self.get_instance(node, pctx) check_method(obj, "emit", node) return obj
class PluginManager(ConfigPluginManager): ''' Vaping plugin manager An instance of this will be instantiated automatically and be available as `vaping.plugin` ''' def exists(self, name): ''' Check if plugin instance exists **Arguments** - name (`str`): plugin instance name **Returns** `True` if instance exists, `False` if not ''' pass def get_probe(self, node, pctx): pass def get_output(self, node, pctx): pass
4
2
8
2
4
2
1
0.92
1
0
0
0
3
0
3
3
34
9
13
6
9
12
13
6
9
2
1
1
4
365
20c/vaping
tests/test_timeseries.py
test_timeseries.TSDBTestPlugin
class TSDBTestPlugin(vaping.plugins.TimeSeriesDB): """ Test plugin from the TimeSeriesDB abstraction """ def __init__(self, config, ctx): super().__init__(config, ctx) self.updated = {} def create(self, filename): self.created = True def update(self, filename, time, value): self.updated[filename] = (time, value)
class TSDBTestPlugin(vaping.plugins.TimeSeriesDB): ''' Test plugin from the TimeSeriesDB abstraction ''' def __init__(self, config, ctx): pass def create(self, filename): pass def update(self, filename, time, value): pass
4
1
2
0
2
0
1
0.38
1
1
0
0
3
2
3
42
15
4
8
6
4
3
8
6
4
1
5
0
3
366
20c/vaping
tests/test_plugin.py
test_plugin.TimedPlugin0
class TimedPlugin0(plugins.TimedProbe): default_config = { "interval": "1m", "count": 5, "period": 20, } def probe(self): return []
class TimedPlugin0(plugins.TimedProbe): def probe(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
9
1
8
3
6
0
4
3
2
1
1
0
1
367
20c/vaping
tests/test_plugin.py
test_plugin.QueueTester
class QueueTester(plugins.ProbeBase): def probe(self): msg = self.new_message() return msg
class QueueTester(plugins.ProbeBase): def probe(self): pass
2
0
3
0
3
0
1
0
1
0
0
0
1
0
1
1
4
0
4
3
2
0
4
3
2
1
1
0
1
368
20c/vaping
tests/test_plugin.py
test_plugin.ProbePlugin1
class ProbePlugin1(plugins.ProbeBase): def probe(self): return []
class ProbePlugin1(plugins.ProbeBase): def probe(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
369
20c/vaping
tests/test_plugin.py
test_plugin.Plugin0
class Plugin0(plugins.PluginBase): pass
class Plugin0(plugins.PluginBase): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
370
20c/vaping
tests/test_plugin.py
test_plugin.EmitPluginStore
class EmitPluginStore(plugins.EmitBase): def init(self): super().init() self.store = [] def emit(self, message): self.store.append(message)
class EmitPluginStore(plugins.EmitBase): def init(self): pass def emit(self, message): pass
3
0
3
0
3
0
1
0
1
1
0
0
2
1
2
2
7
1
6
4
3
0
6
4
3
1
1
0
2
371
20c/vaping
tests/test_plugin.py
test_plugin.EmitPluginABC
class EmitPluginABC(plugins.EmitBase): # emit not defined to test TypeError pass
class EmitPluginABC(plugins.EmitBase): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
3
0
2
1
1
1
2
1
1
0
1
0
0
372
20c/vaping
src/vaping/plugins/logparse.py
vaping.plugins.logparse.AggregateSchema
class AggregateSchema(confu.schema.Schema): count = confu.schema.Int(help="Aggregate n lines")
class AggregateSchema(confu.schema.Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
373
20c/vaping
src/vaping/plugins/zeromq.py
vaping.plugins.zeromq.ZeroMQ
class ZeroMQ(vaping.plugins.EmitBase): """ plugin to emit json encoded messages via zeromq # Instanced Attributes - ctx (`zmq Context`) - sock (`zmq socket`) """ ConfigSchema = ZeroMQSchema def __init__(self, config, ctx): super().__init__(config, ctx) self.sock = None def init(self): self.log.debug("init zeromq ..") if not zmq: self.log.critical("missing zeromq, please install pyzmq to use this plugin") raise RuntimeError("zeromq python module not found") self.ctx = zmq.Context() # sanity check config if self.config.get("bind"): if self.config.get("connect"): msg = "bind and connect are mutually exclusive" self.log.critical(msg) raise ValueError(msg) elif not self.config.get("connect"): msg = "missing bind or connect" self.log.critical(msg) raise ValueError(msg) def on_start(self): self.sock = self.ctx.socket(PUB) if self.config.get("bind"): self.sock.bind(self.config["bind"]) elif self.config.get("connect"): self.sock.connect(self.config["connect"]) def on_stop(self): if self.sock: self.sock.close() def emit(self, message): self.sock.send_json(message) self.log.debug("msg" + str(message)) self.log.debug("[0MQ] sync send")
class ZeroMQ(vaping.plugins.EmitBase): ''' plugin to emit json encoded messages via zeromq # Instanced Attributes - ctx (`zmq Context`) - sock (`zmq socket`) ''' def __init__(self, config, ctx): pass def init(self): pass def on_start(self): pass def on_stop(self): pass def emit(self, message): pass
6
1
7
1
6
0
2
0.21
1
4
0
0
5
2
5
37
51
11
33
10
27
7
31
10
25
5
4
2
12
374
20c/vaping
src/vaping/plugins/whisper.py
vaping.plugins.whisper.WhisperSchema
class WhisperSchema(TimeSeriesDBSchema): """ Define a schema for FPing and also define defaults. """ retention = confu.schema.List(item=confu.schema.Str(), default=["3s:1d"]) x_files_factor = confu.schema.Float(default=0.5) aggregation_method = confu.schema.Str(default="average") sparse = confu.schema.Bool(default=False)
class WhisperSchema(TimeSeriesDBSchema): ''' Define a schema for FPing and also define defaults. '''
1
1
0
0
0
0
0
0.6
1
0
0
0
0
0
0
0
9
1
5
5
4
3
5
5
4
0
3
0
0
375
20c/vaping
tests/test_plugin.py
test_plugin.EmitPlugin0
class EmitPlugin0(plugins.EmitBase): def emit(self, message): pass
class EmitPlugin0(plugins.EmitBase): def emit(self, message): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
376
20c/vaping
src/vaping/plugins/vodka.py
vaping.plugins.vodka.VodkaSchema
class VodkaSchema(PluginConfigSchema): """ Define a schema for FPing and also define defaults. """ data = confu.schema.List(item=vaping.config.MixedDict()) apps = confu.schema.Dict(item=vaping.config.MixedDict()) plugins = confu.schema.List(item=vaping.config.MixedDict())
class VodkaSchema(PluginConfigSchema): ''' Define a schema for FPing and also define defaults. '''
1
1
0
0
0
0
0
0.75
1
0
0
0
0
0
0
0
8
1
4
4
3
3
4
4
3
0
2
0
0
377
20c/vaping
src/vaping/plugins/logparse.py
vaping.plugins.logparse.LogParse
class LogParse(vaping.plugins.FileProbe): r""" Log parse plugin base Will parse a log line by line and probe to emit data over a specified interval. # Config - path (`str`): log file path - fields (`dict`): field definition field name as key `parser` regex pattern to parse field value, needs to one group in it `type` value type (int, float etc.) `aggregate` how to aggregate the field if aggregation is turned on (sum, avg, eval) `eval` evaluate to create the value, other fields values will be available in the string formatting - time_parser (`dict`) if specified will be passed to strptime to generate a timestamp from the logline ``` time_parser: find: \d\d:\d\d:\d\d format: %H:%M:%S ``` - exclude (`list`): list of regex patterns that will cause lines to be excluded on match - include (`list`): list of regex patterns that will cause lines to be included on match - aggregate (`dict`): aggregation config -`count` aggregate n lines # Instance Attributes - stack (`list`) - fields (`dict`): field config - aggregate_count (`int`) - exclude (`list`) - include (`list`) - time_parser (`dict`) """ # default_config = {"fields": {}, "exclude": [], "include": [], "aggregate": {}} ConfigSchema = LogParseSchema def init(self): self.stack = [] self.fields = self.config.get("fields") self.aggregate_count = self.config.get("aggregate").get("count", 0) self.exclude = self.config.get("exclude", []) self.include = self.config.get("include", []) self.time_parser = self.config.get("time_parser") def parse_line(self, line): """ Here is where we parse values out of a single line read from the log and return a dict containg keys and values **Arguments** - line (`str`) """ # if a list of exclude patterns is specified # check if the line matches any of them # and ignore it if it does if self.exclude: for pattern in self.exclude: if re.search(pattern, line): return {} # if a list of include patterns is specified # check if the line matches any of them # and ignore it if it does not if self.include: matched = False for pattern in self.include: if re.search(pattern, line): matched = True break if not matched: return {} fields = self.config.get("fields", {}) data = {} for k, v in list(fields.items()): try: data[k] = self.parse_field_value(v, line) except (ValueError, TypeError) as exc: self.log.debug(str(exc)) return {} for k, v in list(fields.items()): if "eval" in v: data[k] = eval(v["eval"].format(**data)) if "type" in v: data[k] = self.validate_value(data[k], v["type"]) # print(k, data[k]) return data def parse_field_value(self, field, line): """ takes a field definition and a log line and attempts to parse out the field's value """ value = None # parse field value if "parser" in field: match = re.search(field["parser"], line) if not match: raise ValueError(f"Could not parse field value {field}\n{line}") value = match.group(1) # apply field type if "type" in field and value is not None: value = self.validate_value(value, field["type"]) return value def validate_value(self, value, typ): try: return __builtins__.get(typ).__call__(value) except AttributeError: validate = getattr(self, f"validate_{typ}", None) if validate: value = validate(value) else: raise def validate_elapsed(self, value): return self.validate_interval(value) def validate_interval(self, value): """ validates a string describing elapsed time or time duration **Arguments** - value (`str`): elapsed time (example: 1d2h) **Returns** seconds (`float`) """ return vaping.config.parse_interval(value) def aggregate(self, messages): """ Takes a list of messages and aggregates them according to aggration config **Arguments** - messagges (`list<dict>`) **Returns** list of aggregated messages (`list<dict>`) """ # aggregation is not turned on, just return # the messages as they are if not self.aggregate_count: return messages rv = [] # push messages onto stack self.stack = self.stack + messages # stack is still smaller than the aggregation count # return empty list if len(self.stack) < self.aggregate_count: return rv # while stack is bigger than the aggregation count # pop messages off the stack and aggregate while len(self.stack) >= self.aggregate_count: # pop first message in stack message = self.stack[0] self.stack.remove(self.stack[0]) # join data of other messages to first message # no aggregation yet for other in self.stack[: self.aggregate_count - 1]: message["data"].extend(other["data"]) self.stack.remove(self.stack[0]) # append multi-data message to result rv.append(message) # aggregate for message in rv: self.aggregate_message(message) return rv def aggregate_message(self, message): """ Takesa vaping message with multiple items in it's data property and aggregates that data **Arguments** - message (`dict`): vaping message dict """ # first data point is the main data point main = message["data"][0] # finalizers are applied after initial aggregation # we keep track of them here # TODO: move to class property finalizers = ["eval"] # aggregate for k, v in list(self.fields.items()): if v.get("aggregate") not in finalizers: main[k] = self.aggregate_field(k, message["data"]) # aggregate finalizers for k, v in list(self.fields.items()): if v.get("aggregate") in finalizers: main[k] = self.aggregate_field(k, message["data"]) # store number of aggregated messages in message data # at the `messages` key main["messages"] = len(message["data"]) # remove everything but the main data point from # the message message["data"] = [main] def aggregate_field(self, field_name, rows): """ takes a field name and a set of rows and will return an aggregated value this requires for the field to have it's `aggregate` config specified in the probe config **Arguments** - field_name (`str`) - rows (`list`) **Returns** aggregated value """ field = self.fields.get(field_name, {}) # no aggregator specified in field config # return the value of the last row as is if "aggregate" not in field: return rows[-1][field_name] # get aggregate function aggregate = getattr(self, "aggregate_{}".format(field.get("aggregate"))) r = aggregate(field_name, rows) return r def aggregate_sum(self, field_name, rows): """ Aggregate sum **Arguments** - field_name (`str`): field to aggregate - rows (`list`): list of vaping message data rows **Returns** sum """ c = 0 for row in rows: c = c + row.get(field_name, 0) return c def aggregate_eval(self, field_name, rows): """ Aggregate using an `eval()` result Needs to have `eval` set in the field config. Value will be passed straight to the `eval()` function so caution is advised. **Arguments** - field_name (`str`): field to aggregate - rows (`list`): list of vaping message data rows **Returns** eval result """ return eval(self.fields[field_name].get("eval").format(**rows[0])) def aggregate_avg(self, field_name, rows): """ Aggregate average value **Arguments** - field_name (`str`): field to aggregate - rows (`list`): list of vaping message data rows **Returns** avg (`float`) """ return self.aggregate_sum(field_name, rows) / len(rows) def parse_time(self, line): find = self.time_parser.get("find") fmt = self.time_parser.get("format") if not find or not fmt: raise ValueError( "time_parser needs to be a dict with `find` and `format` keys" ) time_string = re.search(find, line) if not time_string: raise ValueError(f"Could not find time string {find} in line {line}") dt = datetime.datetime.strptime(time_string.group(0), fmt) if dt.year == 1900: dt = dt.replace(year=datetime.datetime.now().year) return (dt - datetime.datetime(1970, 1, 1)).total_seconds() def process_line(self, line, data): """ The data dict represents the current emit object, depending on your interval multiple lines may be included in the same emit object. Should return the data object **Arguments** - line (`str`): log line - data (`dict`): current emit dict """ data = self.parse_line(line) if not data: return {} if self.time_parser: try: data.update(ts=self.parse_time(line)) except ValueError as exc: self.log.debug(exc) return {} return data def process_messages(self, messages): """ Process vaping messages before the are emitted Aggregation is handled here **Arguments** - messages (`list`): list of vaping messages **Returns** Result of self.aggregate """ for message in messages: if message["data"] and message["data"][0] and message["data"][0].get("ts"): message["ts"] = message["data"][0]["ts"] return self.aggregate(messages)
class LogParse(vaping.plugins.FileProbe): ''' Log parse plugin base Will parse a log line by line and probe to emit data over a specified interval. # Config - path (`str`): log file path - fields (`dict`): field definition field name as key `parser` regex pattern to parse field value, needs to one group in it `type` value type (int, float etc.) `aggregate` how to aggregate the field if aggregation is turned on (sum, avg, eval) `eval` evaluate to create the value, other fields values will be available in the string formatting - time_parser (`dict`) if specified will be passed to strptime to generate a timestamp from the logline ``` time_parser: find: \d\d:\d\d:\d\d format: %H:%M:%S ``` - exclude (`list`): list of regex patterns that will cause lines to be excluded on match - include (`list`): list of regex patterns that will cause lines to be included on match - aggregate (`dict`): aggregation config -`count` aggregate n lines # Instance Attributes - stack (`list`) - fields (`dict`): field config - aggregate_count (`int`) - exclude (`list`) - include (`list`) - time_parser (`dict`) ''' def init(self): pass def parse_line(self, line): ''' Here is where we parse values out of a single line read from the log and return a dict containg keys and values **Arguments** - line (`str`) ''' pass def parse_field_value(self, field, line): ''' takes a field definition and a log line and attempts to parse out the field's value ''' pass def validate_value(self, value, typ): pass def validate_elapsed(self, value): pass def validate_interval(self, value): ''' validates a string describing elapsed time or time duration **Arguments** - value (`str`): elapsed time (example: 1d2h) **Returns** seconds (`float`) ''' pass def aggregate(self, messages): ''' Takes a list of messages and aggregates them according to aggration config **Arguments** - messagges (`list<dict>`) **Returns** list of aggregated messages (`list<dict>`) ''' pass def aggregate_message(self, message): ''' Takesa vaping message with multiple items in it's data property and aggregates that data **Arguments** - message (`dict`): vaping message dict ''' pass def aggregate_field(self, field_name, rows): ''' takes a field name and a set of rows and will return an aggregated value this requires for the field to have it's `aggregate` config specified in the probe config **Arguments** - field_name (`str`) - rows (`list`) **Returns** aggregated value ''' pass def aggregate_sum(self, field_name, rows): ''' Aggregate sum **Arguments** - field_name (`str`): field to aggregate - rows (`list`): list of vaping message data rows **Returns** sum ''' pass def aggregate_eval(self, field_name, rows): ''' Aggregate using an `eval()` result Needs to have `eval` set in the field config. Value will be passed straight to the `eval()` function so caution is advised. **Arguments** - field_name (`str`): field to aggregate - rows (`list`): list of vaping message data rows **Returns** eval result ''' pass def aggregate_avg(self, field_name, rows): ''' Aggregate average value **Arguments** - field_name (`str`): field to aggregate - rows (`list`): list of vaping message data rows **Returns** avg (`float`) ''' pass def parse_time(self, line): pass def process_line(self, line, data): ''' The data dict represents the current emit object, depending on your interval multiple lines may be included in the same emit object. Should return the data object **Arguments** - line (`str`): log line - data (`dict`): current emit dict ''' pass def process_messages(self, messages): ''' Process vaping messages before the are emitted Aggregation is handled here **Arguments** - messages (`list`): list of vaping messages **Returns** Result of self.aggregate ''' pass
16
12
22
5
9
8
3
1.18
1
6
0
0
15
6
15
15
395
105
133
49
117
157
130
47
114
13
1
3
51
378
20c/vaping
src/vaping/plugins/whisper.py
vaping.plugins.whisper.WhisperPlugin
class WhisperPlugin(vaping.plugins.TimeSeriesDB): """ Whisper plugin that allows vaping to persist data in a whisper database """ ConfigSchema = WhisperSchema def __init__(self, config, ctx): if not whisper: raise ImportError("whisper not found") super().__init__(config, ctx) # whisper specific config self.retention = self.config.get("retention") self.x_files_factor = self.config.get("x_files_factor") self.aggregation_method = self.config.get("aggregation_method") self.sparse = self.config.get("sparse") def start(self): # build archives based on retention setting # NOTE: if retention is changed in config on an existing database # it will have to be rebuilt. self.archives = [whisper.parseRetentionDef(x) for x in self.retention] def create(self, filename): whisper.create( filename, self.archives, xFilesFactor=self.x_files_factor, aggregationMethod=self.aggregation_method, sparse=self.sparse, ) def update(self, filename, time, value): if value is None: return whisper.update(filename, value, time) def get(self, filename, from_time, to_time=None): (times, values) = whisper.fetch(filename, from_time, to_time) return times, values
class WhisperPlugin(vaping.plugins.TimeSeriesDB): ''' Whisper plugin that allows vaping to persist data in a whisper database ''' def __init__(self, config, ctx): pass def start(self): pass def create(self, filename): pass def update(self, filename, time, value): pass def get(self, filename, from_time, to_time=None): pass
6
1
6
0
5
1
1
0.3
1
2
0
0
5
5
5
5
43
8
27
13
21
8
21
13
15
2
1
1
7
379
20c/vaping
src/vaping/plugins/logparse.py
vaping.plugins.logparse.LogParseSchema
class LogParseSchema(PluginConfigSchema): """ Define a schema for FPing and also define defaults. """ fields = confu.schema.Dict(item=FieldSchema(), default={}, help="Field definition") time_parser = TimeParserSchema( help="If specified will be passed to strptime to generate a timestamp from the logline" ) exclude = confu.schema.List( item=confu.schema.Str(), default=[], help="list of regex patterns that will cause lines to be excluded on match", ) include = confu.schema.List( item=confu.schema.Str(), default=[], help="list of regex patterns that will cause lines to be included on match", ) aggregate = AggregateSchema(default={}, help="aggregation config")
class LogParseSchema(PluginConfigSchema): ''' Define a schema for FPing and also define defaults. '''
1
1
0
0
0
0
0
0.19
1
0
0
0
0
0
0
0
20
1
16
6
15
3
6
6
5
0
2
0
0
380
20c/vaping
src/vaping/plugins/logparse.py
vaping.plugins.logparse.TimeParserSchema
class TimeParserSchema(confu.schema.Schema): find = confu.schema.Str(help="Regex string to find timestamps.") format = confu.schema.Str(help="Datetime format to output timestamps.")
class TimeParserSchema(confu.schema.Schema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
2
2
0
3
2
2
0
1
0
0
381
20c/vaping
src/vaping/plugins/zeromq.py
vaping.plugins.zeromq.ZeroMQSchema
class ZeroMQSchema(vaping.plugins.PluginConfigSchema): bind = confu.schema.Str(default="") connect = confu.schema.Str(default="")
class ZeroMQSchema(vaping.plugins.PluginConfigSchema): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
3
0
3
3
2
0
3
3
2
0
2
0
0
382
20c/vaping
src/vaping/plugins/rrd.py
vaping.plugins.rrd.RRDToolPlugin
class RRDToolPlugin(vaping.plugins.TimeSeriesDB): """ RRDTool plugin that allows vaping to persist data in a rrdtool database """ ConfigSchema = RRDToolSchema def __init__(self, config, ctx): if not rrdtool: raise ImportError("rrdtool not found") super().__init__(config, ctx) def init(self): # rrdtool specific config self.data_sources = self.config.get("data_sources") self.archives = self.config.get("archives") self.step = self.config.get("step") def create(self, filename): rrdtool.create( filename, "--step", str(self.step), self.data_sources, *self.archives ) def update(self, filename, time, value): if value is None: return rrdtool.update(filename, "%d:%.4f" % (time, value))
class RRDToolPlugin(vaping.plugins.TimeSeriesDB): ''' RRDTool plugin that allows vaping to persist data in a rrdtool database ''' def __init__(self, config, ctx): pass def init(self): pass def create(self, filename): pass def update(self, filename, time, value): pass
5
1
4
0
4
0
2
0.28
1
3
0
0
4
3
4
4
29
6
18
9
13
5
16
9
11
2
1
1
6
383
20c/vaping
src/vaping/plugins/rrd.py
vaping.plugins.rrd.RRDToolSchema
class RRDToolSchema(TimeSeriesDBSchema): """ Define a schema for FPing and also define defaults. """ step = confu.schema.Int(required=True, help="Passed to rrd tool --step option.") data_sources = confu.schema.List(item=confu.schema.Str(), default=[], help="") archives = confu.schema.List(item=confu.schema.Str(), default=[])
class RRDToolSchema(TimeSeriesDBSchema): ''' Define a schema for FPing and also define defaults. '''
1
1
0
0
0
0
0
0.75
1
0
0
0
0
0
0
0
8
1
4
4
3
3
4
4
3
0
3
0
0
384
20c/vaping
src/vaping/plugins/vodka.py
vaping.plugins.vodka.VodkaPlugin
class VodkaPlugin(vaping.plugins.EmitBase): """ Plugin that emits to vodka data """ # starting vodka automatically when vaping is spinning # up all the plugins causes some inconsistent behaviour # in daemon mode, so we allow it to lazy start for now # # TODO: might need to revisit later lazy_start = True # Define config schema ConfigSchema = VodkaSchema def init(self): self._is_started = False def start(self): if self._is_started: return # deep copy vodka plugin config and prepare to pass # to vodka as it's own copy with type and name keys # removed vodka_config = copy.deepcopy(self.config) if "name" in vodka_config: del vodka_config["name"] if "type" in vodka_config: del vodka_config["type"] self._is_started = True vodka.run(vodka_config, self.vaping.config) if graphsrv: # if graphsrv is installed proceed to generate # target configurations for it from probe config for node in self.vaping.config.get("probes", []): probe = vaping.plugin.get_probe(node, self.vaping) probe_to_graphsrv(probe) def emit(self, message): if not self._is_started: self.start() vodka.data.handle( message.get("type"), message, data_id=message.get("source"), caller=self )
class VodkaPlugin(vaping.plugins.EmitBase): ''' Plugin that emits to vodka data ''' def init(self): pass def start(self): pass def emit(self, message): pass
4
1
11
2
7
2
3
0.56
1
0
0
0
3
1
3
3
51
12
25
10
21
14
23
10
19
6
1
2
9
385
20c/vaping
src/vaping/plugins/prometheus.py
vaping.plugins.prometheus.Prometheus
class Prometheus(vaping.plugins.EmitBase): def init(self): self.log.debug("init prometheus plugin") port = self.pluginmgr_config.get("port", 9099) start_http_server(port) def emit(self, data): raw_data = data.get("data") self.log.debug("data: " + str(raw_data)) for host_data in raw_data: if host_data is None: continue host_name = host_data.get("host") if "min" in host_data: min_latency.labels(host_name).observe(host_data.get("min")) if "max" in host_data: max_latency.labels(host_name).observe(host_data.get("max")) if "avg" in host_data: avg_latency.labels(host_name).observe(host_data.get("avg")) sent_packets.labels(host_name).inc(host_data.get("cnt")) packet_loss.labels(host_name).set(host_data.get("loss") * 100)
class Prometheus(vaping.plugins.EmitBase): def init(self): pass def emit(self, data): pass
3
0
11
1
10
0
4
0
1
1
0
0
2
0
2
34
23
3
20
7
17
0
20
7
17
6
4
2
7
386
20c/vodka
src/vodka/config/configurator.py
vodka.config.configurator.Configurator
class Configurator: """ Handles interactive configuration process guided by specs defined via config Handler classes Attributes: plugin_manager (ConfigPluginManager): plugin manager instance to use during plugin configuration skip_defaults (bool): if True dont prompt for config variables that have a default value assigned action_required (list): will hold list of actions required after configure call has been completed (if any) """ def __init__(self, plugin_manager, skip_defaults=False): self.plugin_manager = plugin_manager self.action_required = [] self.skip_defaults = skip_defaults def configure(self, cfg, handler, path=""): """ Start configuration process for the provided handler Args: cfg (dict): config container handler (config.Handler class): config handler to use path (str): current path in the configuration progress """ # configure simple value attributes (str, int etc.) for name, attr in handler.attributes(): if cfg.get(name) is not None: continue if attr.expected_type not in [list, dict]: cfg[name] = self.set(handler, attr, name, path, cfg) elif attr.default is None and not hasattr(handler, "configure_%s" % name): self.action_required.append( (f"{path}.{name}: {attr.help_text}").strip(".") ) # configure attributes that have complex handlers defined # on the config Handler class (class methods prefixed by # configure_ prefix for name, attr in handler.attributes(): if cfg.get(name) is not None: continue if hasattr(handler, "configure_%s" % name): fn = getattr(handler, "configure_%s" % name) fn(self, cfg, f"{path}.{name}") if attr.expected_type in [list, dict] and not cfg.get(name): try: del cfg[name] except KeyError: pass def set(self, handler, attr, name, path, cfg): """ Obtain value for config variable, by prompting the user for input and substituting a default value if needed. Also does validation on user input """ full_name = (f"{path}.{name}").strip(".") # obtain default value if attr.default is None: default = None else: try: comp = vodka.component.Component(cfg) default = handler.default(name, inst=comp) if self.skip_defaults: self.echo(f"{full_name}: {default} [default]") return default except Exception: raise # render explanation self.echo("") self.echo(attr.help_text) if attr.choices: self.echo("choices: %s" % ", ".join([str(c) for c in attr.choices])) # obtain user input and validate until input is valid b = False while not b: try: if type(attr.expected_type) == type: r = self.prompt(full_name, default=default, type=attr.expected_type) r = attr.expected_type(r) else: r = self.prompt(full_name, default=default, type=str) except ValueError: self.echo("Value expected to be of type %s" % attr.expected_type) try: b = handler.check({name: r}, name, path) except Exception as inst: if hasattr(inst, "explanation"): self.echo(inst.explanation) else: raise return r def echo(self, message): """override this function with something that echos a message to the user""" pass def prompt(self, *args, **kwargs): """override this function to prompt for user input""" return None
class Configurator: ''' Handles interactive configuration process guided by specs defined via config Handler classes Attributes: plugin_manager (ConfigPluginManager): plugin manager instance to use during plugin configuration skip_defaults (bool): if True dont prompt for config variables that have a default value assigned action_required (list): will hold list of actions required after configure call has been completed (if any) ''' def __init__(self, plugin_manager, skip_defaults=False): pass def configure(self, cfg, handler, path=""): ''' Start configuration process for the provided handler Args: cfg (dict): config container handler (config.Handler class): config handler to use path (str): current path in the configuration progress ''' pass def set(self, handler, attr, name, path, cfg): ''' Obtain value for config variable, by prompting the user for input and substituting a default value if needed. Also does validation on user input ''' pass def echo(self, message): '''override this function with something that echos a message to the user''' pass def prompt(self, *args, **kwargs): '''override this function to prompt for user input''' pass
6
5
19
2
13
4
5
0.49
0
7
0
2
5
3
5
5
114
17
65
17
59
32
59
16
53
10
0
4
23
387
20c/vodka
src/vodka/config/__init__.py
vodka.config.Attribute
class Attribute: """ A configuration attribute """ def __init__(self, expected_type, **kwargs): """ Args: expected_type (class or function): type expected for this attribute, if specified as a function the result of the function will determine whether or not the value passed type validation. Kwargs: default: if specified this value will be used as a default value, if not specified then configuration of this attribute is treated as mandatory help_text (str): explains the attribute choices (list): list of valid value choices for this attribute, if set any value not matching any of the choices will raise a configuration error handler (function): when the value for this attribute is a collection of configuration attributes (e.g. nested config) use this function to return the aproporiate config handler class to use to validate them prepare (function): allows you to prepare value for this attribute deprecated (str): if not None indicates that this attribute is still functional but deprecated and will be removed in the vodka version specified in the value """ self.expected_type = expected_type self.default = kwargs.get("default") self.help_text = kwargs.get("help_text") self.handler = kwargs.get("handler") self.choices = kwargs.get("choices") self.prepare = kwargs.get("prepare", []) self.deprecated = kwargs.get("deprecated", False) self.nested = kwargs.get("nested", 0) self.field = kwargs.get("field") def finalize(self, cfg, key_name, value, **kwargs): pass def preload(self, cfg, key_name, **kwargs): pass
class Attribute: ''' A configuration attribute ''' def __init__(self, expected_type, **kwargs): ''' Args: expected_type (class or function): type expected for this attribute, if specified as a function the result of the function will determine whether or not the value passed type validation. Kwargs: default: if specified this value will be used as a default value, if not specified then configuration of this attribute is treated as mandatory help_text (str): explains the attribute choices (list): list of valid value choices for this attribute, if set any value not matching any of the choices will raise a configuration error handler (function): when the value for this attribute is a collection of configuration attributes (e.g. nested config) use this function to return the aproporiate config handler class to use to validate them prepare (function): allows you to prepare value for this attribute deprecated (str): if not None indicates that this attribute is still functional but deprecated and will be removed in the vodka version specified in the value ''' pass def finalize(self, cfg, key_name, value, **kwargs): pass def preload(self, cfg, key_name, **kwargs): pass
4
2
11
1
5
6
1
1.4
0
0
0
1
3
9
3
3
42
6
15
13
11
21
15
13
11
1
0
0
3
388
20c/vodka
src/vodka/config/__init__.py
vodka.config.InstanceHandler
class InstanceHandler(Handler): """ This is the config handler for the vodka main config """ apps = Attribute( dict, help_text="Holds the registered applications", default={}, handler=lambda k, v: vodka.app.get_application(k), ) plugins = Attribute( list, help_text="Holds the registered plugins", default=[], handler=lambda k, v: vodka.plugin.get_plugin_class(v.get("type")), ) data = Attribute(list, help_text="Data type configuration", default=[]) logging = Attribute( dict, help_text="Python logger configuration", default={"version": 1} ) @classmethod def configure_plugins(cls, configurator, cfg, path): configurator.echo("") configurator.echo("Configure plugins") configurator.echo("") plugin_type = configurator.prompt("Add plugin", default="skip") if "plugins" not in cfg: cfg["plugins"] = [] while plugin_type != "skip": plugin_name = configurator.prompt("Name", default=plugin_type) try: plugin_class = configurator.plugin_manager.get_plugin_class(plugin_type) plugin_cfg = {"type": plugin_type, "name": plugin_name} configurator.configure( plugin_cfg, plugin_class.Configuration, path=f"{path}.{plugin_name}", ) cfg["plugins"].append(plugin_cfg) except Exception as inst: configurator.echo(inst) plugin_type = configurator.prompt("Add plugin", default="skip") @classmethod def configure_apps(cls, configurator, cfg, path): configurator.echo("") configurator.echo("Configure applications") configurator.echo("") if "apps" not in cfg: cfg["apps"] = {} name = configurator.prompt("Add application (name)", default="skip") while name != "skip": app_cfg = {} configurator.configure( app_cfg, vodka.app.Application.Configuration, path=f"{path}.{name}" ) vodka.app.load(name, app_cfg) app = vodka.app.get_application(name) configurator.configure(app_cfg, app.Configuration, path=f"{path}.{name}") cfg["apps"][name] = app_cfg name = configurator.prompt("Add application (name)", default="skip")
class InstanceHandler(Handler): ''' This is the config handler for the vodka main config ''' @classmethod def configure_plugins(cls, configurator, cfg, path): pass @classmethod def configure_apps(cls, configurator, cfg, path): pass
5
1
21
2
19
0
4
0.05
1
3
2
0
0
0
2
8
67
7
57
17
52
3
37
14
34
4
1
2
7
389
20c/vodka
src/vodka/config/__init__.py
vodka.config.Handler
class Handler: """ Can be attached to any vodka application class or vodka plugin and allows to setup default values and config sanity checking """ @classmethod def check(cls, cfg, key_name, path, parent_cfg=None): """ Checks that the config values specified in key name is sane according to config attributes defined as properties on this class """ attr = cls.get_attr_by_name(key_name) if path != "": attr_full_name = f"{path}.{key_name}" else: attr_full_name = key_name if not attr: # attribute specified by key_name is unknown, warn raise vodka.exceptions.ConfigErrorUnknown(attr_full_name) if attr.deprecated: vodka.log.warn( "[config deprecated] {} is being deprecated in version {}".format( attr_full_name, attr.deprecated ) ) # prepare data for prepare in attr.prepare: cfg[key_name] = prepare(cfg[key_name]) if hasattr(cls, "prepare_%s" % key_name): prepare = getattr(cls, "prepare_%s" % key_name) cfg[key_name] = prepare(cfg[key_name], config=cfg) value = cfg.get(key_name) if isinstance(attr.expected_type, types.FunctionType): # expected type holds a validator function p, reason = attr.expected_type(value) if not p: # validator did not pass raise vodka.exceptions.ConfigErrorValue( attr_full_name, attr, value, reason=reason ) elif attr.expected_type != type(value): # attribute type mismatch raise vodka.exceptions.ConfigErrorType(attr_full_name, attr) if attr.choices and value not in attr.choices: # attribute value not valid according to # available choices raise vodka.exceptions.ConfigErrorValue(attr_full_name, attr, value) if hasattr(cls, "validate_%s" % key_name): # custom validator for this attribute was found validator = getattr(cls, "validate_%s" % key_name) valid, reason = validator(value) if not valid: # custom validator failed raise vodka.exceptions.ConfigErrorValue( attr_full_name, attr, value, reason=reason ) num_crit = 0 num_warn = 0 if is_config_container(value) and attr.handler: if type(value) == dict or issubclass(type(value), Config): keys = list(value.keys()) elif type(value) == list: keys = list(range(0, len(value))) else: return for k in keys: if not is_config_container(value[k]): continue handler = attr.handler(k, value[k]) if issubclass(handler, Handler): h = handler else: h = getattr(handler, "Configuration", None) # h = getattr(attr.handler(k, value[k]), "Configuration", None) if h: if ( type(k) == int and type(value[k]) == dict and value[k].get("name") ): _path = "{}.{}".format(attr_full_name, value[k].get("name")) else: _path = f"{attr_full_name}.{k}" _num_crit, _num_warn = h.validate( value[k], path=_path, nested=attr.nested, parent_cfg=cfg ) h.finalize( value, k, value[k], attr=attr, attr_name=key_name, parent_cfg=cfg, ) num_crit += _num_crit num_warn += _num_warn attr.finalize(cfg, key_name, value, num_crit=num_crit) return (num_crit, num_warn) @classmethod def finalize(cls, cfg, key_name, value, **kwargs): """ Will be called after validation for a config variable is completed """ pass @classmethod def validate(cls, cfg, path="", nested=0, parent_cfg=None): """ Validates a section of a config dict. Will automatically validate child sections as well if their attribute pointers are instantiated with a handler property """ # number of critical errors found num_crit = 0 # number of non-critical errors found num_warn = 0 # check for missing keys in the config for name in dir(cls): if nested > 0: break try: attr = cls.get_attr_by_name(name) if isinstance(attr, Attribute): if attr.default is None and name not in cfg: # no default value defined, which means its required # to be set in the config file if path: attr_full_name = f"{path}.{name}" else: attr_full_name = name raise vodka.exceptions.ConfigErrorMissing(attr_full_name, attr) attr.preload(cfg, name) except vodka.exceptions.ConfigErrorMissing as inst: if inst.level == "warn": vodka.log.warn(inst.explanation) num_warn += 1 elif inst.level == "critical": vodka.log.error(inst.explanation) num_crit += 1 if type(cfg) in [dict, Config]: keys = list(cfg.keys()) if nested > 0: for _k, _v in list(cfg.items()): _num_crit, _num_warn = cls.validate( _v, path=(f"{path}.{_k}"), nested=nested - 1, parent_cfg=cfg ) num_crit += _num_crit num_warn += _num_warn return num_crit, num_warn elif type(cfg) == list: keys = list(range(0, len(cfg))) else: raise ValueError("Cannot validate non-iterable config value") # validate existing keys in the config for key in keys: try: _num_crit, _num_warn = cls.check(cfg, key, path) num_crit += _num_crit num_warn += _num_warn except ( vodka.exceptions.ConfigErrorUnknown, vodka.exceptions.ConfigErrorValue, vodka.exceptions.ConfigErrorType, ) as inst: if inst.level == "warn": vodka.log.warn(inst.explanation) num_warn += 1 elif inst.level == "critical": vodka.log.error(inst.explanation) num_crit += 1 return num_crit, num_warn @classmethod def get_attr_by_name(cls, name): """ Return attribute by name - will consider value in attribute's `field` property """ for attr_name, attr in cls.attributes(): if attr_name == name: return attr return None @classmethod def default(cls, key_name, inst=None): attr = cls.get_attr_by_name(key_name) if not attr: raise KeyError("No config attribute defined with the name '%s'" % key_name) if attr.default and callable(attr.default): return attr.default(key_name, inst) return attr.default @classmethod def attributes(cls): """ yields tuples for all attributes defined on this handler tuple yielded: name (str), attribute (Attribute) """ for k in dir(cls): v = getattr(cls, k) if isinstance(v, Attribute): name = v.field or k yield name, v
class Handler: ''' Can be attached to any vodka application class or vodka plugin and allows to setup default values and config sanity checking ''' @classmethod def check(cls, cfg, key_name, path, parent_cfg=None): ''' Checks that the config values specified in key name is sane according to config attributes defined as properties on this class ''' pass @classmethod def finalize(cls, cfg, key_name, value, **kwargs): ''' Will be called after validation for a config variable is completed ''' pass @classmethod def validate(cls, cfg, path="", nested=0, parent_cfg=None): ''' Validates a section of a config dict. Will automatically validate child sections as well if their attribute pointers are instantiated with a handler property ''' pass @classmethod def get_attr_by_name(cls, name): ''' Return attribute by name - will consider value in attribute's `field` property ''' pass @classmethod def default(cls, key_name, inst=None): pass @classmethod def attributes(cls): ''' yields tuples for all attributes defined on this handler tuple yielded: name (str), attribute (Attribute) ''' pass
13
6
36
4
25
7
8
0.28
0
13
6
11
0
0
6
6
236
33
159
43
146
44
115
36
108
20
0
5
47
390
20c/vodka
src/vodka/config/__init__.py
vodka.config.Config
class Config(munge.Config): defaults = {"config": {}, "config_dir": "~/.vodka", "codec": "yaml"} def read(self, config_dir=None, clear=False, config_file=None): """ The munge Config's read function only allows to read from a config directory, but we also want to be able to read straight from a config file as well """ if config_file: data_file = os.path.basename(config_file) data_path = os.path.dirname(config_file) if clear: self.clear() config = munge.load_datafile(data_file, data_path, default=None) if not config: raise OSError("Config file not found: %s" % config_file) munge.util.recursive_update(self.data, config) self._meta_config_dir = data_path return else: return super().read(config_dir=config_dir, clear=clear)
class Config(munge.Config): def read(self, config_dir=None, clear=False, config_file=None): ''' The munge Config's read function only allows to read from a config directory, but we also want to be able to read straight from a config file as well ''' pass
2
1
24
5
14
5
4
0.31
1
2
0
0
1
1
1
1
27
6
16
7
14
5
15
7
13
4
1
2
4
391
20c/vodka
src/vodka/config/__init__.py
vodka.config.ComponentHandler
class ComponentHandler(Handler): """ This is the base config handler that will be attached to any vodka application or plugin """ # config attribute: enabled enabled = Attribute( bool, default=True, help_text="specifies whether or not this component should be initialized and started", )
class ComponentHandler(Handler): ''' This is the base config handler that will be attached to any vodka application or plugin ''' pass
1
1
0
0
0
0
0
0.83
1
0
0
3
0
0
0
6
13
2
6
2
5
5
2
2
1
0
1
0
0
392
20c/vodka
src/vodka/component.py
vodka.component.Component
class Component(vodka.log.LoggerMixin): """ Basic vodka component, all applications and plugins extend this class Attributes: handle (str): unique component handle, override this when extending Classes: Configuration (vodka.config.ComponentHandler): Configuration Handler """ handle = "base" class Configuration(vodka.config.ComponentHandler): pass def __init__(self, config): self.config = config @property def home(self): """absolute path to the project home directory""" return self.get_config("home") def get_config(self, key_name): """ Return configuration value Args: key_name (str): configuration key Returns: The value for the specified configuration key, or if not found in the config the default value specified in the Configuration Handler class specified inside this component """ if key_name in self.config: return self.config.get(key_name) return self.Configuration.default(key_name, inst=self) def resource(self, path): """ Return absolute path to resource Args: path (str): relative path to resource from project home Returns: str - absolute path to project resource """ return os.path.join(self.home, path)
class Component(vodka.log.LoggerMixin): ''' Basic vodka component, all applications and plugins extend this class Attributes: handle (str): unique component handle, override this when extending Classes: Configuration (vodka.config.ComponentHandler): Configuration Handler ''' class Configuration(vodka.config.ComponentHandler): def __init__(self, config): pass @property def home(self): '''absolute path to the project home directory''' pass def get_config(self, key_name): ''' Return configuration value Args: key_name (str): configuration key Returns: The value for the specified configuration key, or if not found in the config the default value specified in the Configuration Handler class specified inside this component ''' pass def resource(self, path): ''' Return absolute path to resource Args: path (str): relative path to resource from project home Returns: str - absolute path to project resource ''' pass
7
4
8
1
3
4
1
1.67
1
1
1
4
4
1
4
5
54
14
15
9
8
25
14
8
8
2
1
1
5
393
20c/vodka
tests/test_start.py
tests.test_start.TimedPlugin
class TimedPlugin(vodka.plugins.TimedPlugin): def init(self): self.counter = 0 self.setup_done = False def setup(self): self.setup_done = True def work(self): self.counter += 1
class TimedPlugin(vodka.plugins.TimedPlugin): def init(self): pass def setup(self): pass def work(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
2
3
19
10
2
8
6
4
0
8
6
4
1
4
0
3
394
20c/vodka
src/vodka/app.py
vodka.app.WebApplication
class WebApplication(TemplatedApplication): """ Application wrapper for serving content via a web server. """ # Configuration handler class Configuration(TemplatedApplication.Configuration): includes = vodka.config.shared.Container( dict, default={}, nested=1, share="includes:merge", handler=lambda x, y: vodka.config.shared.Routers( dict, "includes:merge", handler=SharedIncludesConfigHandler ), help_text="allows you to specify extra media includes for js,css etc.", ) # class methods and properties @property def includes(self): """return includes from config""" r = { k: sorted(list(copy.deepcopy(v).values()), key=lambda x: x.get("order", 0)) for k, v in list(self.get_config("includes").items()) } if self.version is not None: for k, v in list(r.items()): for j in v: j["path"] = self.versioned_url(j["path"]) return r def render(self, tmpl_name, request_env): """ Render the specified template and return the output. Args: tmpl_name (str): file name of the template request_env (dict): request environment Returns: str - the rendered template """ return super().render(tmpl_name, request_env)
class WebApplication(TemplatedApplication): ''' Application wrapper for serving content via a web server. ''' class Configuration(TemplatedApplication.Configuration): @property def includes(self): '''return includes from config''' pass def render(self, tmpl_name, request_env): ''' Render the specified template and return the output. Args: tmpl_name (str): file name of the template request_env (dict): request environment Returns: str - the rendered template ''' pass
5
3
12
2
6
5
3
0.56
1
2
0
2
2
0
2
15
48
9
25
8
20
14
12
7
8
4
4
3
5
395
20c/vodka
src/vodka/app.py
vodka.app.TemplatedApplication
class TemplatedApplication(Application): """ Application wrapper for an application that is using templates to build it's output """ class Configuration(Application.Configuration): templates = vodka.config.Attribute( vodka.config.validators.path, default=lambda k, i: i.resource(k), help_text="location of your template files", ) template_locations = vodka.config.Attribute( list, default=[], help_text="allows you to specify additional paths to load templates from", ) template_engine = vodka.config.Attribute( str, default="jinja2", choices=["jinja2"], help_text="template engine to use to render your templates", ) @property def template_path(self): """absolute path to template directory""" return self.get_config("templates") def versioned_url(self, path): # FIXME: needs a more bulletproof solution so it works with paths # that already have query parameters attached etc. if self.version is None: return path if not re.match("^%s/.*" % self.handle, path): return path return f"{path}?v={self.version}" def versioned_path(self, path): return re.sub("^%s/" % self.handle, "%s/" % self.versioned_handle(), path) def render(self, tmpl_name, context_env): """ Render the specified template and return the output. Args: tmpl_name (str): file name of the template context_env (dict): context environment Returns: str - the rendered template """ return self.tmpl._render(tmpl_name, context_env) def setup(self): import tmpl # set up the template engine eng = tmpl.get_engine(self.config.get("template_engine", "jinja2")) template_locations = [] # we want tp search additional template location specified # in this app's config for path in self.get_config("template_locations"): if os.path.exists(path): self.log.debug( f"Template location added for application '{self.handle}': {path}" ) template_locations.append(path) # we want to search for template overrides in other app instances # that provide templates, by checking if they have a subdir in # their template directory that matches this app's handle for name, inst in list(vodka.instance.instances.items()): if inst == self: continue if hasattr(inst, "template_path"): path = os.path.join(inst.template_path, self.handle) if os.path.exists(path): self.log.debug( f"Template location added for application '{self.handle}' via application '{inst.handle}': {path}" ) template_locations.append(path) # finally we add this apps template path to the template locations template_locations.append(self.template_path) self.tmpl = eng(search_path=template_locations)
class TemplatedApplication(Application): ''' Application wrapper for an application that is using templates to build it's output ''' class Configuration(Application.Configuration): @property def template_path(self): '''absolute path to template directory''' pass def versioned_url(self, path): pass def versioned_path(self, path): pass def render(self, tmpl_name, context_env): ''' Render the specified template and return the output. Args: tmpl_name (str): file name of the template context_env (dict): context environment Returns: str - the rendered template ''' pass def setup(self): pass
8
3
12
2
7
4
3
0.42
1
1
0
3
5
1
5
13
92
17
53
17
44
22
35
16
27
7
3
3
13
396
20c/vodka
src/vodka/app.py
vodka.app.SharedIncludesConfigHandler
class SharedIncludesConfigHandler(vodka.config.shared.RoutersHandler): path = vodka.config.Attribute( str, help_text="relative path (to the app's static directory) of the file to be included", ) order = vodka.config.Attribute( int, default=0, help_text="loading order, higher numbers will be loaded after lower numbers", )
class SharedIncludesConfigHandler(vodka.config.shared.RoutersHandler): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
7
11
1
10
3
9
0
3
3
2
0
2
0
0
397
20c/vodka
src/vodka/app.py
vodka.app.Application
class Application(vodka.component.Component): """ Base application class Attributes: handle (str): unique handle for the application, override when extending """ handle = "base" version = None class Configuration(vodka.component.Component.Configuration): home = vodka.config.Attribute( vodka.config.validators.path, default="", help_text="absolute path to application directory. you can ignore this if application is to be loaded from an installed python package.", ) module = vodka.config.Attribute( str, default="", help_text="name of the python module containing this application (usually <namespace>.application)", ) requires = vodka.config.Attribute( list, default=[], help_text="list of vodka apps required by this app" ) @classmethod def versioned_handle(cls): if cls.version is None: return cls.handle return f"{cls.handle}/{cls.version}" def __init__(self, config=None, config_dir=None): """ Kwargs: config (dict or MungeConfig): configuration object, note that either this or config_dir need to be specified. config_dir (str): path to config directory, will attempt to read into a new MungeConfig instance from there. """ if config: if config_dir: raise ValueError("config and config_sir are mutually exclusive") elif config_dir: config = config.Config(read=config_dir) else: raise ValueError("No configuration specified") super().__init__(config) def setup(self): """ Soft initialization method with no arguments that can easily be overwritten by extended classes """ pass
class Application(vodka.component.Component): ''' Base application class Attributes: handle (str): unique handle for the application, override when extending ''' class Configuration(vodka.component.Component.Configuration): @classmethod def versioned_handle(cls): pass def __init__(self, config=None, config_dir=None): ''' Kwargs: config (dict or MungeConfig): configuration object, note that either this or config_dir need to be specified. config_dir (str): path to config directory, will attempt to read into a new MungeConfig instance from there. ''' pass def setup(self): ''' Soft initialization method with no arguments that can easily be overwritten by extended classes ''' pass
6
3
10
1
5
4
2
0.52
1
2
0
10
2
0
3
8
60
10
33
11
27
17
20
10
15
4
2
2
7
398
20c/vodka
tests/test_wsgi.py
tests.test_wsgi.WSGIPlugin
class WSGIPlugin(vodka.plugins.wsgi.WSGIPlugin): routes = {} def set_route(self, path, target, methods=None): self.routes[path] = {"target": target, "methods": methods or []}
class WSGIPlugin(vodka.plugins.wsgi.WSGIPlugin): def set_route(self, path, target, methods=None): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
22
5
1
4
3
2
0
4
3
2
1
4
0
1
399
20c/vodka
tests/test_wsgi.py
tests.test_wsgi.WSGIApp
class WSGIApp(vodka.app.Application): def a(self): return "a" def b(self): return "b"
class WSGIApp(vodka.app.Application): def a(self): pass def b(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
10
6
1
5
3
2
0
5
3
2
1
3
0
2