# @package      hubzero-submit-monitors
# @file         MeasureJobs.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 signal
import time
import logging
from errno import EINTR

from hubzero.submit.LogMessage import getLogPIDMessage as getLogMessage
from hubzero.submit.JobMetrics import JobMetrics

class MeasureJobs:
   def __init__(self,
                daemonsDirectory,
                daemonsConfigurationFile,
                infosDirectory,
                infosConfigurationFile,
                previousState,
                nextState):
      self.logger = logging.getLogger(__name__)

      self.timeBetweenJobMetrics = 5
      self.jobActionPending      = False
      self.wsJobActionPending    = False

      self.jobMetrics = JobMetrics(daemonsDirectory,
                                   daemonsConfigurationFile,
                                   infosDirectory,
                                   infosConfigurationFile,
                                   previousState,
                                   nextState)

      self.terminateJobMetrics = self.jobMetrics.setInfo()
      if not self.terminateJobMetrics:
         success,timeBetween = self.jobMetrics.registerJobActionProcess('WSMeasureSim2L')
         if success:
            self.timeBetweenJobMetrics = timeBetween
         else:
            self.terminateJobMetrics = True

      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)
      signal.signal(signal.SIGUSR1,self.sigUSR1_handler)
      signal.signal(signal.SIGUSR2,self.sigUSR2_handler)


   def terminate(self):
      self.terminateJobMetrics = True


   def sigGEN_handler(self,
                      signalNumber,
                      frame):
      self.terminate()


   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 sigUSR1_handler(self,
                       signalNumber,
                       frame):
      self.jobActionPending = True


   def sigUSR2_handler(self,
                       signalNumber,
                       frame):
      self.wsJobActionPending = True


   def process(self):
      self.logger.log(logging.INFO,getLogMessage("***********************"))
      self.logger.log(logging.INFO,getLogMessage("* job metrics started *"))
      self.logger.log(logging.INFO,getLogMessage("***********************"))

      while True:
         if self.terminateJobMetrics:
            self.jobMetrics.terminate()
            self.logger.log(logging.INFO,getLogMessage("***********************"))
            self.logger.log(logging.INFO,getLogMessage("* job metrics stopped *"))
            self.logger.log(logging.INFO,getLogMessage("***********************"))
            break

         if self.wsJobActionPending:
            self.wsJobActionPending = False
            nMeasuredJobs = self.jobMetrics.postToWS()
            if nMeasuredJobs > 0:
               self.logger.log(logging.INFO,getLogMessage("%d jobs reporting" % (nMeasuredJobs)))

         time.sleep(self.timeBetweenJobMetrics)


