# @package      hubzero-submit-monitors
# @file         ProbeMonitor.py
# @copyright    Copyright (c) 2004-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2004-2020 The Regents of the University of California.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# HUBzero is a registered trademark of The Regents of the University of California.
#
import sys
import os
import select
import signal
import time
import logging
from errno import EINTR

from hubzero.submit.LogMessage   import getLogPIDMessage as getLogMessage
from hubzero.submit.DaemonsInfo  import DaemonsInfo
from hubzero.submit.ProbeMonitor import ProbeMonitor

class MonitorProbe:
   def __init__(self,
                daemonsDirectory,
                daemonsConfigurationFile,
                dumpFilePath,
                activityUpdateInterval):
      self.logger = logging.getLogger(__name__)
 
      configFilePath = os.path.join(daemonsDirectory,daemonsConfigurationFile)
      daemonsInfo    = DaemonsInfo(configFilePath)
      self.listenURI = daemonsInfo.getDaemonListenURI('probeMonitor','tcp')
      self.dumpFilePath = dumpFilePath
      self.activityUpdateInterval = activityUpdateInterval
      self.probeMonitor = ProbeMonitor(self.listenURI,
                                       activeProbeDumpPath=self.dumpFilePath)

      self.terminateProbeMonitor = False

      self.exitSystemCallOnInterrupt = False

      signal.signal(signal.SIGINT,self.sigINT_handler)
      signal.signal(signal.SIGHUP,self.sigHUP_handler)
      signal.signal(signal.SIGQUIT,self.sigQUIT_handler)
      signal.signal(signal.SIGABRT,self.sigABRT_handler)
      signal.signal(signal.SIGTERM,self.sigTERM_handler)


   def terminate(self):
      self.terminateProbeMonitor = True


   def sigGEN_handler(self,
                      signalNumber,
                      frame):
      self.terminate()
      if self.exitSystemCallOnInterrupt:
         if sys.version_info > (3,):
            raise InterruptedError(EINTR,"System Call Interrupt")


   def sigINT_handler(self,
                      signalNumber,
                      frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGINT!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigHUP_handler(self,
                      signalNumber,
                      frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGHUP!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigQUIT_handler(self,
                       signalNumber,
                       frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGQUIT!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigABRT_handler(self,
                       signalNumber,
                       frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGABRT!"))
      self.sigGEN_handler(signalNumber,frame)


   def sigTERM_handler(self,
                       signalNumber,
                       frame):
      self.logger.log(logging.INFO,getLogMessage("Received SIGTERM!"))
      self.sigGEN_handler(signalNumber,frame)


   def monitor(self):
      if not self.probeMonitor.isListening():
         self.logger.log(logging.ERROR,getLogMessage("Port binding failed"))
         sys.exit(1)

      self.logger.log(logging.INFO,getLogMessage("******************************"))
      self.logger.log(logging.INFO,getLogMessage("* grid probe monitor started *"))
      self.logger.log(logging.INFO,getLogMessage("******************************"))

      while True:
         listeningSocket,activeReaders = self.probeMonitor.getInputObjects()
         activeWriters                 = self.probeMonitor.getOutputObjects()
         if not listeningSocket and not activeReaders and not activeWriters:
            self.logger.log(logging.INFO,getLogMessage("******************************"))
            self.logger.log(logging.INFO,getLogMessage("* grid probe monitor stopped *"))
            self.logger.log(logging.INFO,getLogMessage("******************************"))
            break

         try:
            self.exitSystemCallOnInterrupt = True
            readyReaders,readyWriters,readyExceptions = select.select(listeningSocket+activeReaders,
                                                                      activeWriters,
                                                                      [],
                                                                      self.activityUpdateInterval)
         except select.error as e:
            if e.args[0] == EINTR:
               readyReaders = []
               readyWriters = []
            else:
               self.terminate()
         finally:
            self.exitSystemCallOnInterrupt = False

         for readyReader in readyReaders:
            if   readyReader in listeningSocket:
               if not self.probeMonitor.acceptConnection():
                  self.logger.log(logging.ERROR,getLogMessage("Connection failed."))
            elif readyReader in activeReaders:
               self.probeMonitor.receiveMessage(readyReader)

         self.probeMonitor.processRequests()

         for readyWriter in readyWriters:
            if readyWriter in activeWriters:
               self.probeMonitor.sendMessage(readyWriter)

         if self.terminateProbeMonitor:
            self.probeMonitor.terminate()


