This repository has been archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPilotTCPServer.py
48 lines (40 loc) · 1.82 KB
/
PilotTCPServer.py
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
from SocketServer import TCPServer
import threading
import random
import socket
from pUtil import tolog
class PilotTCPServer(threading.Thread):
""" TCP server used to send TCP messages from runJob to pilot """
def __init__(self, handler, name='PilotTCPServer'):
""" constructor, setting initial variables """
# find an available port to create the TCPServer
n = 0
while n < 20: # try 20 times before giving up, which means run 20 pilots on one machine simultaneously :)
n += 1
self.port = random.randrange(1, 800, 1) + 8888
# avoid known port used for local monitoring (req. by A. de Salvo)
if self.port == 9256:
self.port += 1
try:
self.srv = TCPServer(('localhost',self.port), handler)
except socket.error, e:
tolog("WARNING: Can not create TCP server on port %d, re-try... : %s" % (self.port, str(e)))
else:
# tolog("Using port %d" % self.port)
break
if n >= 20: # raise some exception later ??
self.srv = None
self.port = None
self._stopevent = threading.Event()
threading.Thread.__init__(self, name=name)
def run(self):
""" main control loop """
tolog("%s starts" % str((self.getName( ),)))
while not self._stopevent.isSet():
self.srv.handle_request()
def join(self, timeout=None):
""" Stop the thread and wait for it to end. """
tolog("join called on thread %s" % self.getName())
self._stopevent.set() # signal thread to stop
self.srv.socket.shutdown(2) # shutdown the connection in two-ways
threading.Thread.join(self, timeout) # wait until the thread terminates or timeout occurs