# @package      hubzero-submit-monitors
# @file         JobMetrics.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 pwd
import logging

from hubzero.submit.LogMessage import getLogIDMessage as getLogMessage
from hubzero.submit.JobWSCore  import JobWSCore

DOWNLOADJOBMETRICS = 'downloadJobMetricsTarFile.sh'

class JobMetrics(JobWSCore):
   def __init__(self,
                daemonsDirectory,
                daemonsConfigurationFile,
                infosDirectory,
                infosConfigurationFile,
                previousState,
                nextState):
      JobWSCore.__init__(self,daemonsDirectory,daemonsConfigurationFile,
                              infosDirectory,infosConfigurationFile,
                              'metrics',previousState,nextState)

      self.logger = logging.getLogger(__name__)


   def processWSRequest(self,
                        wsJobId,
                        downloadPath):
      metricsDownloaded = False
      metricsCollectionActiveJob = self.remoteJobMonitor.getActiveJobMetricsCollection(wsJobId)
      submitTokenPath = os.path.join(downloadPath,'.submitToken')
      with open(submitTokenPath,'w') as fpSubmitToken:
         fpSubmitToken.write("%s\n" % (metricsCollectionActiveJob['instanceToken']))

      commandArgs = []
      siteName = metricsCollectionActiveJob['siteName']
      siteInfo = self.sitesInfo.getSiteInfo(siteName)
      if siteInfo['fileMover']:
         fileMoverInfo = self.fileMoversInfo.getFileMoverInfo(siteInfo['fileMover'])
         if   fileMoverInfo['fileMoverType'] == 'tapis2':
            remoteBinDirectory = fileMoverInfo['remoteBinDirectory']
            downloadJobMetricsCommand = os.path.join(remoteBinDirectory,DOWNLOADJOBMETRICS)
            commandArgs.append(downloadJobMetricsCommand)
            commandArgs.append(metricsCollectionActiveJob['instanceToken'])
            commandArgs.append(downloadPath)
         elif fileMoverInfo['fileMoverType'] == 'tapis3':
            remoteBinDirectory = fileMoverInfo['remoteBinDirectory']
            downloadJobMetricsCommand = os.path.join(remoteBinDirectory,DOWNLOADJOBMETRICS)
            commandArgs.append(downloadJobMetricsCommand)
            commandArgs.append(metricsCollectionActiveJob['instanceToken'])
            commandArgs.append(downloadPath)
         elif fileMoverInfo['fileMoverType'] == 'ssh':
            commandArgs.append("scp")
            commandArgs += siteInfo['sshOptions'].split()
            identityPaths = self.remoteIdentityManager.queryUserIdentities(siteInfo['identityManagers'],
                                                                           pwd.getpwuid(os.getuid()).pw_name)
            commandArgs += ['-i',identityPaths['individualSSH']]
            commandArgs += ['-P',str(siteInfo['venuePort'])]
            remoteWorkingDirectory = os.path.join(siteInfo['remoteScratchDirectory'],"%s_%s" % \
                            (metricsCollectionActiveJob['stagingHandle'],metricsCollectionActiveJob['instanceToken']))
            simToolJobMetricsPath = os.path.join(remoteWorkingDirectory,'.simtool','jobMetrics.tar.gz')
            commandArgs.append("%s@%s:%s" % (siteInfo['remoteUser'],siteInfo['venues'][0],simToolJobMetricsPath))
            commandArgs.append(downloadPath)

         del fileMoverInfo

         exitStatus,stdOutput,stdError = self.executeCommand(commandArgs)
         if exitStatus == 0:
            self.logger.log(logging.DEBUG,getLogMessage(stdOutput))
            self.logger.log(logging.DEBUG,getLogMessage(stdError))
         else:
            self.logger.log(logging.ERROR,getLogMessage(stdOutput))
            self.logger.log(logging.ERROR,getLogMessage(stdError))

         if exitStatus == 0:
            metricsDownloaded = True
      del siteInfo

      return(metricsDownloaded)


