| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
""" |
| 23 |
ClusterShell base worker for process-based workers. |
| 24 |
|
| 25 |
This module manages the worker class to spawn local commands, possibly using |
| 26 |
a nodeset to behave like a distant worker. Like other workers it can run |
| 27 |
commands or copy files, locally. |
| 28 |
|
| 29 |
This is the base class for most of other distant workers. |
| 30 |
""" |
| 31 |
|
| 32 |
import os |
| 33 |
from string import Template |
| 34 |
|
| 35 |
from ClusterShell.NodeSet import NodeSet |
| 36 |
from ClusterShell.Worker.EngineClient import EngineClient |
| 37 |
from ClusterShell.Worker.Worker import WorkerError, DistantWorker |
| 38 |
from ClusterShell.Worker.Worker import _eh_sigspec_invoke_compat |
| 39 |
|
| 40 |
|
| 41 |
def _replace_cmd(pattern, node, rank): |
| 42 |
""" |
| 43 |
Replace keywords in `pattern' with value from `node' and `rank'. |
| 44 |
|
| 45 |
%h, %host map `node' |
| 46 |
%n, %rank map `rank' |
| 47 |
""" |
| 48 |
variables = { |
| 49 |
'h': node, |
| 50 |
'host': node, |
| 51 |
'hosts': node, |
| 52 |
'n': rank or 0, |
| 53 |
'rank': rank or 0, |
| 54 |
|
| 55 |
} |
| 56 |
class Replacer(Template): |
| 57 |
delimiter = '%' |
| 58 |
try: |
| 59 |
cmd = Replacer(pattern).substitute(variables) |
| 60 |
except (KeyError, ValueError) as error: |
| 61 |
msg = "%s is not a valid pattern, use '%%%%' to escape '%%'" % error |
| 62 |
raise WorkerError(msg) |
| 63 |
return cmd |
| 64 |
|
| 65 |
class ExecClient(EngineClient): |
| 66 |
""" |
| 67 |
Run a simple local command. |
| 68 |
|
| 69 |
Useful as a superclass for other more specific workers. |
| 70 |
""" |
| 71 |
|
| 72 |
def __init__(self, node, command, worker, stderr, timeout, autoclose=False, |
| 73 |
rank=None): |
| 74 |
""" |
| 75 |
Create an EngineClient-type instance to locally run *command*. |
| 76 |
|
| 77 |
:param node: will be used as key. |
| 78 |
""" |
| 79 |
EngineClient.__init__(self, worker, node, stderr, timeout, autoclose) |
| 80 |
self.rank = rank |
| 81 |
self.command = command |
| 82 |
self.popen = None |
| 83 |
|
| 84 |
self.streams.set_writer(worker.SNAME_STDIN, None, retain=True) |
| 85 |
|
| 86 |
def _build_cmd(self): |
| 87 |
""" |
| 88 |
Build the shell command line to start the command. |
| 89 |
|
| 90 |
Return a tuple containing command and arguments as a string or a list |
| 91 |
of string, and a dict of additional environment variables. None could |
| 92 |
be returned if no environment change is required. |
| 93 |
""" |
| 94 |
return (_replace_cmd(self.command, self.key, self.rank), None) |
| 95 |
|
| 96 |
def _start(self): |
| 97 |
"""Prepare command and start client.""" |
| 98 |
|
| 99 |
|
| 100 |
cmd, cmd_env = self._build_cmd() |
| 101 |
|
| 102 |
|
| 103 |
shell = isinstance(cmd, str) |
| 104 |
|
| 105 |
task = self.worker.task |
| 106 |
if task.info("debug", False): |
| 107 |
name = self.__class__.__name__.upper().split('.')[-1] |
| 108 |
if shell: |
| 109 |
task.info("print_debug")(task, "%s: %s" % (name, cmd)) |
| 110 |
else: |
| 111 |
task.info("print_debug")(task, "%s: %s" % (name, ' '.join(cmd))) |
| 112 |
|
| 113 |
self.popen = self._exec_nonblock(cmd, env=cmd_env, shell=shell) |
| 114 |
self._on_nodeset_start(self.key) |
| 115 |
return self |
| 116 |
|
| 117 |
def _close(self, abort, timeout): |
| 118 |
"""Close client. See EngineClient._close().""" |
| 119 |
if abort: |
| 120 |
|
| 121 |
prc = self.popen.poll() |
| 122 |
|
| 123 |
if prc is None: |
| 124 |
try: |
| 125 |
self.popen.kill() |
| 126 |
except OSError: |
| 127 |
pass |
| 128 |
prc = self.popen.wait() |
| 129 |
|
| 130 |
self.streams.clear() |
| 131 |
self.invalidate() |
| 132 |
|
| 133 |
if prc >= 0: |
| 134 |
self._on_nodeset_close(self.key, prc) |
| 135 |
elif timeout: |
| 136 |
assert abort, "abort flag not set on timeout" |
| 137 |
self.worker._on_node_timeout(self.key) |
| 138 |
elif not abort: |
| 139 |
|
| 140 |
self._on_nodeset_close(self.key, 128 + -prc) |
| 141 |
|
| 142 |
self.worker._check_fini() |
| 143 |
|
| 144 |
def _on_nodeset_start(self, nodes): |
| 145 |
"""local wrapper over _on_start that can also handle nodeset""" |
| 146 |
if isinstance(nodes, NodeSet): |
| 147 |
for node in nodes: |
| 148 |
self.worker._on_start(node) |
| 149 |
else: |
| 150 |
self.worker._on_start(nodes) |
| 151 |
|
| 152 |
def _on_nodeset_close(self, nodes, rc): |
| 153 |
"""local wrapper over _on_node_rc that can also handle nodeset""" |
| 154 |
if isinstance(nodes, NodeSet): |
| 155 |
for node in nodes: |
| 156 |
self.worker._on_node_close(node, rc) |
| 157 |
else: |
| 158 |
self.worker._on_node_close(nodes, rc) |
| 159 |
|
| 160 |
def _on_nodeset_msgline(self, nodes, msg, sname): |
| 161 |
"""local wrapper over _on_node_msgline that can also handle nodeset""" |
| 162 |
if isinstance(nodes, NodeSet): |
| 163 |
for node in nodes: |
| 164 |
self.worker._on_node_msgline(node, msg, sname) |
| 165 |
else: |
| 166 |
self.worker._on_node_msgline(nodes, msg, sname) |
| 167 |
|
| 168 |
def _flush_read(self, sname): |
| 169 |
"""Called at close time to flush stream read buffer.""" |
| 170 |
stream = self.streams[sname] |
| 171 |
if stream.readable() and stream.rbuf: |
| 172 |
|
| 173 |
|
| 174 |
self._on_nodeset_msgline(self.key, stream.rbuf, sname) |
| 175 |
|
| 176 |
def _handle_read(self, sname): |
| 177 |
""" |
| 178 |
Handle a read notification. Called by the engine as the result of an |
| 179 |
event indicating that a read is available. |
| 180 |
""" |
| 181 |
|
| 182 |
worker = self.worker |
| 183 |
task = worker.task |
| 184 |
key = self.key |
| 185 |
node_msgline = self._on_nodeset_msgline |
| 186 |
debug = task.info("debug", False) |
| 187 |
if debug: |
| 188 |
print_debug = task.info("print_debug") |
| 189 |
for msg in self._readlines(sname): |
| 190 |
if debug: |
| 191 |
print_debug(task, "%s: %s" % (key, msg)) |
| 192 |
node_msgline(key, msg, sname) |
| 193 |
|
| 194 |
class CopyClient(ExecClient): |
| 195 |
""" |
| 196 |
Run a local `cp' between a source and destination. |
| 197 |
|
| 198 |
Destination could be a directory. |
| 199 |
""" |
| 200 |
|
| 201 |
def __init__(self, node, source, dest, worker, stderr, timeout, autoclose, |
| 202 |
preserve, reverse, rank=None): |
| 203 |
"""Create an EngineClient-type instance to locally run 'cp'.""" |
| 204 |
ExecClient.__init__(self, node, None, worker, stderr, timeout, |
| 205 |
autoclose, rank) |
| 206 |
self.source = source |
| 207 |
self.dest = dest |
| 208 |
|
| 209 |
|
| 210 |
self.preserve = preserve |
| 211 |
|
| 212 |
|
| 213 |
self.reverse = reverse |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
if self.reverse: |
| 219 |
self.isdir = os.path.isdir(self.dest) |
| 220 |
if not self.isdir: |
| 221 |
raise ValueError("reverse copy dest must be a directory") |
| 222 |
else: |
| 223 |
self.isdir = os.path.isdir(self.source) |
| 224 |
|
| 225 |
def _build_cmd(self): |
| 226 |
""" |
| 227 |
Build the shell command line to start the rcp command. |
| 228 |
Return an array of command and arguments. |
| 229 |
""" |
| 230 |
source = _replace_cmd(self.source, self.key, self.rank) |
| 231 |
dest = _replace_cmd(self.dest, self.key, self.rank) |
| 232 |
|
| 233 |
cmd_l = [ "cp" ] |
| 234 |
|
| 235 |
if self.isdir: |
| 236 |
cmd_l.append("-r") |
| 237 |
|
| 238 |
if self.preserve: |
| 239 |
cmd_l.append("-p") |
| 240 |
|
| 241 |
if self.reverse: |
| 242 |
cmd_l.append(dest) |
| 243 |
cmd_l.append(source) |
| 244 |
else: |
| 245 |
cmd_l.append(source) |
| 246 |
cmd_l.append(dest) |
| 247 |
|
| 248 |
return (cmd_l, None) |
| 249 |
|
| 250 |
|
| 251 |
class ExecWorker(DistantWorker): |
| 252 |
""" |
| 253 |
ClusterShell simple execution worker Class. |
| 254 |
|
| 255 |
It runs commands locally. If a node list is provided, one command will be |
| 256 |
launched for each node and specific keywords will be replaced based on node |
| 257 |
name and rank. |
| 258 |
|
| 259 |
Local shell usage example: |
| 260 |
|
| 261 |
>>> worker = ExecWorker(nodeset, handler=MyEventHandler(), |
| 262 |
... timeout=30, command="/bin/uptime") |
| 263 |
>>> task.schedule(worker) # schedule worker for execution |
| 264 |
>>> task.run() # run |
| 265 |
|
| 266 |
Local copy usage example: |
| 267 |
|
| 268 |
>>> worker = ExecWorker(nodeset, handler=MyEventHandler(), |
| 269 |
... source="/etc/my.cnf", |
| 270 |
... dest="/etc/my.cnf.bak") |
| 271 |
>>> task.schedule(worker) # schedule worker for execution |
| 272 |
>>> task.run() # run |
| 273 |
|
| 274 |
connect_timeout option is ignored by this worker. |
| 275 |
""" |
| 276 |
|
| 277 |
SHELL_CLASS = ExecClient |
| 278 |
COPY_CLASS = CopyClient |
| 279 |
|
| 280 |
def __init__(self, nodes, handler, timeout=None, **kwargs): |
| 281 |
"""Create an ExecWorker and its engine client instances.""" |
| 282 |
DistantWorker.__init__(self, handler) |
| 283 |
self._close_count = 0 |
| 284 |
self._has_timeout = False |
| 285 |
self._clients = [] |
| 286 |
|
| 287 |
self.nodes = NodeSet(nodes) |
| 288 |
self.command = kwargs.get('command') |
| 289 |
self.source = kwargs.get('source') |
| 290 |
self.dest = kwargs.get('dest') |
| 291 |
|
| 292 |
self._create_clients(timeout=timeout, **kwargs) |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
def _create_clients(self, **kwargs): |
| 299 |
""" |
| 300 |
Create several shell and copy engine client instances based on worker |
| 301 |
properties. |
| 302 |
|
| 303 |
Additional arguments in `kwargs' will be used for client creation. |
| 304 |
There will be one client per node in self.nodes |
| 305 |
""" |
| 306 |
|
| 307 |
if self.command and ('%hosts' in self.command or |
| 308 |
'%{hosts}' in self.command): |
| 309 |
self._add_client(self.nodes, rank=None, **kwargs) |
| 310 |
else: |
| 311 |
for rank, node in enumerate(self.nodes): |
| 312 |
self._add_client(node, rank=rank, **kwargs) |
| 313 |
|
| 314 |
def _add_client(self, nodes, **kwargs): |
| 315 |
"""Create one shell or copy client.""" |
| 316 |
autoclose = kwargs.get('autoclose', False) |
| 317 |
stderr = kwargs.get('stderr', False) |
| 318 |
rank = kwargs.get('rank') |
| 319 |
timeout = kwargs.get('timeout') |
| 320 |
|
| 321 |
if self.command is not None: |
| 322 |
cls = self.__class__.SHELL_CLASS |
| 323 |
self._clients.append(cls(nodes, self.command, self, stderr, |
| 324 |
timeout, autoclose, rank)) |
| 325 |
elif self.source: |
| 326 |
cls = self.__class__.COPY_CLASS |
| 327 |
self._clients.append(cls(nodes, self.source, self.dest, self, |
| 328 |
stderr, timeout, autoclose, |
| 329 |
kwargs.get('preserve', False), |
| 330 |
kwargs.get('reverse', False), rank)) |
| 331 |
else: |
| 332 |
raise ValueError("missing command or source parameter in " |
| 333 |
"worker constructor") |
| 334 |
|
| 335 |
def _engine_clients(self): |
| 336 |
""" |
| 337 |
Used by upper layer to get the list of underlying created engine |
| 338 |
clients. |
| 339 |
""" |
| 340 |
return self._clients |
| 341 |
|
| 342 |
def write(self, buf, sname=None): |
| 343 |
"""Write to worker clients.""" |
| 344 |
sname = sname or self.SNAME_STDIN |
| 345 |
for client in self._clients: |
| 346 |
if sname in client.streams: |
| 347 |
client._write(sname, buf) |
| 348 |
|
| 349 |
def set_write_eof(self, sname=None): |
| 350 |
""" |
| 351 |
Tell worker to close its writer file descriptors once flushed. Do not |
| 352 |
perform writes after this call. |
| 353 |
""" |
| 354 |
for client in self._clients: |
| 355 |
client._set_write_eof(sname or self.SNAME_STDIN) |
| 356 |
|
| 357 |
def abort(self): |
| 358 |
"""Abort processing any action by this worker.""" |
| 359 |
for client in self._clients: |
| 360 |
client.abort() |
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
def _on_node_timeout(self, node): |
| 367 |
DistantWorker._on_node_timeout(self, node) |
| 368 |
self._has_timeout = True |
| 369 |
|
| 370 |
def _check_fini(self): |
| 371 |
""" |
| 372 |
Must be called by each client when closing. |
| 373 |
|
| 374 |
If they are all closed, trigger the required events. |
| 375 |
""" |
| 376 |
self._close_count += 1 |
| 377 |
assert self._close_count <= len(self._clients) |
| 378 |
if self._close_count == len(self._clients) and self.eh is not None: |
| 379 |
|
| 380 |
if self._has_timeout and hasattr(self.eh, 'ev_timeout'): |
| 381 |
|
| 382 |
self.eh.ev_timeout(self) |
| 383 |
_eh_sigspec_invoke_compat(self.eh.ev_close, 2, self, |
| 384 |
self._has_timeout) |
| 385 |
|
| 386 |
|
| 387 |
WORKER_CLASS = ExecWorker |