# @package      hubzero-submit-monitors
# @file         MonitorsInfo.py
# @copyright    Copyright (c) 2012-2020 The Regents of the University of California.
# @license      http://opensource.org/licenses/MIT MIT
#
# Copyright (c) 2012-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.path
import pwd
import re
import glob
import socket
import select
import subprocess
import shlex
import traceback
import json
import logging
from errno import EPIPE

from hubzero.submit.LogMessage import getLogPIDMessage as getLogMessage

class MonitorsInfo:
   def __init__(self,
                monitorsPath):
      self.logger = logging.getLogger(__name__)

      self.monitors   = {}
      self.childPid   = 0
      self.bufferSize = 4096

      if os.path.isdir(monitorsPath):
         for monitorsInfoPath in glob.iglob(os.path.join(monitorsPath,'*')):
            self.readMonitorsInfoFile(monitorsInfoPath)
      else:
         for monitorsInfoPath in glob.iglob(monitorsPath):
            self.readMonitorsInfoFile(monitorsInfoPath)

      markedForDeletion = []
      for monitorName in self.monitors:
         if self.monitors[monitorName]['state'] != 'enabled':
            markedForDeletion.append(monitorName)
      for monitorName in markedForDeletion:
         del self.monitors[monitorName]
      del markedForDeletion


   def readMonitorsInfoFile(self,
                            monitorsInfoPath):
      monitorPattern  = re.compile(r'(\s*\[)([^\s]*)(]\s*)')
      keyValuePattern = re.compile(r'( *)(\w*)( *= *)(.*[^\s$])( *)')
      commentPattern  = re.compile(r'\s*#.*')
      monitorName     = ""

      if os.path.exists(monitorsInfoPath):
         try:
            fpInfo = open(monitorsInfoPath,'r')
            try:
               eof = False
               while not eof:
                  record = fpInfo.readline()
                  if record != "":
                     record = commentPattern.sub("",record)
                     if   monitorPattern.match(record):
                        monitorName = monitorPattern.match(record).group(2)
                        self.monitors[monitorName] = {'venue':'',
                                                      'venuePort':22,
                                                      'sshOptions':'',
                                                      'identityManager':'',
                                                      'gsiHost':socket.gethostname(),
                                                      'venueMechanism':'ssh',
                                                      'tunnelDesignator':'',
                                                      'remoteUser':'',
                                                      'x509ProxyPath':'',
                                                      'remoteBinDirectory':'',
                                                      'remoteMonitorCommand':'',
                                                      'state':'enabled'
                                                     }
                     elif keyValuePattern.match(record):
                        key,value = keyValuePattern.match(record).group(2,4)
                        if key in self.monitors[monitorName]:
                           if   isinstance(self.monitors[monitorName][key],list):
                              self.monitors[monitorName][key] = [e.strip() for e in value.split(',')]
                           elif isinstance(self.monitors[monitorName][key],bool):
                              self.monitors[monitorName][key] = bool(value.lower() == 'true')
                           elif isinstance(self.monitors[monitorName][key],float):
                              self.monitors[monitorName][key] = float(value)
                           elif isinstance(self.monitors[monitorName][key],int):
                              self.monitors[monitorName][key] = int(value)
                           elif isinstance(self.monitors[monitorName][key],dict):
                              try:
                                 sampleKey   = list(self.monitors[monitorName][key].keys())[0]
                                 sampleValue = self.monitors[monitorName][key][sampleKey]
                              except:
                                 try:
                                    self.monitors[monitorName][key] = json.loads(value)
                                 except:
                                    self.monitors[monitorName][key] = {}
                                    sampleKey   = "key"
                                    sampleValue = "value"
                              else:
                                 self.monitors[monitorName][key] = {}
               
                              if not self.monitors[monitorName][key]:
                                 for e in value.split(','):
                                    dictKey,dictValue = e.split(':')
                                    if isinstance(sampleKey,int):
                                       dictKey = int(dictKey)
                                    if   isinstance(sampleValue,int):
                                       dictValue = int(dictValue)
                                    elif isinstance(sampleValue,float):
                                       dictValue = float(dictValue)
                                    elif isinstance(sampleValue,bool):
                                       dictValue = bool(dictValue.lower() == 'true')
                                    self.monitors[monitorName][key][dictKey] = dictValue
                           else:
                              self.monitors[monitorName][key] = value
                        else:
                           message = "Undefined key = value pair %s = %s for site %s" % (key,value,monitorName)
                           self.logger.log(logging.WARNING,getLogMessage(message))
                  else:
                     eof = True
            except (IOError,OSError):
               self.logger.log(logging.ERROR,getLogMessage("Monitors configuration file %s could not be read" % \
                                                                                             (monitorsInfoPath)))
            finally:
               fpInfo.close()
         except (IOError,OSError):
            self.logger.log(logging.ERROR,getLogMessage("Monitors configuration file %s could not be opened" % \
                                                                                            (monitorsInfoPath)))
      else:
         self.logger.log(logging.ERROR,getLogMessage("Monitors configuration file %s is missing" % \
                                                                                (monitorsInfoPath)))


   def __writeToStdout(self,
                       message):
      try:
         sys.stdout.write(message)
         sys.stdout.flush()
      except IOError as e:
         if not e.args[0] in [EPIPE]:
            self.logger.log(logging.ERROR,getLogMessage("Can't write to stdout: %s" % (message)))


   def __writeToStderr(self,
                       message):
      try:
         sys.stderr.write(message)
         sys.stderr.flush()
      except IOError as e:
         if not e.args[0] in [EPIPE]:
            self.logger.log(logging.ERROR,getLogMessage("Can't write to stderr: %s" % (message)))


   def getMonitorInfo(self,
                      monitorDesignator):
      monitorInfo = {}
      monitorName = ""
      if monitorDesignator in self.monitors:
         monitorName = monitorDesignator
      else:
         for monitorInfoName in self.monitors:
            if re.match(monitorInfoName,monitorDesignator):
               self.monitors[monitorDesignator] = {}
               venueTemplate                                            = self.monitors[monitorInfoName]['venue']
               self.monitors[monitorDesignator]['venue']                = venueTemplate.replace('@@{name}',monitorDesignator)
               self.monitors[monitorDesignator]['venuePort']            = self.monitors[monitorInfoName]['venuePort']
               self.monitors[monitorDesignator]['sshOptions']           = self.monitors[monitorInfoName]['sshOptions']
               self.monitors[monitorDesignator]['venueMechanism']       = self.monitors[monitorInfoName]['venueMechanism']
               self.monitors[monitorDesignator]['tunnelDesignator']     = self.monitors[monitorInfoName]['tunnelDesignator']
               self.monitors[monitorDesignator]['remoteUser']           = self.monitors[monitorInfoName]['remoteUser']
               self.monitors[monitorDesignator]['identityManager']      = self.monitors[monitorInfoName]['identityManager']
               self.monitors[monitorDesignator]['x509ProxyPath']        = self.monitors[monitorInfoName]['x509ProxyPath']
               self.monitors[monitorDesignator]['remoteMonitorCommand'] = self.monitors[monitorInfoName]['remoteMonitorCommand']
               self.monitors[monitorDesignator]['state']                = self.monitors[monitorInfoName]['state']
               monitorName = monitorDesignator
               break

      if monitorName:
         monitorInfo['monitorName'] = monitorName
         for key in self.monitors[monitorName]:
            monitorInfo[key] = self.monitors[monitorName][key]
      else:
         message = "Could not retrieve MonitorInfo for %s." % (monitorDesignator)
         self.logger.log(logging.ERROR,getLogMessage(message))

      return(monitorInfo)


   def __executeCommand(self,
                        command,
                        streamOutput=False):
      commandArgs = shlex.split(command)
      child = subprocess.Popen(commandArgs,bufsize=self.bufferSize,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
      self.childPid = child.pid
      childout      = child.stdout
      childoutFd    = childout.fileno()
      childerr      = child.stderr
      childerrFd    = childerr.fileno()

      outEOF = False
      errEOF = False

      outData = []
      errData = []

      while True:
         toCheck = []
         if not outEOF:
            toCheck.append(childoutFd)
         if not errEOF:
            toCheck.append(childerrFd)
         try:
            ready = select.select(toCheck,[],[]) # wait for input
         except select.error:
            ready = {}
            ready[0] = []
         if childoutFd in ready[0]:
            outChunk = os.read(childoutFd,self.bufferSize).decode('utf-8')
            if outChunk == '':
               outEOF = True
            outData.append(outChunk)
            if streamOutput:
               self.__writeToStdout(outChunk)

         if childerrFd in ready[0]:
            errChunk = os.read(childerrFd,self.bufferSize).decode('utf-8')
            if errChunk == '':
               errEOF = True
            errData.append(errChunk)
            if streamOutput:
               self.__writeToStderr(errChunk)

         if outEOF and errEOF:
            break

      pid,err = os.waitpid(self.childPid,0)
      self.childPid = 0
      if err != 0:
         if   os.WIFSIGNALED(err):
            self.logger.log(logging.ERROR,getLogMessage("%s failed w/ signal %d" % (command,os.WTERMSIG(err))))
         else:
            if os.WIFEXITED(err):
               err = os.WEXITSTATUS(err)
            self.logger.log(logging.ERROR,getLogMessage("%s failed w/ exit code %d" % (command,err)))
         if not streamOutput:
            self.logger.log(logging.ERROR,getLogMessage("%s" % ("".join(errData))))

      return(err,"".join(outData),"".join(errData))


