| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
""" |
| 23 |
ClusterShell Propagation module. Use the topology tree to send commands |
| 24 |
through gateways and gather results. |
| 25 |
""" |
| 26 |
|
| 27 |
from collections import deque |
| 28 |
import logging |
| 29 |
|
| 30 |
from ClusterShell.Defaults import DEFAULTS |
| 31 |
from ClusterShell.NodeSet import NodeSet |
| 32 |
from ClusterShell.Communication import (Channel, ControlMessage, StdOutMessage, |
| 33 |
StdErrMessage, RetcodeMessage, |
| 34 |
StartMessage, EndMessage, |
| 35 |
RoutedMessageBase, ErrorMessage, |
| 36 |
ConfigurationMessage, TimeoutMessage, |
| 37 |
RoutingMessage) |
| 38 |
from ClusterShell.Communication import ENCODING |
| 39 |
from ClusterShell.Topology import TopologyError |
| 40 |
|
| 41 |
|
| 42 |
class RouteResolvingError(Exception): |
| 43 |
"""error raised on invalid conditions during routing operations""" |
| 44 |
|
| 45 |
|
| 46 |
class PropagationTreeRouter(object): |
| 47 |
"""performs routes resolving operations within a propagation tree. |
| 48 |
This object provides a next_hop method, that will look for the best |
| 49 |
directly connected node to use to forward a message to a remote |
| 50 |
node. |
| 51 |
|
| 52 |
Upon instantiation, the router will parse the topology tree to |
| 53 |
generate its routing table. |
| 54 |
""" |
| 55 |
def __init__(self, root, topology, fanout=0): |
| 56 |
self.root = root |
| 57 |
self.topology = topology |
| 58 |
self.fanout = fanout |
| 59 |
self.nodes_fanin = {} |
| 60 |
self.table = None |
| 61 |
|
| 62 |
self.table_generate(root, topology) |
| 63 |
self._unreachable_hosts = NodeSet() |
| 64 |
|
| 65 |
def table_generate(self, root, topology): |
| 66 |
"""The router relies on a routing table. The keys are the |
| 67 |
destination nodes and the values are the next hop gateways to |
| 68 |
use to reach these nodes. |
| 69 |
""" |
| 70 |
try: |
| 71 |
root_group = topology.find_nodegroup(root) |
| 72 |
except TopologyError: |
| 73 |
msgfmt = "Invalid root or gateway node: %s" |
| 74 |
raise RouteResolvingError(msgfmt % root) |
| 75 |
|
| 76 |
self.table = [] |
| 77 |
for group in root_group.children(): |
| 78 |
dest = NodeSet() |
| 79 |
stack = [group] |
| 80 |
while len(stack) > 0: |
| 81 |
curr = stack.pop() |
| 82 |
dest.update(curr.children_ns()) |
| 83 |
stack += curr.children() |
| 84 |
self.table.append((dest, group.nodeset)) |
| 85 |
|
| 86 |
def dispatch(self, dst): |
| 87 |
"""dispatch nodes from a target nodeset to the directly |
| 88 |
connected gateways. |
| 89 |
|
| 90 |
The method acts as an iterator, returning a gateway and the |
| 91 |
associated hosts. It should provide a rather good load balancing |
| 92 |
between the gateways. |
| 93 |
""" |
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
for network, _ in self.table: |
| 104 |
dst_inter = network & dst |
| 105 |
dst.difference_update(dst_inter) |
| 106 |
for host in dst_inter.nsiter(): |
| 107 |
yield self.next_hop(host), host |
| 108 |
|
| 109 |
|
| 110 |
if dst: |
| 111 |
yield dst, dst |
| 112 |
|
| 113 |
def next_hop(self, dst): |
| 114 |
"""perform the next hop resolution. If several hops are |
| 115 |
available, then, the one with the least number of current jobs |
| 116 |
will be returned |
| 117 |
""" |
| 118 |
if dst in self._unreachable_hosts: |
| 119 |
raise RouteResolvingError( |
| 120 |
'Invalid destination: %s, host is unreachable' % dst) |
| 121 |
|
| 122 |
|
| 123 |
if self.root == dst: |
| 124 |
raise RouteResolvingError( |
| 125 |
'Invalid resolution request: %s -> %s' % (self.root, dst)) |
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
for network, nexthops in self.table: |
| 137 |
|
| 138 |
if dst in network: |
| 139 |
res = self._best_next_hop(nexthops) |
| 140 |
if res is None: |
| 141 |
raise RouteResolvingError('No route available to %s' % \ |
| 142 |
str(dst)) |
| 143 |
self.nodes_fanin[res] += len(dst) |
| 144 |
return res |
| 145 |
|
| 146 |
|
| 147 |
if dst in nexthops: |
| 148 |
return dst |
| 149 |
|
| 150 |
raise RouteResolvingError( |
| 151 |
'No route from %s to host %s' % (self.root, dst)) |
| 152 |
|
| 153 |
def mark_unreachable(self, dst): |
| 154 |
"""mark node dst as unreachable and don't advertise routes |
| 155 |
through it anymore. The cache will be updated only when |
| 156 |
necessary to avoid performing expensive traversals. |
| 157 |
""" |
| 158 |
|
| 159 |
|
| 160 |
self._unreachable_hosts.add(dst) |
| 161 |
|
| 162 |
def _best_next_hop(self, candidates): |
| 163 |
"""find out a good next hop gateway""" |
| 164 |
backup = None |
| 165 |
backup_connections = 1e400 |
| 166 |
|
| 167 |
candidates = candidates.difference(self._unreachable_hosts) |
| 168 |
|
| 169 |
for host in candidates: |
| 170 |
|
| 171 |
|
| 172 |
connections = self.nodes_fanin.setdefault(host, 0) |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
if backup_connections > connections: |
| 178 |
backup = host |
| 179 |
backup_connections = connections |
| 180 |
return backup |
| 181 |
|
| 182 |
|
| 183 |
class PropagationChannel(Channel): |
| 184 |
"""Admin node propagation logic. Instances are able to handle |
| 185 |
incoming messages from a directly connected gateway, process them |
| 186 |
and reply. |
| 187 |
|
| 188 |
In order to take decisions, the instance acts as a finite states |
| 189 |
machine, whose current state evolves according to received data. |
| 190 |
|
| 191 |
-- INTERNALS -- |
| 192 |
Instance can be in one of the 4 different states: |
| 193 |
- init (implicit) |
| 194 |
This is the very first state. The instance enters the init |
| 195 |
state at start() method, and will then send the configuration |
| 196 |
to the remote node. Once the configuration is sent away, the |
| 197 |
state changes to cfg. |
| 198 |
|
| 199 |
- cfg |
| 200 |
During this second state, the instance will wait for a valid |
| 201 |
acknowledgement from the gateway to the previously sent |
| 202 |
configuration message. If such a message is delivered, the |
| 203 |
control message (the one that contains the actions to perform) |
| 204 |
is sent, and the state is set to ctl. |
| 205 |
|
| 206 |
- ctl |
| 207 |
Third state, the instance is waiting for a valid ack for from |
| 208 |
the gateway to the ctl packet. Then, the state switch to gtr |
| 209 |
(gather). |
| 210 |
|
| 211 |
- gtr |
| 212 |
Final state: wait for results from the subtree and store them. |
| 213 |
""" |
| 214 |
def __init__(self, task, gateway): |
| 215 |
""" |
| 216 |
""" |
| 217 |
Channel.__init__(self, initiator=True) |
| 218 |
self.task = task |
| 219 |
self.gateway = gateway |
| 220 |
self.workers = {} |
| 221 |
self._cfg_write_hist = deque() |
| 222 |
self._sendq = deque() |
| 223 |
self._rc = None |
| 224 |
self.logger = logging.getLogger(__name__) |
| 225 |
|
| 226 |
def _send_ctl(self, ctl, pickup_worker=None, pickup_nodes=None): |
| 227 |
"""Actually push a CTL message on the wire. |
| 228 |
|
| 229 |
If pickup_worker is set, fires _emit_pickup() on the meta |
| 230 |
worker for every target node, AFTER the send -- so ev_pickup |
| 231 |
only fires when the command really left the local process |
| 232 |
(#594). write()/set_write_eof() don't carry pickup args. |
| 233 |
""" |
| 234 |
self.send(ctl) |
| 235 |
if pickup_worker is not None and pickup_nodes is not None: |
| 236 |
for node in pickup_nodes: |
| 237 |
pickup_worker._emit_pickup(node) |
| 238 |
|
| 239 |
def send_queued(self, ctl, pickup_worker=None, pickup_nodes=None): |
| 240 |
"""helper used to send a message, using msg queue if needed""" |
| 241 |
if self.setup and not self._sendq: |
| 242 |
|
| 243 |
self._send_ctl(ctl, pickup_worker, pickup_nodes) |
| 244 |
else: |
| 245 |
self.logger.debug("send_queued: %d", len(self._sendq)) |
| 246 |
self._sendq.appendleft((ctl, pickup_worker, pickup_nodes)) |
| 247 |
|
| 248 |
def send_dequeue(self): |
| 249 |
"""helper used to send one queued message (if any)""" |
| 250 |
if self._sendq: |
| 251 |
ctl, pickup_worker, pickup_nodes = self._sendq.pop() |
| 252 |
self.logger.debug("dequeuing sendq: %s", ctl) |
| 253 |
self._send_ctl(ctl, pickup_worker, pickup_nodes) |
| 254 |
|
| 255 |
def start(self): |
| 256 |
"""start propagation channel""" |
| 257 |
self._init() |
| 258 |
self._open() |
| 259 |
|
| 260 |
cfg = ConfigurationMessage(self.gateway) |
| 261 |
cfg.data_encode(self.task.topology) |
| 262 |
self.send(cfg) |
| 263 |
|
| 264 |
def _report_stderr(self, nodeset, buf): |
| 265 |
"""report buf as stderr of nodeset, as seen from the gateway""" |
| 266 |
|
| 267 |
lines = (buf + b'\n').splitlines() |
| 268 |
|
| 269 |
for metaworker in self.workers.values(): |
| 270 |
for line in lines: |
| 271 |
for node in nodeset: |
| 272 |
metaworker._on_remote_node_msgline(node, line, 'stderr', |
| 273 |
self.gateway) |
| 274 |
|
| 275 |
def recv(self, msg): |
| 276 |
"""process incoming messages""" |
| 277 |
self.logger.debug("recv: %s", msg) |
| 278 |
if msg.type == EndMessage.ident: |
| 279 |
self.logger.debug("got EndMessage; closing") |
| 280 |
self._close() |
| 281 |
elif msg.type == StdErrMessage.ident and msg.srcid == 0: |
| 282 |
|
| 283 |
|
| 284 |
self._report_stderr(NodeSet(msg.nodes), msg.data_decode()) |
| 285 |
elif self.setup: |
| 286 |
self.recv_ctl(msg) |
| 287 |
elif self.opened: |
| 288 |
self.recv_cfg(msg) |
| 289 |
elif msg.type == StartMessage.ident: |
| 290 |
self.opened = True |
| 291 |
self.logger.debug('channel started (version %s on remote gateway)', |
| 292 |
self._xml_reader.version) |
| 293 |
else: |
| 294 |
self.logger.error('unexpected message: %s', str(msg)) |
| 295 |
|
| 296 |
def shell(self, nodes, command, worker, timeout, stderr, gw_invoke_cmd, |
| 297 |
remote): |
| 298 |
"""command execution through channel""" |
| 299 |
self.logger.debug("shell nodes=%s timeout=%s worker=%s remote=%s", |
| 300 |
nodes, timeout, id(worker), remote) |
| 301 |
|
| 302 |
self.workers[id(worker)] = worker |
| 303 |
|
| 304 |
ctl = ControlMessage(id(worker)) |
| 305 |
ctl.action = 'shell' |
| 306 |
ctl.target = nodes |
| 307 |
|
| 308 |
|
| 309 |
info = dict((k, v) for k, v in self.task._info.items() |
| 310 |
if k not in DEFAULTS._task_info_pkeys_bl) |
| 311 |
|
| 312 |
ctl_data = { |
| 313 |
'cmd': command, |
| 314 |
'invoke_gateway': gw_invoke_cmd, |
| 315 |
'taskinfo': info, |
| 316 |
'stderr': stderr, |
| 317 |
'timeout': timeout, |
| 318 |
'remote': remote, |
| 319 |
} |
| 320 |
ctl.data_encode(ctl_data) |
| 321 |
|
| 322 |
|
| 323 |
self.send_queued(ctl, pickup_worker=worker, pickup_nodes=nodes) |
| 324 |
|
| 325 |
def write(self, nodes, buf, worker): |
| 326 |
"""write buffer through channel to nodes on standard input""" |
| 327 |
self.logger.debug("write buflen=%d", len(buf)) |
| 328 |
assert id(worker) in self.workers |
| 329 |
|
| 330 |
ctl = ControlMessage(id(worker)) |
| 331 |
ctl.action = 'write' |
| 332 |
ctl.target = nodes |
| 333 |
|
| 334 |
ctl_data = { |
| 335 |
'buf': buf, |
| 336 |
} |
| 337 |
ctl.data_encode(ctl_data) |
| 338 |
self._cfg_write_hist.appendleft((ctl.msgid, nodes, len(buf), worker)) |
| 339 |
self.send_queued(ctl) |
| 340 |
|
| 341 |
def set_write_eof(self, nodes, worker): |
| 342 |
"""send EOF through channel to specified nodes""" |
| 343 |
self.logger.debug("set_write_eof") |
| 344 |
assert id(worker) in self.workers |
| 345 |
|
| 346 |
ctl = ControlMessage(id(worker)) |
| 347 |
ctl.action = 'eof' |
| 348 |
ctl.target = nodes |
| 349 |
self.send_queued(ctl) |
| 350 |
|
| 351 |
def recv_cfg(self, msg): |
| 352 |
"""handle incoming messages for state 'propagate configuration'""" |
| 353 |
self.logger.debug("recv_cfg") |
| 354 |
if msg.type == 'ACK': |
| 355 |
self.logger.debug("CTL - connection with gateway fully established") |
| 356 |
self.setup = True |
| 357 |
self.send_dequeue() |
| 358 |
elif msg.type == ErrorMessage.ident: |
| 359 |
|
| 360 |
self._report_stderr(NodeSet(self.gateway), |
| 361 |
msg.reason.encode(ENCODING)) |
| 362 |
else: |
| 363 |
self.logger.debug("_state_config error (msg=%s)", msg) |
| 364 |
|
| 365 |
def recv_ctl(self, msg): |
| 366 |
"""handle incoming messages for state 'control'""" |
| 367 |
if msg.type == 'ACK': |
| 368 |
self.logger.debug("got ack (%s)", msg.type) |
| 369 |
|
| 370 |
if self._cfg_write_hist and msg.ack == self._cfg_write_hist[-1][0]: |
| 371 |
_, nodes, bytes_count, metaworker = self._cfg_write_hist.pop() |
| 372 |
for node in nodes: |
| 373 |
|
| 374 |
|
| 375 |
metaworker._on_written(node, bytes_count, 'stdin') |
| 376 |
self.send_dequeue() |
| 377 |
elif isinstance(msg, RoutedMessageBase): |
| 378 |
metaworker = self.workers[msg.srcid] |
| 379 |
if msg.type == StdOutMessage.ident: |
| 380 |
nodeset = NodeSet(msg.nodes) |
| 381 |
|
| 382 |
|
| 383 |
decoded = msg.data_decode() + b'\n' |
| 384 |
for line in decoded.splitlines(): |
| 385 |
for node in nodeset: |
| 386 |
metaworker._on_remote_node_msgline(node, line, 'stdout', |
| 387 |
self.gateway) |
| 388 |
elif msg.type == StdErrMessage.ident: |
| 389 |
nodeset = NodeSet(msg.nodes) |
| 390 |
decoded = msg.data_decode() + b'\n' |
| 391 |
for line in decoded.splitlines(): |
| 392 |
for node in nodeset: |
| 393 |
metaworker._on_remote_node_msgline(node, line, 'stderr', |
| 394 |
self.gateway) |
| 395 |
elif msg.type == RetcodeMessage.ident: |
| 396 |
rc = msg.retcode |
| 397 |
for node in NodeSet(msg.nodes): |
| 398 |
metaworker._on_remote_node_close(node, rc, self.gateway) |
| 399 |
elif msg.type == TimeoutMessage.ident: |
| 400 |
self.logger.debug("TimeoutMessage for %s", msg.nodes) |
| 401 |
for node in NodeSet(msg.nodes): |
| 402 |
metaworker._on_remote_node_timeout(node, self.gateway) |
| 403 |
elif msg.type == RoutingMessage.ident: |
| 404 |
self.logger.debug("RoutingMessage for %s (gw %s)", msg.targets, |
| 405 |
msg.gateway) |
| 406 |
metaworker._on_routing_event({ "event": msg.event, |
| 407 |
"gateway": msg.gateway, |
| 408 |
"targets": msg.targets }) |
| 409 |
elif msg.type == ErrorMessage.ident: |
| 410 |
|
| 411 |
raise TopologyError("%s: %s" % (self.gateway, msg.reason)) |
| 412 |
else: |
| 413 |
self.logger.debug("recv_ctl: unhandled msg %s", msg) |
| 414 |
|
| 415 |
def ev_hup(self, worker, node, rc): |
| 416 |
"""Channel command is closing""" |
| 417 |
self.logger.debug("ev_hup gateway=%s %s", str(worker.nodes), self) |
| 418 |
self._rc = rc |
| 419 |
|
| 420 |
def ev_close(self, worker, timedout): |
| 421 |
"""Channel is closing""" |
| 422 |
|
| 423 |
|
| 424 |
gateway = str(worker.nodes) |
| 425 |
self.logger.debug("ev_close gateway=%s rc=%s %s", gateway, self._rc, |
| 426 |
self) |
| 427 |
|
| 428 |
|
| 429 |
if self._rc is None and not self.setup: |
| 430 |
|
| 431 |
self.logger.warning("ev_close: rc=%s with channel not setup", |
| 432 |
self._rc) |
| 433 |
|
| 434 |
if self._rc is not None and self._rc != 0: |
| 435 |
|
| 436 |
self.logger.debug("error on gateway %s (rc=%s, setup=%s)", gateway, |
| 437 |
self._rc, self.setup) |
| 438 |
self.task.router.mark_unreachable(gateway) |
| 439 |
self.logger.debug("gateway %s now set as unreachable", gateway) |
| 440 |
|
| 441 |
if not self.setup: |
| 442 |
|
| 443 |
self.logger.debug("channel was not set up: redistributing...") |
| 444 |
for mw in set(self.task.gateways[gateway][1]): |
| 445 |
mw._relaunch(gateway) |
| 446 |
|
| 447 |
|
| 448 |
worker.task._pchannel_close(gateway, worker) |