# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()


from SocketServer import TCPServer
from pUtil import tolog
import threading
import random
import socket
        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. """

# Path: pUtil.py
# def tolog(msg, tofile=True, label='INFO', essential=False):
#     """ Write date+msg to pilot log and to stdout """
# 
#     try:
#         import inspect
# 
#         MAXLENGTH = 12
#         # getting the name of the module that is invoking tolog() and adjust the length
#         try:
#             module_name = os.path.basename(inspect.stack()[1][1])
#         except Exception, e:
#             module_name = "unknown"
#             #print "Exception caught by tolog(): ", e,
#         module_name_cut = module_name[0:MAXLENGTH].ljust(MAXLENGTH)
#         msg = "%i|%s| %s" % (os.getpid(),module_name_cut, msg)
# 
#         t = timeStampUTC(format='%Y-%m-%d %H:%M:%S')
#         if tofile:
#             appendToLog("%s|%s\n" % (t, msg))
# 
#         # remove backquotes from the msg since they cause problems with batch submission of pilot
#         # (might be present in error messages from the OS)
#         msg = msg.replace("`","'")
#         msg = msg.replace('"','\\"')
#         print "%s| %s" % (t, msg)
# 
#         # write any FAILED messages to stderr
#         if "!!FAILED!!" in msg:
#             try:
#                 print >> sys.stderr, "%s| %s" % (t, msg)
#             except:
#                 print "Failed to print to sys.stderr: %s" % (t, msg)
#     except:
#         print "!!WARNING!!4000!! %s" % traceback.format_exc()


# Path: PilotTCPServer.py
from SocketServer import TCPServer
from pUtil import tolog
import threading
import random
import socket

        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())