2018-01-07 21:50:41 +01:00
|
|
|
#!/usr/bin/python
|
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
"""!
|
|
|
|
|
____ ____ ______ __ __ __ _____
|
|
|
|
|
/ __ )/ __ \/ ___/ | / /___ _/ /______/ /_ |__ /
|
|
|
|
|
/ __ / / / /\__ \| | /| / / __ `/ __/ ___/ __ \ /_ <
|
|
|
|
|
/ /_/ / /_/ /___/ /| |/ |/ / /_/ / /_/ /__/ / / / ___/ /
|
|
|
|
|
/_____/\____//____/ |__/|__/\__,_/\__/\___/_/ /_/ /____/
|
|
|
|
|
German BOS Information Script
|
|
|
|
|
by Bastian Schroll
|
|
|
|
|
|
|
|
|
|
@file: server.py
|
|
|
|
|
@date: 11.12.2017
|
|
|
|
|
@author: Bastian Schroll
|
|
|
|
|
@description: Class implementation for a threaded TCP socket server
|
|
|
|
|
"""
|
|
|
|
|
import logging
|
|
|
|
|
import socketserver
|
|
|
|
|
import threading
|
2018-01-12 09:02:26 +01:00
|
|
|
import time
|
2018-01-07 21:50:41 +01:00
|
|
|
|
|
|
|
|
logging.debug("- %s loaded", __name__)
|
|
|
|
|
|
2018-02-03 22:32:28 +01:00
|
|
|
# module wide global list for received data sets
|
|
|
|
|
_dataPackets = []
|
2018-02-02 23:43:05 +01:00
|
|
|
_lockDataPackets = threading.Lock()
|
|
|
|
|
|
2018-02-03 22:32:28 +01:00
|
|
|
# module wide global list for all currently connected clients
|
|
|
|
|
_clients = {} # _clients[ThreadName] = {"address", "timestamp"}
|
2018-01-12 09:50:46 +01:00
|
|
|
_lockClients = threading.Lock()
|
|
|
|
|
|
2018-01-07 21:50:41 +01:00
|
|
|
|
|
|
|
|
class TCPHandler(socketserver.BaseRequestHandler):
|
|
|
|
|
"""!RequestHandler class for our TCPServer class."""
|
|
|
|
|
|
|
|
|
|
def handle(self):
|
|
|
|
|
"""!Handles the request from an single client in a own thread
|
|
|
|
|
|
|
|
|
|
Insert a request in the clients[] list and send a [ack]"""
|
2018-02-02 23:43:05 +01:00
|
|
|
with _lockClients:
|
|
|
|
|
_clients[threading.current_thread().name] = {"address": self.client_address[0], "timestamp": time.time()}
|
|
|
|
|
|
|
|
|
|
logging.info("Client connected: %s", self.client_address[0])
|
|
|
|
|
data = 1 # to enter while loop
|
2018-01-12 12:33:41 +01:00
|
|
|
cur_thread = threading.current_thread().name
|
2018-01-07 21:50:41 +01:00
|
|
|
req_name = str(cur_thread) + " " + self.client_address[0]
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
while data:
|
|
|
|
|
data = str(self.request.recv(1024).strip(), 'utf-8')
|
2018-09-18 05:59:38 +02:00
|
|
|
if data != "":
|
|
|
|
|
logging.debug("%s recv: %s", req_name, data)
|
2018-01-07 21:50:41 +01:00
|
|
|
|
|
|
|
|
# add a new entry at first position (index 0) with client IP
|
2018-01-13 09:56:46 +01:00
|
|
|
# and the decoded data dict as an string in utf-8 and an timestamp
|
2018-02-02 23:43:05 +01:00
|
|
|
with _lockDataPackets:
|
|
|
|
|
_dataPackets.insert(0, (self.client_address[0], data, time.time())) # time() to calc time in queue
|
2018-01-07 21:50:41 +01:00
|
|
|
logging.debug("Add data to queue")
|
|
|
|
|
|
2018-09-18 05:59:38 +02:00
|
|
|
logging.debug("%s send: [ack]", req_name)
|
2018-01-07 21:50:41 +01:00
|
|
|
self.request.sendall(bytes("[ack]", "utf-8"))
|
|
|
|
|
self.request.close()
|
|
|
|
|
|
|
|
|
|
except (ConnectionResetError, ConnectionAbortedError): # pragma: no cover
|
2018-09-18 05:59:38 +02:00
|
|
|
logging.debug("%s connection closed", req_name)
|
2018-01-07 21:50:41 +01:00
|
|
|
except: # pragma: no cover
|
2018-09-18 05:59:38 +02:00
|
|
|
logging.exception("%s error while receiving", req_name)
|
2018-02-02 23:43:05 +01:00
|
|
|
finally:
|
|
|
|
|
with _lockClients:
|
|
|
|
|
del _clients[threading.current_thread().name]
|
|
|
|
|
logging.info("Client disconnected: %s", self.client_address[0])
|
2018-01-07 21:50:41 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class TCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
|
|
|
|
|
"""!TCP server class"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, timeout=3):
|
|
|
|
|
"""!Create a new instance"""
|
|
|
|
|
self._server = None
|
|
|
|
|
self._server_thread = None
|
|
|
|
|
self._timeout = timeout
|
|
|
|
|
|
|
|
|
|
def start(self, port=8080):
|
|
|
|
|
"""!Start a threaded TCP socket server
|
|
|
|
|
|
|
|
|
|
Start a TCP Socket Server in a new thread that will
|
|
|
|
|
then start one more thread for each client request.
|
|
|
|
|
The ip address for binding the server socket is always 'localhost'
|
|
|
|
|
|
|
|
|
|
@param port: Server Port (8080)
|
|
|
|
|
|
|
|
|
|
@return True or False"""
|
|
|
|
|
try:
|
2018-01-13 13:22:28 +01:00
|
|
|
self._server = socketserver.ThreadingTCPServer(("", port), TCPHandler)
|
2018-01-07 21:50:41 +01:00
|
|
|
self._server.timeout = self._timeout
|
|
|
|
|
|
2018-09-09 16:16:55 +02:00
|
|
|
self.flushQueue()
|
2018-01-07 21:50:41 +01:00
|
|
|
|
|
|
|
|
self._server_thread = threading.Thread(target=self._server.serve_forever)
|
2018-01-12 09:02:26 +01:00
|
|
|
self._server_thread.name = "Thread-BWServer"
|
2018-01-07 21:50:41 +01:00
|
|
|
self._server_thread.daemon = True
|
|
|
|
|
self._server_thread.start()
|
2018-09-18 05:59:38 +02:00
|
|
|
logging.debug("TCPServer started in Thread: %s", self._server_thread.name)
|
2018-01-07 21:50:41 +01:00
|
|
|
return True
|
|
|
|
|
except OSError:
|
|
|
|
|
logging.exception("server always running?")
|
|
|
|
|
except: # pragma: no cover
|
|
|
|
|
logging.exception("cannot start the server")
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
|
"""!Stops the TCP socket server
|
|
|
|
|
|
|
|
|
|
@return True or False"""
|
|
|
|
|
try:
|
|
|
|
|
self._server.shutdown()
|
|
|
|
|
self._server_thread.join()
|
|
|
|
|
self._server.socket.close()
|
|
|
|
|
logging.debug("TCPServer stopped")
|
|
|
|
|
return True
|
|
|
|
|
except AttributeError:
|
|
|
|
|
logging.exception("cannot stop - server not started?")
|
|
|
|
|
return False
|
|
|
|
|
except: # pragma: no cover
|
|
|
|
|
logging.exception("cannot stop the server")
|
|
|
|
|
return False
|
|
|
|
|
|
2018-01-08 08:09:23 +01:00
|
|
|
@staticmethod
|
2018-02-02 23:43:05 +01:00
|
|
|
def countClientsConnected():
|
2018-01-07 21:50:41 +01:00
|
|
|
"""!Number of currently connected Clients
|
|
|
|
|
|
|
|
|
|
@return Connected clients"""
|
2018-02-02 23:43:05 +01:00
|
|
|
with _lockClients:
|
|
|
|
|
return len(_clients)
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def getClientsConnected():
|
|
|
|
|
# todo insert comment
|
|
|
|
|
# todo return full list or write a print/debug method?
|
|
|
|
|
return _clients
|
2018-01-07 21:50:41 +01:00
|
|
|
|
2018-01-08 08:09:23 +01:00
|
|
|
@staticmethod
|
2018-02-03 22:32:28 +01:00
|
|
|
def getDataFromQueue():
|
2018-01-07 21:50:41 +01:00
|
|
|
"""!Function to get the data packages from server
|
|
|
|
|
must be polled by main program
|
|
|
|
|
|
|
|
|
|
@return Next data packet.py from intern queue"""
|
2018-02-02 23:43:05 +01:00
|
|
|
if _dataPackets:
|
|
|
|
|
with _lockDataPackets:
|
|
|
|
|
message = _dataPackets.pop()
|
2018-01-07 21:50:41 +01:00
|
|
|
logging.debug("Get data from queue")
|
|
|
|
|
return message
|
|
|
|
|
return None
|
|
|
|
|
|
2018-01-12 18:58:14 +01:00
|
|
|
@staticmethod
|
|
|
|
|
def countPacketsInQueue():
|
|
|
|
|
"""!Get packets waiting in queue
|
|
|
|
|
|
|
|
|
|
@return Packets in queue"""
|
2018-02-02 23:43:05 +01:00
|
|
|
return len(_dataPackets) # no lock needed - only reading
|
2018-01-12 18:58:14 +01:00
|
|
|
|
2018-01-08 08:09:23 +01:00
|
|
|
@staticmethod
|
2018-09-09 16:16:55 +02:00
|
|
|
def flushQueue():
|
2018-01-07 21:50:41 +01:00
|
|
|
"""!To flush all existing data in queue"""
|
2018-01-12 09:50:46 +01:00
|
|
|
logging.debug("Flush data queue")
|
2018-02-02 23:43:05 +01:00
|
|
|
with _lockDataPackets:
|
|
|
|
|
_dataPackets.clear()
|