IMP  2.0.1
The Integrative Modeling Platform
util.py
1 import socket
2 import select
3 import sys
4 import random
5 
6 class _ListenSocket(socket.socket):
7  def __init__(self, host, timeout):
8  socket.socket.__init__(self, socket.AF_INET, socket.SOCK_STREAM)
9  self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
10  self.port = self._bind_to_random_port(host, timeout)
11  self.settimeout(timeout)
12  self.listen(15)
13 
14  def _bind_to_random_port(self, host, timeout):
15  """Bind to a random high-numbered port"""
16  tries = 0
17  while True:
18  port = random.randint(10000, 60000)
19  try:
20  self.bind((host, port))
21  # gaierror is a subclass of error, so catch it separately
22  except socket.gaierror:
23  raise
24  except socket.error:
25  tries += 1
26  if tries > 10: raise
27  else:
28  break
29  return port
30 
31 
32 class _ContextWrapper(object):
33  def __init__(self, obj):
34  self.obj = obj
35 
36 
37 class _TaskWrapper(object):
38  def __init__(self, obj):
39  self.obj = obj
40 
41 
42 class _ErrorWrapper(object):
43  def __init__(self, obj, traceback):
44  self.obj = obj
45  self.traceback = traceback
46 
47 
48 class _HeartBeat(object):
49  pass
50 
51 
52 class _SlaveAction(object):
53  pass
54 
55 
56 class _SetPathAction(_SlaveAction):
57  def __init__(self, path):
58  self.path = path
59  def execute(self):
60  sys.path.insert(0, self.path)
61 
62 
63 if hasattr(select, 'poll'):
64  def _poll_events(listen_sock, slaves, timeout):
65  fileno = listen_sock.fileno()
66  slavemap = { fileno: listen_sock }
67 
68  p = select.poll()
69  p.register(fileno, select.POLLIN)
70  for slave in slaves:
71  fileno = slave._socket.fileno()
72  slavemap[fileno] = slave
73  p.register(fileno, select.POLLIN)
74  ready = p.poll(timeout * 1000)
75  return [slavemap[fd[0]] for fd in ready]
76 
77 else:
78  # Use select on systems that don't have poll()
79  def _poll_events(listen_sock, slaves, timeout):
80  fileno = listen_sock.fileno()
81  slavemap = { fileno: listen_sock }
82  waitin = [fileno]
83 
84  for slave in slaves:
85  fileno = slave._socket.fileno()
86  slavemap[fileno] = slave
87  waitin.append(fileno)
88  (ready,rout,rerr) = select.select(waitin, [], [], timeout)
89  return [slavemap[fd] for fd in ready]