Commit fda52b92 authored by Claudio Scafuri's avatar Claudio Scafuri 💬
Browse files

black, flake8 applied

parent c13783a4
This diff is collapsed.
#!/usr/bin/python3
# TCPS server-bridge based on twisted
from twisted.internet.protocol import Protocol, Factory
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet import reactor
#import time
# import time
import sys
import TCPS2tango
import logging
import logging.handlers
#obsolete! must be switched to argparse
# obsolete! must be switched to argparse
import optparse
global_logging=logging.getLogger('TCPS')
global_logging = logging.getLogger("TCPS")
# there should be a cleaner way ... but now I use a GLOBAL.....
#--------------------------------------------------------------
# --------------------------------------------------------------
class twistedTCPS(Protocol):
'adapter of TCPS protocol for twisted package'
"adapter of TCPS protocol for twisted package"
def __init__(self):
self.__myname='default TCPS server'
self.__myname = "default TCPS server"
def connectionMade(self):
if(self.factory._timeout):
self.transport.socket.settimeout(self.factory._timeout) # it is possible to set timeouts!!
self.__peer=self.transport.getPeer()
global_logging.info ('new connection: ' + self.__peer.host + ':' + repr(self.__peer.port))
if self.factory._timeout:
self.transport.socket.settimeout(
self.factory._timeout
) # it is possible to set timeouts!!
self.__peer = self.transport.getPeer()
global_logging.info(
"new connection: " + self.__peer.host + ":" + repr(self.__peer.port)
)
def connectionLost(self, reason):
self.transport.loseConnection()
global_logging.info('connection closed/lost: ' + self.__peer.host + ':' + repr(self.__peer.port))
global_logging.info(
"connection closed/lost: " + self.__peer.host + ":" + repr(self.__peer.port)
)
def dataReceived(self, data):
global_logging.debug("dataReceived " + data.decode().strip())
try:
resp=self.factory.handler.dispatch_call(data.decode().strip())
resp = self.factory.handler.dispatch_call(data.decode().strip())
self.transport.write(resp.encode())
except:
global_logging.error ('exception writing data to ' + self.__peer.host + ':' + repr(self.__peer.port))
except Exception:
global_logging.error(
"exception writing data to "
+ self.__peer.host
+ ":"
+ repr(self.__peer.port)
)
# method to associate TCPS object and other initialization data
def makeTCPSFactory(fname,logger,timeout=None,):
factory=Factory()
factory.protocol=twistedTCPS
factory._fname=fname
factory._timeout=timeout
factory.handler=TCPS2tango.ProxyContainer()
def makeTCPSFactory(
fname,
logger,
timeout=None,
):
factory = Factory()
factory.protocol = twistedTCPS
factory._fname = fname
factory._timeout = timeout
factory.handler = TCPS2tango.ProxyContainer()
factory.handler.add_logger(logger)
factory.handler.parse_conf_file(fname)
return factory
#-----------------------------------------------------------------
#remeber to switch use argparse for configuring cmd line options with python > 2.7
# -----------------------------------------------------------------
# remeber to switch use argparse for configuring cmd line options with python > 2.7
def main(argv=None):
if argv is None:
argv = sys.argv # argv for initializing , etc
#parse comnd line and prepare optinal arguments
parser = optparse.OptionParser(description='TCPStwserver options')
parser.add_option('-f','--configfile',help='configuration file')
parser.add_option('-p', '--port', help='tpc port number [20000]')
parser.add_option('-l','--logfile',help='log_file')
parser.add_option('-v','--loglevel',help='log_level [debug|info|warning|error|critical]')
parser.add_option('-s','--logsize',help='log_file_size')
parser.add_option('-V','--verbose',help='echo debug to console')
(options,argmy) = parser.parse_args()
argv = sys.argv # argv for initializing , etc
# parse comnd line and prepare optinal arguments
parser = optparse.OptionParser(description="TCPStwserver options")
parser.add_option("-f", "--configfile", help="configuration file")
parser.add_option("-p", "--port", help="tpc port number [20000]")
parser.add_option("-l", "--logfile", help="log_file")
parser.add_option(
"-v", "--loglevel", help="log_level [debug|info|warning|error|critical]"
)
parser.add_option("-s", "--logsize", help="log_file_size")
parser.add_option("-V", "--verbose", help="echo debug to console")
(options, argmy) = parser.parse_args()
if options.configfile:
fname=options.configfile
fname = options.configfile
else:
print(('usage: '+sys.argv[0] + ' --configfile= '))
print(("usage: " + sys.argv[0] + " --configfile= "))
return 1
if options.port:
tcpport=int(options.port)
tcpport = int(options.port)
else:
tcpport=20000
tcpport = 20000
if options.logfile:
lfile=options.logfile
lfile = options.logfile
else:
lfile='/dev/null'
lfile = "/dev/null"
if options.loglevel:
lev=options.loglevel
level=-1
if lev=='debug':
level=logging.DEBUG
elif lev=='info':
level=logging.INFO
elif lev=='warning':
level=logging.WARNING
elif lev=='error':
level=logging.ERROR
elif lev=='critical':
level=logging.CRITICAL
elif lev=='notset':
level==logging.NOTSET
lev = options.loglevel
level = -1
if lev == "debug":
level = logging.DEBUG
elif lev == "info":
level = logging.INFO
elif lev == "warning":
level = logging.WARNING
elif lev == "error":
level = logging.ERROR
elif lev == "critical":
level = logging.CRITICAL
elif lev == "notset":
level == logging.NOTSET
else:
lev='notset'
level=logging.NOTSET
lev = "notset"
level = logging.NOTSET
if options.logsize:
mBytes=int(options.logsize)
mBytes = int(options.logsize)
else:
mBytes=2196608
mBytes = 2196608
if options.verbose:
verbose=True
verbose = True
else:
verbose=False
verbose = False
# Set up a specific logger with our desired output level
# use INFO for for tracking all SET operations
# use ERROR and CRITICAL for errors (non-fatal and fatal)
# use INFO and DEBUG for diagnostics
# info is set with -V
#debug is set
logger = logging.getLogger('TCPS')
logger.setLevel(level) #default level is NOTSET
# debug is set
logger = logging.getLogger("TCPS")
logger.setLevel(level) # default level is NOTSET
formatter = logging.Formatter("%(asctime)s\t%(levelname)s\t%(message)s")
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(lfile, maxBytes=mBytes, backupCount=5)
handler = logging.handlers.RotatingFileHandler(
lfile, maxBytes=mBytes, backupCount=5
)
# create and add formatter to logger
handler.setFormatter(formatter)
......@@ -133,21 +160,23 @@ def main(argv=None):
ch.setLevel(level)
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.info('debug echo to console')
logger.info("debug echo to console")
# use special builder to associate our data to TCPS object
# extra arguments are:
# 'internal name'
# timeout for network calls
logger.info('using config file '+fname)
factory=makeTCPSFactory(fname,logger)
logger.info("using config file " + fname)
factory = makeTCPSFactory(fname, logger)
# 20000 is the port assigned to TPCS - backlog que is 20
reactor.listenTCP(tcpport, factory, 10)
# we can also open on multiple ports, just make another instance another reactor object
#reactor.listenTCP(30000, factory,30.0)
logger.debug('entering loop')
# reactor.listenTCP(30000, factory,30.0)
logger.debug("entering loop")
reactor.run()
logger.debug('exit loop')
logger.debug("exit loop")
if __name__ == "__main__":
sys.exit(main())
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment