Debian Codegraph @

lib/ClusterShell/Defaults.py

raw symbols SCIP
1 #
2 # Copyright (C) 2015-2019 Stephane Thiell <[email protected]>
3 #
4 # This file is part of ClusterShell.
5 #
6 # ClusterShell is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # ClusterShell is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with ClusterShell; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
20 """
21 ClusterShell Defaults module.
22
23 Manage library defaults.
24 """
25
26 from __future__ import print_function
27
28 # Imported early
29 # Should not import any other ClusterShell modules when loaded
30 try:
31 from configparser import ConfigParser, NoOptionError, NoSectionError
32 except ImportError:
33 # Python 2 compat
34 from ConfigParser import ConfigParser, NoOptionError, NoSectionError
35
36 import os
37 import sys
38
39
40 #
41 # defaults.conf sections
42 #
43 CFG_SECTION_TASK_DEFAULT = 'task.default'
44 CFG_SECTION_TASK_INFO = 'task.info'
45 CFG_SECTION_NODESET = 'nodeset'
46 CFG_SECTION_ENGINE = 'engine'
47
48 #
49 # Functions
50 #
51 def _task_print_debug(task, line):
52 """Default task debug printing function."""
53 print(line)
54
55 def _load_workerclass(workername):
56 """
57 Return the class pointer matching `workername`.
58
59 This can be the 'short' name (such as `ssh`) or a fully-qualified
60 module path (such as ClusterShell.Worker.Ssh).
61
62 The module is loaded if not done yet.
63 """
64
65 # First try the worker name as a module under ClusterShell.Worker,
66 # but if that fails, try the worker name directly
67 try:
68 modname = "ClusterShell.Worker.%s" % workername.capitalize()
69 _import_module(modname)
70 except ImportError:
71 modname = workername
72 _import_module(modname)
73
74 # Get the class pointer
75 return sys.modules[modname].WORKER_CLASS
76
77 def _import_module(modname):
78 """Import a python module if not done yet."""
79 # Iterate over a copy of sys.modules' keys to avoid RuntimeError
80 if modname.lower() not in [mod.lower() for mod in list(sys.modules)]:
81 # Import module if not yet loaded
82 __import__(modname)
83
84 def _local_workerclass(defaults):
85 """Return default local worker class."""
86 return _load_workerclass(defaults.local_workername)
87
88 def _distant_workerclass(defaults):
89 """Return default distant worker class."""
90 return _load_workerclass(defaults.distant_workername)
91
92 def config_paths(config_name):
93 """Return default path list for a ClusterShell config file name."""
94
95 paths = [os.path.join('/etc/clustershell', config_name), # system-wide
96 # default pip --user config file
97 os.path.expanduser('~/.local/etc/clustershell/%s' % config_name),
98 # Python installation prefix (for venv)
99 os.path.join(sys.prefix, 'etc/clustershell', config_name),
100 # per-user config (XDG Base Directory Specification)
101 os.path.join(os.environ.get('XDG_CONFIG_HOME',
102 os.path.expanduser('~/.config')),
103 'clustershell', config_name)]
104
105 # $CLUSTERSHELL_CFGDIR has precedence over any other config paths
106 if 'CLUSTERSHELL_CFGDIR' in os.environ:
107 paths.append(os.path.join(os.environ['CLUSTERSHELL_CFGDIR'],
108 config_name))
109 return paths
110
111 def _converter_integer_tuple(value):
112 """ConfigParser converter for tuple of integers"""
113 # NOTE: compatible with ConfigParser 'converters' argument (Python 3.5+)
114 return tuple(int(x) for x in value.split(',') if x.strip())
115
116 def _parser_get_integer_tuple(parser, section, option, **kwargs):
117 """
118 Compatible converter for parsing tuple of integers until we can use
119 converters from new ConfigParser (Python 3.5+).
120 """
121 return _converter_integer_tuple(
122 ConfigParser.get(parser, section, option, **kwargs))
123
124
125 #
126 # Classes
127 #
128 class Defaults(object):
129 """
130 Class used to manipulate ClusterShell defaults.
131
132 The following attributes may be read at any time and also changed
133 programmatically, for most of them **before** ClusterShell objects
134 (Task or NodeSet) are initialized.
135
136 NodeSet defaults:
137
138 * fold_axis (tuple of axis integers; default is empty tuple ``()``)
139
140 Task defaults:
141
142 * stderr (boolean; default is ``False``)
143 * stdin (boolean; default is ``True``)
144 * stdout_msgtree (boolean; default is ``True``)
145 * stderr_msgtree (boolean; default is ``True``)
146 * engine (string; default is ``'auto'``)
147 * local_workername (string; default is ``'exec'``)
148 * distant_workername (string; default is ``'ssh'``)
149 * auto_tree (boolean; default is ``True``)
150 * debug (boolean; default is ``False``)
151 * print_debug (function; default is internal)
152 * fanout (integer; default is ``64``)
153 * grooming_delay (float; default is ``0.25``)
154 * connect_timeout (float; default is ``10``)
155 * command_timeout (float; default is ``0``)
156
157 Engine defaults:
158
159 * port_qlimit (integer; default is ``100``)
160
161 Example of use::
162
163 >>> from ClusterShell.Defaults import DEFAULTS
164 >>> from ClusterShell.Task import task_self
165 >>> # Change default distant worker to rsh (WorkerRsh)
166 ... DEFAULTS.distant_workername = 'rsh'
167 >>> task = task_self()
168 >>> task.run("uname -r", nodes="cs[01-03]")
169 <ClusterShell.Worker.Rsh.WorkerRsh object at 0x1f4a410>
170 >>> list((str(msg), nodes) for msg, nodes in task.iter_buffers())
171 [('3.10.0-229.7.2.el7.x86_64', ['cs02', 'cs01', 'cs03'])]
172
173
174 The library default values of all of the above attributes may be changed
175 using the defaults.conf configuration file, except for *print_debug*
176 (cf. :ref:`defaults-config`). An example defaults.conf file should be
177 included with ClusterShell. Remember that this could affect all
178 applications using ClusterShell.
179 """
180
181 #
182 # Default values for task "default" sync dict
183 #
184 _TASK_DEFAULT = {"stderr" : False,
185 "stdin" : True,
186 "stdout_msgtree" : True,
187 "stderr_msgtree" : True,
188 "engine" : 'auto',
189 "port_qlimit" : 100, # 1.8 compat
190 "auto_tree" : True,
191 "local_workername" : 'exec',
192 "distant_workername" : 'ssh'}
193
194 #
195 # Datatype converters for task_default
196 #
197 _TASK_DEFAULT_CONVERTERS = {"stderr" : ConfigParser.getboolean,
198 "stdin" : ConfigParser.getboolean,
199 "stdout_msgtree" : ConfigParser.getboolean,
200 "stderr_msgtree" : ConfigParser.getboolean,
201 "engine" : ConfigParser.get,
202 "port_qlimit" : ConfigParser.getint, # 1.8 compat
203 "auto_tree" : ConfigParser.getboolean,
204 "local_workername" : ConfigParser.get,
205 "distant_workername" : ConfigParser.get}
206
207 #
208 # Default values for task "info" async dict
209 #
210 _TASK_INFO = {"debug" : False,
211 "print_debug" : _task_print_debug,
212 "fanout" : 64,
213 "grooming_delay" : 0.25,
214 "connect_timeout" : 10,
215 "command_timeout" : 0}
216
217 #
218 # Datatype converters for task_info
219 #
220 _TASK_INFO_CONVERTERS = {"debug" : ConfigParser.getboolean,
221 "fanout" : ConfigParser.getint,
222 "grooming_delay" : ConfigParser.getfloat,
223 "connect_timeout" : ConfigParser.getfloat,
224 "command_timeout" : ConfigParser.getfloat}
225
226 #
227 # Black list of info keys whose values cannot safely be propagated
228 # in tree mode
229 #
230 _TASK_INFO_PKEYS_BL = ['engine', 'print_debug']
231
232 #
233 # Default values for NodeSet
234 #
235 _NODESET = {"fold_axis" : ()}
236
237 #
238 # Datatype converters for NodeSet defaults
239 #
240 _NODESET_CONVERTERS = {"fold_axis" : _parser_get_integer_tuple}
241
242 #
243 # Default values for Engine objects
244 #
245 _ENGINE = {"port_qlimit" : 100}
246
247 #
248 # Datatype converters for Engine defaults
249 #
250 _ENGINE_CONVERTERS = {"port_qlimit" : ConfigParser.getint}
251
252 def __init__(self, filenames):
253 """Initialize Defaults from config filenames"""
254
255 self._task_default = self._TASK_DEFAULT.copy()
256 self._task_info = self._TASK_INFO.copy()
257 self._task_info_pkeys_bl = list(self._TASK_INFO_PKEYS_BL)
258 self._nodeset = self._NODESET.copy()
259 self._engine = self._ENGINE.copy()
260
261 config = ConfigParser()
262 parsed = config.read(filenames)
263
264 if parsed:
265 self._parse_config(config)
266
267 def _parse_config(self, config):
268 """parse config"""
269
270 # task_default overrides
271 for key, conv in self._TASK_DEFAULT_CONVERTERS.items():
272 try:
273 self._task_default[key] = conv(config, CFG_SECTION_TASK_DEFAULT,
274 key)
275 except (NoSectionError, NoOptionError):
276 pass
277
278 # task_info overrides
279 for key, conv in self._TASK_INFO_CONVERTERS.items():
280 try:
281 self._task_info[key] = conv(config, CFG_SECTION_TASK_INFO, key)
282 except (NoSectionError, NoOptionError):
283 pass
284
285 # NodeSet
286 for key, conv in self._NODESET_CONVERTERS.items():
287 try:
288 self._nodeset[key] = conv(config, CFG_SECTION_NODESET, key)
289 except (NoSectionError, NoOptionError):
290 pass
291
292 # Engine
293 for key, conv in self._ENGINE_CONVERTERS.items():
294 try:
295 self._engine[key] = conv(config, CFG_SECTION_ENGINE, key)
296 except (NoSectionError, NoOptionError):
297 pass
298
299 def __getattr__(self, name):
300 """Defaults attribute lookup"""
301 # 1.8 compat: port_qlimit moved into engine section
302 if name == 'port_qlimit':
303 if self._engine[name] == self._ENGINE[name]:
304 return self._task_default[name]
305 if name in self._engine:
306 return self._engine[name]
307 elif name in self._task_default:
308 return self._task_default[name]
309 elif name in self._task_info:
310 return self._task_info[name]
311 elif name in self._nodeset:
312 return self._nodeset[name]
313 raise AttributeError(name)
314
315 def __setattr__(self, name, value):
316 """Defaults attribute assignment"""
317 if name in ('_task_default', '_task_info', '_task_info_pkeys_bl',
318 '_nodeset', '_engine'):
319 object.__setattr__(self, name, value)
320 elif name in self._engine:
321 self._engine[name] = value
322 elif name in self._task_default:
323 self._task_default[name] = value
324 elif name in self._task_info:
325 self._task_info[name] = value
326 elif name in self._nodeset:
327 self._nodeset[name] = value
328 else:
329 raise AttributeError(name)
330
331 #
332 # Globally accessible Defaults object
333 #
334 DEFAULTS = Defaults(config_paths('defaults.conf'))