# @package      hubzero-submit-monitors
# @file         TunnelMonitor.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 os
import re
import subprocess
import shlex
import select
import signal
import json
import logging
import traceback

from hubzero.submit.LogMessage       import getLogIDMessage as getLogMessage
from hubzero.submit.BoundConnections import BoundConnections
from hubzero.submit.TunnelsInfo      import TunnelsInfo

class TunnelMonitor(BoundConnections):
   def __init__(self,
                listenURI,
                tunnelsInfoPath,
                sshIdentity):
      BoundConnections.__init__(self,listenURI,logConnection=False)

      self.logger = logging.getLogger(__name__)

      self.tunnelsInfoPath = tunnelsInfoPath
      self.tunnelsInfo     = TunnelsInfo(self.tunnelsInfoPath)

      self.sshIdentity = sshIdentity

      self.commandBufferSize = 1024
      self.activeTunnels     = {}
      self.terminating       = False


   def terminate(self):
      if not self.terminating:
         self.signalActiveTunnels(signal.SIGTERM)
         self.closeListeningConnection()
         self.terminating = True


   def __executeCommand(self,
                        command):
      commandArgs = shlex.split(command)
      child = subprocess.Popen(commandArgs,bufsize=self.commandBufferSize,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)
      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.commandBufferSize).decode('utf-8')
            if outChunk == '':
               outEOF = True
            outData.append(outChunk)

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

         if outEOF and errEOF:
            break

      pid,err = os.waitpid(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)))
         self.logger.log(logging.ERROR,getLogMessage("%s" % ("".join(errData))))

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


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

      outEOF = False
      errEOF = False

      outData = []
      errData = []

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

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

         if outEOF and errEOF:
            break

         err = child.poll()
         if err > -1:
            break

      if err == -1:
         pid,err = os.waitpid(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)))
         self.logger.log(logging.ERROR,getLogMessage("%s" % ("".join(errData))))

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


   def reloadTunnelsInfo(self):
      del self.tunnelsInfo

      self.tunnelsInfo = TunnelsInfo(self.tunnelsInfoPath)
      self.logger.log(logging.INFO,getLogMessage("Tunnel Info Reloaded!"))


   def signalActiveTunnels(self,
                           signalNumber):
      for activeTunnel in self.activeTunnels:
         try:
            tunnelPid = self.activeTunnels[activeTunnel]['tunnelPid']
            self.logger.log(logging.INFO,getLogMessage("Send TERM to tunnel %s process" % (activeTunnel)))
            os.kill(tunnelPid,signalNumber)
         except:
            self.logger.log(logging.ERROR,getLogMessage(traceback.format_exc()))
            pass


   def processRequests(self):
      for channel in self.activeChannels:
         message = self.pullMessage(channel,0)
         while message:
            args = message.split()
            if args[0] == 'json':
               jsonMessageLength = int(args[1])
               jsonMessage = self.pullMessage(channel,jsonMessageLength)
               if len(jsonMessage) > 0:
                  try:
                     jsonObject = json.loads(jsonMessage)
                  except ValueError:
                     self.logger.log(logging.ERROR,getLogMessage("JSON object %s could not be decoded" % (jsonMessage)))
                  else:
                     tunnelDesignator = jsonObject['tunnelDesignator']
                     if   jsonObject['messageType'] == 'getTunnelAddress':
                        address,port = self.tunnelsInfo.getSSHTunnelAddressPort(tunnelDesignator)
                        returnMessage = {'messageType':'tunnelInfo',
                                         'tunnelDesignator':tunnelDesignator,
                                         'address':address,
                                         'port':port}
                        self.postJsonMessage(channel,returnMessage)
                     elif jsonObject['messageType'] == 'incrementTunnelUsage':
                        if tunnelDesignator in self.activeTunnels:
                           useCount = self.activeTunnels[tunnelDesignator]['useCount']
                           useCount += 1
                           self.activeTunnels[tunnelDesignator]['useCount'] = useCount
                        else:
                           useCount = 1
                           gatewayHost,localHost = self.tunnelsInfo.getSSHTunnelHosts(tunnelDesignator)
                           if gatewayHost != "" and localHost != "":
                              sshTunnelCommand = self.tunnelsInfo.getSSHTunnelCommand(tunnelDesignator,self.sshIdentity)
                              self.logger.log(logging.INFO,getLogMessage(sshTunnelCommand))
                              exitStatus,stdOutput,stdError = self.__executeTunnelCommand(sshTunnelCommand)
                              if exitStatus == 0:
                                 sshTunnelPidCommand = self.tunnelsInfo.getSSHTunnelPidCommand(tunnelDesignator)
                                 self.logger.log(logging.INFO,getLogMessage(sshTunnelPidCommand))
                                 exitStatus,tunnelPid,stdPidError = self.__executeCommand(sshTunnelPidCommand)
                                 tunnelPid = tunnelPid.strip()
                                 if exitStatus == 0:
                                    tunnelPid = int(tunnelPid)
                                    self.activeTunnels[tunnelDesignator] = {'tunnelPid':tunnelPid,'useCount':useCount}
                                    self.logger.log(logging.INFO,getLogMessage("%s tunnel started, pid = %d" % \
                                                                                (tunnelDesignator,tunnelPid)))
                                 else:
                                    self.logger.log(logging.ERROR,getLogMessage(tunnelPid))
                                    self.logger.log(logging.ERROR,getLogMessage(stdPidError))
                              else:
                                 self.logger.log(logging.ERROR,getLogMessage(stdOutput))
                                 self.logger.log(logging.ERROR,getLogMessage(stdError))
                        returnMessage = {'messageType':'tunnelUsage',
                                         'tunnelDesignator':tunnelDesignator,
                                         'useCount':useCount}
                        self.postJsonMessage(channel,returnMessage)
                     elif jsonObject['messageType'] == 'decrementTunnelUsage':
                        if tunnelDesignator in self.activeTunnels:
                           useCount = self.activeTunnels[tunnelDesignator]['useCount']
                           useCount -= 1
                           if useCount == 0:
                              tunnelPid = self.activeTunnels[tunnelDesignator]['tunnelPid']
                              os.kill(int(tunnelPid),signal.SIGTERM)
                              del self.activeTunnels[tunnelDesignator]
                              self.logger.log(logging.INFO,getLogMessage("%s tunnel stopped, pid = %d" % \
                                                                          (tunnelDesignator,tunnelPid)))
                           else:
                              self.activeTunnels[tunnelDesignator]['useCount'] = useCount
                        else:
                           useCount = "0"
                        returnMessage = {'messageType':'tunnelUsage',
                                         'tunnelDesignator':tunnelDesignator,
                                         'useCount':useCount}
                        self.postJsonMessage(channel,returnMessage)
                     elif jsonObject['messageType'] == 'terminateTunnel':
                        if tunnelDesignator in self.activeTunnels:
                           useCount  = self.activeTunnels[tunnelDesignator]['useCount']
                           tunnelPid = self.activeTunnels[tunnelDesignator]['tunnelPid']
                           os.kill(tunnelPid,signal.SIGTERM)
                           del self.activeTunnels[tunnelDesignator]
                           self.logger.log(logging.INFO,getLogMessage("%s tunnel stopped, pid = %s" % (tunnelDesignator,tunnelPid)))
                        else:
                           useCount = 0
                        returnMessage = {'messageType':'tunnelUsage',
                                         'tunnelDesignator':tunnelDesignator,
                                         'useCount':useCount}
                        self.postJsonMessage(channel,returnMessage)
                     elif jsonObject['messageType'] == 'reportActiveTunnels':
                        returnMessage = {'messageType':'tunnelReport',
                                         'usageReport':{}}
                        if tunnelDesignator == "":
                           for activeTunnel in self.activeTunnels:
                              useCount = self.activeTunnels[activeTunnel]['useCount']
                              returnMessage['usageReport'][activeTunnel] = useCount
                        else:
                           if tunnelDesignator in self.activeTunnels:
                              useCount = self.activeTunnels[tunnelDesignator]['useCount']
                              returnMessage['usageReport'][tunnelDesignator] = useCount
                           else:
                              returnMessage['usageReport'][tunnelDesignator] = 0
                        self.postJsonMessage(channel,returnMessage)
                     else:
                        self.logger.log(logging.ERROR,getLogMessage("Discarded message type: %s" % (jsonObject['messageType'])))
               else:
                  self.pushMessage(channel,message + '\n')
                  break
            else:
               self.logger.log(logging.ERROR,getLogMessage("Discarded message: %s" % (message)))

            message = self.pullMessage(channel,0)


