Debian Codegraph @

ipaserver/custodia/server/__init__.py

raw
1 # Copyright (C) 2015 Custodia Project Contributors - see LICENSE file
2 from __future__ import absolute_import
3
4 import importlib
5 import importlib.metadata
6 import os
7
8 import six
9
10 from ipaserver.custodia import log
11 from ipaserver.custodia.httpd.server import HTTPServer
12
13 from .args import default_argparser
14 from .args import parse_args as _parse_args
15 from .config import parse_config as _parse_config
16
17 logger = log.getLogger('custodia')
18
19 __all__ = ['default_argparser', 'main']
20
21
22 def attach_store(typename, plugins, stores):
23 for name, c in six.iteritems(plugins):
24 if getattr(c, 'store_name', None) is None:
25 continue
26 try:
27 c.store = stores[c.store_name]
28 except KeyError:
29 raise ValueError('[%s%s] references unexisting store '
30 '"%s"' % (typename, name, c.store_name))
31
32
33 def _load_plugin_class(menu, name):
34 """Load Custodia plugin
35
36 Entry points are preferred over dotted import path.
37 """
38 group = 'custodia.{}'.format(menu)
39 eps = importlib.metadata.entry_points(group=group, name=name)
40 if len(eps) > 1:
41 raise ValueError(
42 "Multiple entry points for {} {}: {}".format(menu, name, eps))
43 elif len(eps) == 1:
44 ep, *_ = eps
45 return ep.load(require=False)
46 elif '.' in name:
47 # fall back to old style dotted name
48 module, classname = name.rsplit('.', 1)
49 m = importlib.import_module(module)
50 return getattr(m, classname)
51 else:
52 raise ValueError("{}: {} not found".format(menu, name))
53
54
55 def _create_plugin(cfgparser, section, menu):
56 if not cfgparser.has_option(section, 'handler'):
57 raise ValueError('Invalid section, missing "handler"')
58
59 handler_name = cfgparser.get(section, 'handler')
60 hconf = {'facility_name': section}
61 try:
62 handler = _load_plugin_class(menu, handler_name)
63 classname = handler.__name__
64 hconf['facility_name'] = '%s-[%s]' % (classname, section)
65 except Exception as e:
66 raise ValueError('Invalid format for "handler" option '
67 '[%r]: %s' % (e, handler_name))
68
69 if handler._options is not None:
70 # new-style plugin with parser and section
71 plugin = handler(cfgparser, section)
72 else:
73 # old-style plugin with config dict
74 hconf.update(cfgparser.items(section))
75 hconf.pop('handler')
76 plugin = handler(hconf)
77 plugin.section = section
78 return plugin
79
80
81 def _load_plugins(config, cfgparser):
82 """Load and initialize plugins
83 """
84 # set umask before any plugin gets a chance to create a file
85 os.umask(config['umask'])
86
87 for s in cfgparser.sections():
88 if s in {'ENV', 'global'}:
89 # ENV section is only used for interpolation
90 continue
91
92 if s.startswith('/'):
93 menu = 'consumers'
94 path_chain = s.split('/')
95 if path_chain[-1] == '':
96 path_chain = path_chain[:-1]
97 name = tuple(path_chain)
98 else:
99 if s.startswith('auth:'):
100 menu = 'authenticators'
101 name = s[5:]
102 elif s.startswith('authz:'):
103 menu = 'authorizers'
104 name = s[6:]
105 elif s.startswith('store:'):
106 menu = 'stores'
107 name = s[6:]
108 else:
109 raise ValueError('Invalid section name [%s].\n' % s)
110
111 try:
112 config[menu][name] = _create_plugin(cfgparser, s, menu)
113 except Exception as e:
114 logger.debug("Plugin '%s' failed to load.", name, exc_info=True)
115 raise RuntimeError(menu, name, e)
116
117 # 2nd initialization stage
118 for menu in ['authenticators', 'authorizers', 'consumers', 'stores']:
119 plugins = config[menu]
120 for name in sorted(plugins):
121 plugin = plugins[name]
122 plugin.finalize_init(config, cfgparser, context=None)
123
124
125 def main(argparser=None):
126 args = _parse_args(argparser=argparser)
127 # parse arguments and populate config with basic settings
128 cfgparser, config = _parse_config(args)
129 # initialize logging
130 log.setup_logging(config['debug'], config['auditlog'])
131 logger.info('Custodia instance %s', args.instance or '<main>')
132 logger.debug('Config file(s) %s loaded', config['configfiles'])
133 # load plugins after logging
134 _load_plugins(config, cfgparser)
135 # create and run server
136 httpd = HTTPServer(config['server_url'], config)
137 httpd.serve()