/usr/lib/python2.7/dist-packages/taskflow/engines/action_engine/process_executor.py is in python-taskflow 2.3.0-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import asyncore
import binascii
import collections
import errno
import functools
import hmac
import math
import os
import pickle
import socket
import struct
import time
import futurist
from oslo_utils import excutils
import six
from taskflow.engines.action_engine import executor as base
from taskflow import logging
from taskflow import task as ta
from taskflow.utils import iter_utils
from taskflow.utils import misc
from taskflow.utils import schema_utils as su
from taskflow.utils import threading_utils
LOG = logging.getLogger(__name__)
# Internal parent <-> child process protocol schema, message constants...
MAGIC_HEADER = 0xDECAF
CHALLENGE = 'identify_yourself'
CHALLENGE_RESPONSE = 'worker_reporting_in'
ACK = 'ack'
EVENT = 'event'
SCHEMAS = {
# Basic jsonschemas for verifying that the data we get back and
# forth from parent <-> child observes at least a basic expected
# format.
CHALLENGE: {
"type": "string",
"minLength": 1,
},
ACK: {
"type": "string",
"minLength": 1,
},
CHALLENGE_RESPONSE: {
"type": "string",
"minLength": 1,
},
EVENT: {
"type": "object",
"properties": {
'event_type': {
"type": "string",
},
'sent_on': {
"type": "number",
},
},
"required": ['event_type', 'sent_on'],
"additionalProperties": True,
},
}
# See http://bugs.python.org/issue1457119 for why this is so complex...
_DECODE_ENCODE_ERRORS = [pickle.PickleError, TypeError]
try:
import cPickle
_DECODE_ENCODE_ERRORS.append(cPickle.PickleError)
del cPickle
except (ImportError, AttributeError):
pass
_DECODE_ENCODE_ERRORS = tuple(_DECODE_ENCODE_ERRORS)
# Use the best pickle from here on out...
from six.moves import cPickle as pickle
class UnknownSender(Exception):
"""Exception raised when message from unknown sender is recvd."""
class ChallengeIgnored(Exception):
"""Exception raised when challenge has not been responded to."""
class Reader(object):
"""Reader machine that streams & parses messages that it then dispatches.
TODO(harlowja): Use python-suitcase in the future when the following
are addressed/resolved and released:
- https://github.com/digidotcom/python-suitcase/issues/28
- https://github.com/digidotcom/python-suitcase/issues/29
Binary format format is the following (no newlines in actual format)::
<magic-header> (4 bytes)
<mac-header-length> (4 bytes)
<mac> (1 or more variable bytes)
<identity-header-length> (4 bytes)
<identity> (1 or more variable bytes)
<msg-header-length> (4 bytes)
<msg> (1 or more variable bytes)
"""
#: Per state memory initializers.
_INITIALIZERS = {
'magic_header_left': 4,
'mac_header_left': 4,
'identity_header_left': 4,
'msg_header_left': 4,
}
#: Linear steps/transitions (order matters here).
_TRANSITIONS = tuple([
'magic_header_left',
'mac_header_left',
'mac_left',
'identity_header_left',
'identity_left',
'msg_header_left',
'msg_left',
])
def __init__(self, auth_key, dispatch_func, msg_limit=-1):
if not six.callable(dispatch_func):
raise ValueError("Expected provided dispatch function"
" to be callable")
self.auth_key = auth_key
self.dispatch_func = dispatch_func
msg_limiter = iter_utils.iter_forever(msg_limit)
self.msg_count = six.next(msg_limiter)
self._msg_limiter = msg_limiter
self._buffer = misc.BytesIO()
self._state = None
# Local machine variables and such are stored in here.
self._memory = {}
self._transitions = collections.deque(self._TRANSITIONS)
# This is the per state callback handler set. The first entry reads
# the data and the second entry is called after reading is completed,
# typically to save that data into object memory, or to validate
# it.
self._handlers = {
'magic_header_left': (self._read_field_data,
self._save_and_validate_magic),
'mac_header_left': (self._read_field_data,
functools.partial(self._save_pos_integer,
'mac_left')),
'mac_left': (functools.partial(self._read_data, 'mac'),
functools.partial(self._save_data, 'mac')),
'identity_header_left': (self._read_field_data,
functools.partial(self._save_pos_integer,
'identity_left')),
'identity_left': (functools.partial(self._read_data, 'identity'),
functools.partial(self._save_data, 'identity')),
'msg_header_left': (self._read_field_data,
functools.partial(self._save_pos_integer,
'msg_left')),
'msg_left': (functools.partial(self._read_data, 'msg'),
self._dispatch_and_reset),
}
# Force transition into first state...
self._transition()
def _save_pos_integer(self, key_name, data):
key_val = struct.unpack("!i", data)[0]
if key_val <= 0:
raise IOError("Invalid %s length received for key '%s', expected"
" greater than zero length" % (key_val, key_name))
self._memory[key_name] = key_val
return True
def _save_data(self, key_name, data):
self._memory[key_name] = data
return True
def _dispatch_and_reset(self, data):
self.dispatch_func(
self._memory['identity'],
# Lazy evaluate so the message can be thrown out as needed
# (instead of the receiver discarding it after the fact)...
functools.partial(_decode_message, self.auth_key, data,
self._memory['mac']))
self.msg_count = six.next(self._msg_limiter)
self._memory.clear()
def _transition(self):
try:
self._state = self._transitions.popleft()
except IndexError:
self._transitions.extend(self._TRANSITIONS)
self._state = self._transitions.popleft()
try:
self._memory[self._state] = self._INITIALIZERS[self._state]
except KeyError:
pass
self._handle_func, self._post_handle_func = self._handlers[self._state]
def _save_and_validate_magic(self, data):
magic_header = struct.unpack("!i", data)[0]
if magic_header != MAGIC_HEADER:
raise IOError("Invalid magic header received, expected 0x%x but"
" got 0x%x for message %s" % (MAGIC_HEADER,
magic_header,
self.msg_count + 1))
self._memory['magic'] = magic_header
return True
def _read_data(self, save_key_name, data):
data_len_left = self._memory[self._state]
self._buffer.write(data[0:data_len_left])
if len(data) < data_len_left:
data_len_left -= len(data)
self._memory[self._state] = data_len_left
return ''
else:
self._memory[self._state] = 0
buf_data = self._buffer.getvalue()
self._buffer.reset()
self._post_handle_func(buf_data)
self._transition()
return data[data_len_left:]
def _read_field_data(self, data):
return self._read_data(self._state, data)
@property
def bytes_needed(self):
return self._memory.get(self._state, 0)
def feed(self, data):
while len(data):
data = self._handle_func(data)
class BadHmacValueError(ValueError):
"""Value error raised when an invalid hmac is discovered."""
def _create_random_string(desired_length):
if desired_length <= 0:
return b''
data_length = int(math.ceil(desired_length / 2.0))
data = os.urandom(data_length)
hex_data = binascii.hexlify(data)
return hex_data[0:desired_length]
def _calculate_hmac(auth_key, body):
mac = hmac.new(auth_key, body).hexdigest()
if isinstance(mac, six.text_type):
mac = mac.encode("ascii")
return mac
def _encode_message(auth_key, message, identity, reverse=False):
message = pickle.dumps(message, 2)
message_mac = _calculate_hmac(auth_key, message)
pieces = [
struct.pack("!i", MAGIC_HEADER),
struct.pack("!i", len(message_mac)),
message_mac,
struct.pack("!i", len(identity)),
identity,
struct.pack("!i", len(message)),
message,
]
if reverse:
pieces.reverse()
return tuple(pieces)
def _decode_message(auth_key, message, message_mac):
tmp_message_mac = _calculate_hmac(auth_key, message)
if tmp_message_mac != message_mac:
raise BadHmacValueError('Invalid message hmac')
return pickle.loads(message)
class Channel(object):
"""Object that workers use to communicate back to their creator."""
def __init__(self, port, identity, auth_key):
self.identity = identity
self.port = port
self.auth_key = auth_key
self.dead = False
self._sent = self._received = 0
self._socket = None
self._read_pipe = None
self._write_pipe = None
def close(self):
if self._socket is not None:
self._socket.close()
self._socket = None
self._read_pipe = None
self._write_pipe = None
def _ensure_connected(self):
if self._socket is None:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(1)
try:
s.connect(("", self.port))
except socket.error as e:
with excutils.save_and_reraise_exception():
s.close()
if e.errno in (errno.ECONNREFUSED, errno.ENOTCONN,
errno.ECONNRESET):
# Don't bother with further connections...
self.dead = True
read_pipe = s.makefile("rb", 0)
write_pipe = s.makefile("wb", 0)
try:
msg = self._do_recv(read_pipe=read_pipe)
su.schema_validate(msg, SCHEMAS[CHALLENGE])
if msg != CHALLENGE:
raise IOError("Challenge expected not received")
else:
pieces = _encode_message(self.auth_key,
CHALLENGE_RESPONSE,
self.identity)
self._do_send_and_ack(pieces, write_pipe=write_pipe,
read_pipe=read_pipe)
except Exception:
with excutils.save_and_reraise_exception():
s.close()
else:
self._socket = s
self._read_pipe = read_pipe
self._write_pipe = write_pipe
def recv(self):
self._ensure_connected()
return self._do_recv()
def _do_recv(self, read_pipe=None):
if read_pipe is None:
read_pipe = self._read_pipe
msg_capture = collections.deque(maxlen=1)
msg_capture_func = (lambda _from_who, msg_decoder_func:
msg_capture.append(msg_decoder_func()))
reader = Reader(self.auth_key, msg_capture_func, msg_limit=1)
try:
maybe_msg_num = self._received + 1
bytes_needed = reader.bytes_needed
while True:
blob = read_pipe.read(bytes_needed)
if len(blob) != bytes_needed:
raise EOFError("Read pipe closed while reading %s"
" bytes for potential message %s"
% (bytes_needed, maybe_msg_num))
reader.feed(blob)
bytes_needed = reader.bytes_needed
except StopIteration:
pass
msg = msg_capture[0]
self._received += 1
return msg
def _do_send(self, pieces, write_pipe=None):
if write_pipe is None:
write_pipe = self._write_pipe
for piece in pieces:
write_pipe.write(piece)
write_pipe.flush()
def _do_send_and_ack(self, pieces, write_pipe=None, read_pipe=None):
self._do_send(pieces, write_pipe=write_pipe)
self._sent += 1
msg = self._do_recv(read_pipe=read_pipe)
su.schema_validate(msg, SCHEMAS[ACK])
if msg != ACK:
raise IOError("Failed receiving ack for sent"
" message %s" % self._metrics['sent'])
def send(self, message):
self._ensure_connected()
self._do_send_and_ack(_encode_message(self.auth_key, message,
self.identity))
class EventSender(object):
"""Sends event information from a child worker process to its creator."""
def __init__(self, channel):
self._channel = channel
self._pid = None
def __call__(self, event_type, details):
if not self._channel.dead:
if self._pid is None:
self._pid = os.getpid()
message = {
'event_type': event_type,
'details': details,
'sent_on': time.time(),
}
LOG.trace("Sending %s (from child %s)", message, self._pid)
self._channel.send(message)
class DispatcherHandler(asyncore.dispatcher):
"""Dispatches from a single connection into a target."""
#: Read/write chunk size.
CHUNK_SIZE = 8192
def __init__(self, sock, addr, dispatcher):
if six.PY2:
asyncore.dispatcher.__init__(self, map=dispatcher.map, sock=sock)
else:
super(DispatcherHandler, self).__init__(map=dispatcher.map,
sock=sock)
self.blobs_to_write = list(dispatcher.challenge_pieces)
self.reader = Reader(dispatcher.auth_key, self._dispatch)
self.targets = dispatcher.targets
self.tied_to = None
self.challenge_responded = False
self.ack_pieces = _encode_message(dispatcher.auth_key, ACK,
dispatcher.identity,
reverse=True)
self.addr = addr
def handle_close(self):
self.close()
def writable(self):
return bool(self.blobs_to_write)
def handle_write(self):
try:
blob = self.blobs_to_write.pop()
except IndexError:
pass
else:
sent = self.send(blob[0:self.CHUNK_SIZE])
if sent < len(blob):
self.blobs_to_write.append(blob[sent:])
def _send_ack(self):
self.blobs_to_write.extend(self.ack_pieces)
def _dispatch(self, from_who, msg_decoder_func):
if not self.challenge_responded:
msg = msg_decoder_func()
su.schema_validate(msg, SCHEMAS[CHALLENGE_RESPONSE])
if msg != CHALLENGE_RESPONSE:
raise ChallengeIgnored("Discarding connection from %s"
" challenge was not responded to"
% self.addr)
else:
LOG.trace("Peer %s (%s) has passed challenge sequence",
self.addr, from_who)
self.challenge_responded = True
self.tied_to = from_who
self._send_ack()
else:
if self.tied_to != from_who:
raise UnknownSender("Sender %s previously identified as %s"
" changed there identity to %s after"
" challenge sequence" % (self.addr,
self.tied_to,
from_who))
try:
task = self.targets[from_who]
except KeyError:
raise UnknownSender("Unknown message from %s (%s) not matched"
" to any known target" % (self.addr,
from_who))
msg = msg_decoder_func()
su.schema_validate(msg, SCHEMAS[EVENT])
if LOG.isEnabledFor(logging.TRACE):
msg_delay = max(0, time.time() - msg['sent_on'])
LOG.trace("Dispatching message from %s (%s) (it took %0.3f"
" seconds for it to arrive for processing after"
" being sent)", self.addr, from_who, msg_delay)
task.notifier.notify(msg['event_type'], msg.get('details'))
self._send_ack()
def handle_read(self):
data = self.recv(self.CHUNK_SIZE)
if len(data) == 0:
self.handle_close()
else:
try:
self.reader.feed(data)
except (IOError, UnknownSender):
LOG.warn("Invalid received message", exc_info=True)
self.handle_close()
except _DECODE_ENCODE_ERRORS:
LOG.warn("Badly formatted message", exc_info=True)
self.handle_close()
except (ValueError, su.ValidationError):
LOG.warn("Failed validating message", exc_info=True)
self.handle_close()
except ChallengeIgnored:
LOG.warn("Failed challenge sequence", exc_info=True)
self.handle_close()
class Dispatcher(asyncore.dispatcher):
"""Accepts messages received from child worker processes."""
#: See https://docs.python.org/2/library/socket.html#socket.socket.listen
MAX_BACKLOG = 5
def __init__(self, map, auth_key, identity):
if six.PY2:
asyncore.dispatcher.__init__(self, map=map)
else:
super(Dispatcher, self).__init__(map=map)
self.identity = identity
self.challenge_pieces = _encode_message(auth_key, CHALLENGE,
identity, reverse=True)
self.auth_key = auth_key
self.targets = {}
@property
def port(self):
if self.socket is not None:
return self.socket.getsockname()[1]
else:
return None
def setup(self):
self.targets.clear()
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(("", 0))
LOG.trace("Accepting dispatch requests on port %s", self.port)
self.listen(self.MAX_BACKLOG)
def writable(self):
return False
@property
def map(self):
return self._map
def handle_close(self):
if self.socket is not None:
self.close()
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
addr = "%s:%s" % (addr[0], addr[1])
LOG.trace("Potentially accepted new connection from %s", addr)
DispatcherHandler(sock, addr, self)
class ParallelProcessTaskExecutor(base.ParallelTaskExecutor):
"""Executes tasks in parallel using a process pool executor.
NOTE(harlowja): this executor executes tasks in external processes, so that
implies that tasks that are sent to that external process are pickleable
since this is how the multiprocessing works (sending pickled objects back
and forth) and that the bound handlers (for progress updating in
particular) are proxied correctly from that external process to the one
that is alive in the parent process to ensure that callbacks registered in
the parent are executed on events in the child.
"""
#: Default timeout used by asyncore io loop (and eventually select/poll).
WAIT_TIMEOUT = 0.01
constructor_options = [
('max_workers', lambda v: v if v is None else int(v)),
('wait_timeout', lambda v: v if v is None else float(v)),
]
"""
Optional constructor keyword arguments this executor supports. These will
typically be passed via engine options (by a engine user) and converted
into the correct type before being sent into this
classes ``__init__`` method.
"""
def __init__(self, executor=None,
max_workers=None, wait_timeout=None):
super(ParallelProcessTaskExecutor, self).__init__(
executor=executor, max_workers=max_workers)
self._auth_key = _create_random_string(32)
self._dispatcher = Dispatcher({}, self._auth_key,
_create_random_string(32))
if wait_timeout is None:
self._wait_timeout = self.WAIT_TIMEOUT
else:
if wait_timeout <= 0:
raise ValueError("Provided wait timeout must be greater"
" than zero and not '%s'" % wait_timeout)
self._wait_timeout = wait_timeout
# Only created after starting...
self._worker = None
def _create_executor(self, max_workers=None):
return futurist.ProcessPoolExecutor(max_workers=max_workers)
def start(self):
if threading_utils.is_alive(self._worker):
raise RuntimeError("Worker thread must be stopped via stop()"
" before starting/restarting")
super(ParallelProcessTaskExecutor, self).start()
self._dispatcher.setup()
self._worker = threading_utils.daemon_thread(
asyncore.loop, map=self._dispatcher.map,
timeout=self._wait_timeout)
self._worker.start()
def stop(self):
super(ParallelProcessTaskExecutor, self).stop()
self._dispatcher.close()
if threading_utils.is_alive(self._worker):
self._worker.join()
self._worker = None
def _submit_task(self, func, task, *args, **kwargs):
"""Submit a function to run the given task (with given args/kwargs).
NOTE(harlowja): Adjust all events to be proxies instead since we want
those callbacks to be activated in this process, not in the child,
also since typically callbacks are functors (or callables) we can
not pickle those in the first place...
To make sure people understand how this works, the following is a
lengthy description of what is going on here, read at will:
So to ensure that we are proxying task triggered events that occur
in the executed subprocess (which will be created and used by the
thing using the multiprocessing based executor) we need to establish
a link between that process and this process that ensures that when a
event is triggered in that task in that process that a corresponding
event is triggered on the original task that was requested to be ran
in this process.
To accomplish this we have to create a copy of the task (without
any listeners) and then reattach a new set of listeners that will
now instead of calling the desired listeners just place messages
for this process (a dispatcher thread that is created in this class)
to dispatch to the original task (using a common accepting socket and
per task sender socket that is used and associated to know
which task to proxy back too, since it is possible that there many
be *many* subprocess running at the same time).
Once the subprocess task has finished execution, the executor will
then trigger a callback that will remove the task + target from the
dispatcher (which will stop any further proxying back to the original
task).
"""
progress_callback = kwargs.pop('progress_callback', None)
clone = task.copy(retain_listeners=False)
identity = _create_random_string(32)
channel = Channel(self._dispatcher.port, identity, self._auth_key)
def rebind_task():
# Creates and binds proxies for all events the task could receive
# so that when the clone runs in another process that this task
# can receive the same notifications (thus making it look like the
# the notifications are transparently happening in this process).
needed = set()
for (event_type, listeners) in task.notifier.listeners_iter():
if listeners:
needed.add(event_type)
if progress_callback is not None:
needed.add(ta.EVENT_UPDATE_PROGRESS)
if needed:
sender = EventSender(channel)
for event_type in needed:
clone.notifier.register(event_type, sender)
def register():
if progress_callback is not None:
task.notifier.register(ta.EVENT_UPDATE_PROGRESS,
progress_callback)
self._dispatcher.targets[identity] = task
def deregister(fut=None):
if progress_callback is not None:
task.notifier.deregister(ta.EVENT_UPDATE_PROGRESS,
progress_callback)
self._dispatcher.targets.pop(identity, None)
rebind_task()
register()
try:
fut = self._executor.submit(func, clone, *args, **kwargs)
except RuntimeError:
with excutils.save_and_reraise_exception():
deregister()
fut.atom = task
fut.add_done_callback(deregister)
return fut
|