Skip to content
Snippets Groups Projects
SignalHandler.py 14.4 KiB
Newer Older
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
__author__ = 'Manuela Kuhn <manuela.kuhn@desy.de>', 'Marco Strutz <marco.strutz@desy.de>'

import time
import zmq
import logging
import os
import sys
import traceback
import copy
from multiprocessing import Process
from WorkerProcess import WorkerProcess

#path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
SHARED_PATH = os.path.dirname ( os.path.dirname ( os.path.realpath ( __file__ ) ) ) + os.sep + "shared"

if not SHARED_PATH in sys.path:
    sys.path.append ( SHARED_PATH )
del SHARED_PATH

import helperScript

#
#  --------------------------  class: SignalHandler  --------------------------------------
#
class SignalHandler():
    def __init__(self,
                 whiteList,
                 comPort, signalFwPort, requestPort,
                 context = None):

        # to get the logging only handling this class
        log                 = None


        self.context         = context or zmq.Context()
        self.localhost       = "127.0.0.1"
        self.extIp           = "0.0.0.0"
        self.comPort         = comPort
        self.signalFwPort    = signalFwPort
        self.requestPort     = requestPort
        self.openConnections = []

        self.openRequVari    = []
        self.openRequPerm    = []
        self.allowedQueries  = []

        self.whiteList       = []

        #remove .desy.de from hostnames
        for host in whiteList:
            if host.endswith(".desy.de"):
                self.whiteList.append(host[:-8])
            else:
                self.whiteList.append(host)

        # sockets
        self.comSocket      = None
        self.signalFwSocket = None
        self.requestSocket  = None

        self.log = self.getLogger()
        self.log.debug("Init")

        self.createSockets()

        try:
            self.run()
        except KeyboardInterrupt:
            pass
        except:
            trace = traceback.format_exc()
            self.log.info("Stopping signalHandler due to unknown error condition.")
            self.log.debug("Error was: " + str(trace))


    def getLogger(self):
        logger = logging.getLogger("SignalHandler")
        return logger


    def createSockets(self):

        # create zmq socket for signal communication with receiver
        self.comSocket = self.context.socket(zmq.REP)
        connectionStr  = "tcp://{ip}:{port}".format(ip=self.extIp, port=self.comPort)
        try:
            self.comSocket.bind(connectionStr)
            self.log.info("comSocket started (bind) for '" + connectionStr + "'")
        except Exception as e:
            self.log.error("Failed to start comSocket (bind): '" + connectionStr + "'")
            self.log.debug("Error was:" + str(e))

        # setting up router for load-balancing worker-processes.
        # each worker-process will handle a file event
        self.signalFwSocket = self.context.socket(zmq.REP)
        connectionStr       = "tcp://{ip}:{port}".format(ip=self.localhost, port=self.signalFwPort)
        try:
            self.signalFwSocket.bind(connectionStr)
            self.log.debug("signalFwSocket started (bind) for '" + connectionStr + "'")
        except Exception as e:
            self.log.error("Failed to start signalFwSocket (bind): '" + connectionStr + "'")
            self.log.debug("Error was:" + str(e))

        # create socket to receive requests
        self.requestSocket = self.context.socket(zmq.PULL)
        connectionStr      = "tcp://{ip}:{port}".format(ip=self.extIp, port=self.requestPort)
        try:
            self.requestSocket.bind(connectionStr)
            self.log.debug("requestSocket started (bind) for '" + connectionStr + "'")
        except Exception as e:
            self.log.error("Failed to start requestSocket (bind): '" + connectionStr + "'")
            self.log.debug("Error was:" + str(e))

        # Poller to distinguish between start/stop signals and queries for the next set of signals
        self.poller = zmq.Poller()
        self.poller.register(self.comSocket, zmq.POLLIN)
        self.poller.register(self.signalFwSocket, zmq.POLLIN)
        self.poller.register(self.requestSocket, zmq.POLLIN)


    def run(self):
        #run loop, and wait for incoming messages
        self.log.debug("Waiting for new signals or requests.")
        while True:
            socks = dict(self.poller.poll())

            if self.signalFwSocket in socks and socks[self.signalFwSocket] == zmq.POLLIN:

                try:
                    incomingMessage = self.signalFwSocket.recv()
                    if incomingMessage == "STOP":
                        self.signalFwSocket.send(incomingMessage)
                        break
                    self.log.debug("New request for signals received.")

                    openRequests = self.openRequPerm + self.openRequVari
                    self.openRequVari = []
                    if openRequests:
                        self.signalFwSocket.send_multipart(openRequests)
                        self.log.debug("Answered to request: " + str(openRequests))
                    else:
                        openRequests = ["None"]
                        self.signalFwSocket.send_multipart(openRequests)
                        self.log.debug("Answered to request: " + str(openRequests))
                except Exception, e:
                    self.log.error("Failed to receive/answer new signal requests.")
                    trace = traceback.format_exc()
                    self.log.debug("Error was: " + str(trace))
                continue

            if self.comSocket in socks and socks[self.comSocket] == zmq.POLLIN:

                incomingMessage = self.comSocket.recv_multipart()
                self.log.debug("Received signal: " + str(incomingMessage) )

                checkStatus, signal, host, port = self.checkSignal(incomingMessage)
                if not checkStatus:
                    continue

                self.reactToSignal(signal, host, port)

            if self.requestSocket in socks and socks[self.requestSocket] == zmq.POLLIN:

                incomingMessage = self.requestSocket.recv_multipart()
                self.log.debug("Received request: " + str(incomingMessage) )

                if incomingMessage[1] in self.allowedQueries:
                    self.openRequVari.append(incomingMessage[1])
                    self.log.debug("Add to openRequVari: " + incomingMessage[1] )


    def checkSignal(self, incomingMessage):

        if len(incomingMessage) != 4:

            log.info("Received signal is of the wrong format")
            log.debug("Received signal is too short or too long: " + str(incomingMessage))
            return False, None, None, None

        else:

            version, signal, host, port = incomingMessage

            if host.startswith("["):
                # remove "['" and "']" at the beginning and the end
                host = host[2:-2].split("', '")
            else:
                host = [host]

            if port.startswith("["):
                port = port[2:-2].split("', '")
            else:
                port = [port]

            if version:
                if helperScript.checkVersion(version, self.log):
                    self.log.debug("Versions are compatible: " + str(version))
                else:
                    self.log.debug("Version are not compatible")
                    self.sendResponse("VERSION_CONFLICT")
                    return False, None, None, None

            if signal and host and port :

                # Checking signal sending host
                self.log.debug("Check if signal sending host is in WhiteList...")
                if helperScript.checkHost(host, self.whiteList, self.log):
                    self.log.debug("Hosts are allowed to connect.")
                    self.log.debug("hosts: " + str(host))
                else:
                    self.log.debug("One of the hosts is not allowed to connect.")
                    self.log.debug("hosts: " + str(host))
                    self.sendResponse("NO_VALID_HOST")
                    return False, None, None, None

        return True, signal, host, port


    def sendResponse(self, signal):
            self.log.debug("send confirmation back to receiver: " + str(signal) )
            self.comSocket.send(signal, zmq.NOBLOCK)


    def reactToSignal(self, signal, host, port):

        # React to signal
        if signal == "START_STREAM":
            #FIXME
            host = host[0]
            port = port[0]
            socketId = host + ":" + port
            self.log.info("Received signal: " + signal + " to host " + str(socketId))

            if socketId in self.openRequPerm:
                self.log.info("Connection to " + str(socketId) + " is already open")
                self.sendResponse("CONNECTION_ALREADY_OPEN")
            else:
                # send signal back to receiver
                self.sendResponse(signal)
                self.log.debug("Send response back: " + str(signal))
                self.openRequPerm.append(socketId)

            return

        elif signal == "STOP_STREAM":
            #FIXME
            host = host[0]
            port = port[0]
            socketId = host + ":" + port
            self.log.info("Received signal: " + signal + " to host " + str(socketId))

            if socketId in self.openRequPerm:
                # send signal back to receiver
                self.sendResponse(signal)
                self.log.debug("Send response back: " + str(signal))
                self.openRequPerm.remove(socketId)
            else:
                self.log.info("No connection to close was found for " + str(socketId))
                self.sendResponse("NO_OPEN_CONNECTION_FOUND")

            return

        elif signal == "START_QUERY_NEXT":
            self.log.info("Received signal to enable querying for data for hosts: " + str(host))
            connectionFound = False
            tmpAllowed = []
            for h in host:
                for p in port:
                    socketId = h + ":" + p
                    if socketId in self.allowedQueries:
                        connectionFound = True
                        self.log.info("Connection to " + str(socketId) + " is already open")
                        self.sendResponse("CONNECTION_ALREADY_OPEN")
                    elif socketId not in tmpAllowed:
                        tmpAllowed.append(socketId)
                    else:
                        #TODO send notification (double entries in START_QUERY_NEXT) back?
                        pass

            if not connectionFound:
                # send signal back to receiver
                self.sendResponse(signal)
                self.allowedQueries += tmpAllowed
                self.log.debug("Send response back: " + str(signal))

            return

        elif signal == "STOP_QUERY_NEXT":
            self.log.info("Received signal to disable querying for data for hosts: " + str(host))
            connectionNotFound = False
            for h in host:
                for p in port:
                    socketId = h + ":" + p
                    if socketId in self.allowedQueries:
                        self.allowedQueries.remove(socketId)
                    else:
                        connectionNotFound = True

            if connectionNotFound:
                self.log.info("No connection to close was found for " + str(socketId))
                self.sendResponse("NO_OPEN_CONNECTION_FOUND")
            else:
                # send signal back to receiver
                self.sendResponse(signal)
                self.log.debug("Send response back: " + str(signal))

            return

        else:
            self.log.info("Received signal from host " + str(host) + " unkown: " + str(signal))
            self.sendResponse("NO_VALID_SIGNAL")


    def stop(self):
        self.log.debug("Closing sockets")
        self.comSocket.close(0)
        self.signalFwSocket.close(0)
        self.requestSocket.close(0)


    def __exit__(self):
        self.stop()


    def __del__(self):
        self.stop()


