/usr/lib/python3/dist-packages/pyutilib/pyro/worker.py is in python3-pyutilib 5.3.5-1.
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 | # _________________________________________________________________________
#
# PyUtilib: A Python utility library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
# _________________________________________________________________________
__all__ = ['TaskWorker','MultiTaskWorker','TaskWorkerServer']
import sys
import os
import socket
import time
import itertools
import random
from pyutilib.pyro import get_nameserver, using_pyro3, using_pyro4
from pyutilib.pyro import Pyro as _pyro
from pyutilib.pyro.util import get_dispatchers, _connection_problem
from six import advance_iterator, iteritems, itervalues
from six.moves import xrange
#
# With Pyro3 we check for a different set of errors
# in the run loop so that we don't ignore shutdown
# requests from the dispatcher
#
_worker_connection_problem = None
if using_pyro3:
_worker_connection_problem = (_pyro.errors.TimeoutError, _pyro.errors.ConnectionDeniedError)
elif using_pyro4:
_worker_connection_problem = _pyro.errors.TimeoutError
_worker_task_return_queue_unset = object()
class TaskWorkerBase(object):
def __init__(self,
group=":PyUtilibServer",
host=None,
port=None,
num_dispatcher_tries=30,
caller_name="Task Worker",
verbose=False,
name=None):
self._verbose = verbose
# A worker can set this flag
# if an error occurs during processing
self._worker_error = False
self._worker_shutdown = False
self._worker_task_return_queue = _worker_task_return_queue_unset
# sets whether or not multiple tasks should
# be gathered from the worker queue during
# each request for work
self._bulk_task_collection = False
if _pyro is None:
raise ImportError("Pyro or Pyro4 is not available")
# Deprecated in Pyro3
# Removed in Pyro4
if using_pyro3:
_pyro.core.initClient()
if name is None:
self.WORKERNAME = "Worker_%d@%s" % (os.getpid(),
socket.gethostname())
else:
self.WORKERNAME = name
self.ns = get_nameserver(host=host, port=port, caller_name=caller_name)
if self.ns is None:
raise RuntimeError("TaskWorkerBase failed to locate "
"Pyro name server on the network!")
print('Worker attempting to find Pyro dispatcher object...')
cumulative_sleep_time = 0.0
self.dispatcher = None
for i in xrange(0, num_dispatcher_tries):
dispatchers = get_dispatchers(group=group, ns=self.ns)
random.shuffle(dispatchers)
for name, uri in dispatchers:
try:
if using_pyro3:
self.dispatcher = _pyro.core.getProxyForURI(uri)
else:
self.dispatcher = _pyro.Proxy(uri)
self.dispatcher._pyroTimeout = 10
if not self.dispatcher.register_worker(self.WORKERNAME):
if using_pyro4:
self.dispatcher._pyroRelease()
else:
self.dispatcher._release()
self.dispatcher = None
else:
break
except _connection_problem:
self.dispatcher = None
if self.dispatcher is not None:
if using_pyro4:
self.dispatcher._pyroTimeout = None
break
sleep_interval = random.uniform(5.0, 15.0)
print("Worker failed to find dispatcher object from "
"name server after %d attempts and %5.2f seconds "
"- trying again in %5.2f seconds."
% (i+1, cumulative_sleep_time, sleep_interval))
time.sleep(sleep_interval)
cumulative_sleep_time += sleep_interval
if self.dispatcher is None:
raise RuntimeError(
"Worker could not find dispatcher object - giving up")
# There is no need to retain the proxy connection to the
# nameserver, so free up resources on the nameserver thread
URI = None
if using_pyro4:
self.ns._pyroRelease()
URI = self.dispatcher._pyroUri
else:
self.ns._release()
URI = self.dispatcher.URI
print("Connection to dispatch server %s established "
"after %d attempts and %5.2f seconds - "
"this is worker: %s"
% (URI, i+1, cumulative_sleep_time, self.WORKERNAME))
# Do not release the connection to the dispatcher
# We use this functionality to distribute workers across
# multiple dispatchers based off of denied connections
def close(self):
if self.dispatcher is not None:
self.dispatcher.unregister_worker(self.WORKERNAME)
if using_pyro4:
self.dispatcher._pyroRelease()
else:
self.dispatcher._release()
self.dispather = None
def _get_request_type(self):
raise NotImplementedError("This is an abstract method")
def run(self):
print("Listening for work from dispatcher...")
while 1:
self._worker_error = False
self._worker_shutdown = False
try:
tasks = {}
if self._bulk_task_collection:
tasks = self.dispatcher.get_tasks((self._get_request_type(),))
else:
_type, _block, _timeout = self._get_request_type()
_task = self.dispatcher.get_task(type=_type,
block=_block,
timeout=_timeout)
if _task is not None:
tasks[_type] = [_task]
except _worker_connection_problem as e:
x = sys.exc_info()[1]
# this can happen if the dispatcher is overloaded
print("***WARNING: Connection to dispatcher server "
"denied\n - exception type: "+str(type(e))+
"\n - message: "+str(x))
print("A potential remedy may be to increase "
"PYUTILIB_PYRO_MAXCONNECTIONS in your shell "
"environment.")
# sleep for a bit longer than normal, for obvious reasons
sleep_interval = random.uniform(0.05, 0.15)
time.sleep(sleep_interval)
else:
if len(tasks) > 0:
assert len(tasks) == 1
if self._verbose:
print("Processing %s task(s) from queue %s"
% (len(list(tasks.values())[0]),
list(tasks.keys())[0]))
results = {}
# process tasks by type in order of increasing id
for type_name, type_tasks in iteritems(tasks):
for task in sorted(type_tasks, key=lambda x: x['id']):
self._worker_task_return_queue = \
_worker_task_return_queue_unset
self._current_task_client = task['client']
task['result'] = self.process(task['data'])
task['processedBy'] = self.WORKERNAME
return_type_name = self._worker_task_return_queue
if return_type_name is _worker_task_return_queue_unset:
return_type_name = type_name
if self._worker_error:
if return_type_name not in results:
results[return_type_name] = []
task['processedBy'] = self.WORKERNAME
results[return_type_name].append(task)
print("Task worker reported error during processing "
"of task with id=%s. Any remaining tasks in "
"local queue will be ignored." % (task['id']))
break
if self._worker_shutdown:
self.close()
return
if task['generateResponse']:
if return_type_name not in results:
results[return_type_name] = []
results[return_type_name].append(task)
if self._worker_error:
break
if len(results):
self.dispatcher.add_results(results)
class TaskWorker(TaskWorkerBase):
def __init__(self, type=None, block=True, timeout=None, *args, **kwds):
self.type = type
self.block = block
self.timeout = timeout
TaskWorkerBase.__init__(self, *args, **kwds)
# Called by the run() method to get the work type
# including blocking and timeout options
def _get_request_type(self):
return self.type, self.block, self.timeout
class MultiTaskWorker(TaskWorkerBase):
def __init__(self,
type_default=None,
block_default=True,
timeout_default=5,
*args,
**kwds):
TaskWorkerBase.__init__(self, *args, **kwds)
#
# **NOTE: For this class 'type' is
# a tuple (type, blocking, timeout, local)
#
self._num_types = 0
self._type_cycle = None
self.push_request_type(type_default,
block_default,
timeout_default)
# Called by the run() method to get the next work type to request,
# moves index to the next location in the cycle
def _get_request_type(self):
new = None
try:
new = advance_iterator(self._type_cycle)
except StopIteration:
raise RuntimeError("MultiTaskWorker has no work request types!")
return new
def current_type_order(self):
"""
return the full work type list, starting from the current
location in the cycle.
"""
if self._num_types == 0:
return []
type_list = []
for cnt in xrange(self._num_types):
type_list.append(advance_iterator(self._type_cycle))
return type_list
def cycle_type_order(self):
advance_iterator(self._type_cycle)
def num_request_types(self):
return self._num_types
def clear_request_types(self):
self._type_cycle = itertools.cycle([])
self._num_types = 0
def push_request_type(self, type_name, block, timeout):
"""
add a request type to the end relative to the current cycle
location
"""
self._type_cycle = itertools.cycle(self.current_type_order() + \
[(type_name, block, timeout)])
self._num_types += 1
def pop_request_type(self):
"""
delete the last type request relative to the current cycle
location
"""
new_type_list = self.current_type_order()
el = new_type_list.pop()
self._type_cycle = itertools.cycle(new_type_list)
self._num_types -= 1
return el
def run(self):
print("Listening for work from dispatcher...")
while 1:
self._worker_error = False
self._worker_shutdown = False
try:
tasks = self.dispatcher.get_tasks(self.current_type_order())
except _worker_connection_problem as e:
x = sys.exc_info()[1]
# this can happen if the dispatcher is overloaded
print("***WARNING: Connection to dispatcher server "
"denied\n - exception type: "+str(type(e))+
"\n - message: "+str(x))
print("A potential remedy may be to increase "
"PYUTILIB_PYRO_MAXCONNECTIONS in your shell "
"environment.")
# sleep for a bit longer than normal, for obvious reasons
sleep_interval = random.uniform(0.05, 0.15)
time.sleep(sleep_interval)
else:
if len(tasks) > 0:
if self._verbose:
print("Processing %s tasks from %s queue(s)"
% (sum(len(_tl) for _tl in itervalues(tasks)),
len(tasks)))
results = {}
# process tasks by type in order of increasing id
for type_name, type_tasks in iteritems(tasks):
type_results = results[type_name] = []
for task in sorted(type_tasks, key=lambda x: x['id']):
self._worker_task_return_queue = \
_worker_task_return_queue_unset
self._current_task_client = task['client']
task['result'] = self.process(task['data'])
task['processedBy'] = self.WORKERNAME
return_type_name = self._worker_task_return_queue
if return_type_name is _worker_task_return_queue_unset:
return_type_name = type_name
if self._worker_error:
if return_type_name not in results:
results[return_type_name] = []
results[return_type_name].append(task)
print("Task worker reported error during processing "
"of task with id=%s. Any remaining tasks in "
"local queue will be ignored." % (task['id']))
break
if self._worker_shutdown:
self.close()
return
if task['generateResponse']:
if return_type_name not in results:
results[return_type_name] = []
results[return_type_name].append(task)
if self._worker_error:
break
if len(results):
self.dispatcher.add_results(results)
def TaskWorkerServer(cls, **kwds):
worker = cls(**kwds)
if worker.ns is None:
return
try:
worker.run()
except _pyro.errors.ConnectionClosedError:
print("Lost connection to dispatch server "
"- shutting down...")
|