if __name__ == '__main__':
    from multiprocessing import Process
    import time

    helperScript.initLogging("/space/projects/live-viewer/logs/signalHandler.log", verbose=True, onScreenLogLevel="debug")


    whiteList     = ["localhost", "zitpcx19282"]
    comPort       = "6000"
    requestFwPort = "6001"
    requestPort   = "6002"
    signalHandlerProcess = Process ( target = SignalHandler, args = (whiteList, comPort, requestFwPort, requestPort) )

    signalHandlerProcess.start()


    def sendSignal(socket, signal, port):
        sendMessage = ["0.0.1",  signal, "zitpcx19282", port]
        socket.send_multipart(sendMessage)
        receivedMessage = socket.recv()
        logging.info("=== Responce : " + receivedMessage )

    def sendRequest(socket, socketId):
        sendMessage = ["NEXT", socketId]
        socket.send_multipart(sendMessage)
        logging.info("=== request sent: " + str(sendMessage))


    def getRequests(socket):
        socket.send("")
        requests = socket.recv_multipart()
        logging.info("=== Requests: " + str(requests))


    context         = zmq.Context.instance()
    comSocket       = context.socket(zmq.REQ)
    connectionStr   = "tcp://zitpcx19282:" + comPort
    comSocket.connect(connectionStr)
    logging.info("=== comSocket connected to " + connectionStr)

    requestSocket   = context.socket(zmq.PUSH)
    connectionStr   = "tcp://zitpcx19282:" + requestPort
    requestSocket.connect(connectionStr)
    logging.info("=== requestSocket connected to " + connectionStr)

    requestFwSocket = context.socket(zmq.REQ)
    connectionStr   = "tcp://localhost:" + requestFwPort
    requestFwSocket.connect(connectionStr)
    logging.info("=== requestFwSocket connected to " + connectionStr)



    sendSignal(comSocket, "START_STREAM", "6003")
    getRequests(requestFwSocket)

    sendSignal(comSocket, "START_STREAM", "6004")
    getRequests(requestFwSocket)

    sendSignal(comSocket, "STOP_STREAM", "6003")
    getRequests(requestFwSocket)

    sendRequest(requestSocket, "zitpcx19282:6006")
    getRequests(requestFwSocket)

    sendSignal(comSocket, "START_QUERY_NEXT", "6005")
    getRequests(requestFwSocket)

    sendRequest(requestSocket, "zitpcx19282:6005")
    getRequests(requestFwSocket)
    getRequests(requestFwSocket)


    requestFwSocket.send("STOP")
    requests = requestFwSocket.recv()
    logging.debug("=== Requests: " + requests)

    signalHandlerProcess.join()

    comSocket.close(0)
    requestSocket.close(0)
    requestFwSocket.close(0)
    context.destroy()