#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################################
# Copyright (c) 2020-2030, Yunhe Enmo (Beijing) Information Technology Co., Ltd
#
# MogDB is licensed under Mulan PSL v2.
# You can use this software according to the terms 
# and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
#          http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
# ---------------------------------------------------------------------------
# Description  : gs_watch is a utility to monitor the mogdb process. When
# mogdb exit abnormally, the daemon process it creates will call watchTrigger.sh
# (gs_collector by default) automatically to collect information about the cluster.
#############################################################################

import os
import psutil
import pwd
import signal
import subprocess
import sys

from base_utils.os.file_util import FileUtil
from domain_utils.cluster_os.cluster_user import ClusterUser
from gspylib.common.ErrorCode import ErrorCode
from gspylib.common.GaussLog import GaussLog
from gspylib.common.ParameterParsecheck import Parameter
from gspylib.inspection.common import SharedFuncs


def usage():
    """
gs_watch is a utility to monitor the mogdb process. When mogdb exit abnormally, 
the daemon process it creates will call watchTrigger.sh (gs_collector by default) 
automatically to collect information about the cluster.

Usage:
  gs_watch -? | --help
  gs_watch -V | --version
  gs_watch -t start [-o OUTPUTDIR] [--pid=PID]
  gs_watch -t stop  [--pid=PID]

General options:
  -t                                Operation type. It can be start or stop.
  -o                                Save the result to the specified directory.
      --pid                         The process ID used for identify a specific
                                    mogdb process.
  -?, --help                        Show help information for this utility,
                                    and exit the command line mode.
  -V, --version                     Show version information.
    """
    print(usage.__doc__)

def version():
    '''
    function : get the version the check tool
    input : NA
    output: NA
    '''
    print(SharedFuncs.getVersion())    

#############################################################################
# Parse and check parameters
#############################################################################
def parseCommandLine():
    """
    function: Parse command line and return parameter value dict
    input : NA
    output: dict(parameter value dict)
    """
    ParaObj = Parameter()
    ParaDict = ParaObj.ParameterCommandLine("watch")
    # If help is included in the parameter,
    # the help message is printed and exited
    if (ParaDict.__contains__("helpFlag")):
        usage()
        sys.exit(0)

    # parameter can not be set at the same time
    if ParaDict["action"] == "stop" and ParaDict.__contains__("outFile"):
        GaussLog.exitWithError(
            ErrorCode.GAUSS_500["GAUSS_50005"] % ('t','o'))

    #check out path permission
    if ParaDict.__contains__("outFile"):
        outDir = ParaDict["outFile"]
        if os.path.isdir(outDir):
            #test write permissions
            if not FileUtil.checkDirWriteable(outDir):
                GaussLog.exitWithError(
                    "The directory %s is not writable for current user" 
                    % outDir)
        elif os.path.isfile(outDir):
            raise Exception(ErrorCode.GAUSS_502["GAUSS_50211"] %outDir)
        else:
            #path does not exist
            raise Exception(ErrorCode.GAUSS_502["GAUSS_50201"] %outDir)

    return ParaDict

def checkParameter(ParaDict):
    """
    function: do parameter checking 
    input : dict ()
    output: NA
    """
    # check if user exists and is the right user
    checkUserParameter()    
    # check the pid parameter
    if ParaDict.__contains__("pid"):
        # if --pid is specified
        if not psutil.pid_exists(int(ParaDict["pid"])):
            #specified pid does not exist
            GaussLog.exitWithError(
                ErrorCode.GAUSS_539["GAUSS_53900"] % ParaDict["pid"])
        # check process name and user
        # get process name and user based on specified pid
        p = psutil.Process(int(ParaDict["pid"]))
        processName = p.name()
        processUser = p.username()
        user = pwd.getpwuid(os.getuid()).pw_name
        if processName != "mogdb":
            # specified another process pid 
            GaussLog.exitWithError(
                ErrorCode.GAUSS_539["GAUSS_53901"])
        if user != processUser:
            if ParaDict["action"] == "start" or \
                (ParaDict["action"] == "stop" and (not __isRoot)):
                # The user is not the name of the user starts mogdb
                GaussLog.exitWithError(
                    ErrorCode.GAUSS_539["GAUSS_53902"] % user)             
        if ParaDict["action"] == "start":
            if __isRoot():
                GaussLog.exitWithError(ErrorCode.GAUSS_501["GAUSS_50105"])
            else:
                # if mogdb with specified pid has been watched
                if isWatched(ParaDict):
                    GaussLog.exitWithError(
                        ErrorCode.GAUSS_539["GAUSS_53903"] % ParaDict["pid"])
        if ParaDict["action"] == "stop":
            # if mogdb with specified pid hasn't been watched
            if not isWatched(ParaDict):
                GaussLog.exitWithError(
                    ErrorCode.GAUSS_539["GAUSS_53904"] % ParaDict["pid"])
    else:
        # --pid is not specified
        if ParaDict["action"] == "start":
            if __isRoot():
                GaussLog.exitWithError(ErrorCode.GAUSS_501["GAUSS_50105"])
            user = pwd.getpwuid(os.getuid()).pw_name
            processCount = 0
            pidList = []
            for proc in psutil.process_iter():
                if "mogdb" in proc.name().lower() and user == proc.username():
                    processCount += 1
                    pidList.append(str(proc.pid))
                    
            if processCount == 0:
                # There is no mogdb started by user
                GaussLog.exitWithError(
                    ErrorCode.GAUSS_539["GAUSS_53905"] % user)
            elif processCount == 1:
                # one mogdb started and user owns the mogdb process
                ParaDict["pid"] = pidList[0]
                # if mogdb with specified pid has been watched
                if isWatched(ParaDict):
                    GaussLog.exitWithError(
                        ErrorCode.GAUSS_539["GAUSS_53903"] % ParaDict["pid"])
            else:
                # two or more mogdb started by user
                GaussLog.exitWithError(ErrorCode.GAUSS_539["GAUSS_53906"])
        if ParaDict["action"] == "stop":
            # how many mogdb processes are watched
            processCount = 0
            pidList = []
            for proc in psutil.process_iter():
                if "python" in proc.name().lower():
                    cmdline = proc.cmdline()
                    if any("gs_watch_daemon.py" in s for s in cmdline):
                        processCount += 1
                        pidList.append(str(proc.pid))

            if processCount == 0:
                # no mogdb is watched
                GaussLog.exitWithError(
                    ErrorCode.GAUSS_539["GAUSS_53907"])
            elif processCount == 1:
                # check if user has the right to stop 
                process = psutil.Process(int(pidList[0]))
                user = pwd.getpwuid(os.getuid()).pw_name
                if (not __isRoot()) and (user != process.username()):
                    GaussLog.exitWithError(
                        ErrorCode.GAUSS_539["GAUSS_53902"] % user)
                # retrieve the watched mogdb pid 
                dict = eval(process.cmdline()[-1])
                ParaDict["pid"] = dict["pid"]
            else:
                # two or more mogdb processes are watched
                GaussLog.exitWithError(ErrorCode.GAUSS_539["GAUSS_53908"])
            
                              

                
                


def __isRoot():
    """
    function: whether the process running under root user
    """
    return os.getuid() == 0

def checkUserParameter():
    """
    function: check User Parameter
    input : NA
    output: NA
    """
    try:
        user = pwd.getpwuid(os.getuid()).pw_name
        ClusterUser.checkUser(user)
    except Exception as e:
        GaussLog.exitWithError(str(e))

def isWatched(ParaDict):
    """
    function: whether the mogdb process with specified pid has been watched
    input : ParaDict(dict)
    output: bool
    """ 
    # if mogdb with specified pid has been watched
    for proc in psutil.process_iter():
        if "python" in proc.name().lower():
            cmdline = proc.cmdline()
            if any("gs_watch_daemon.py" in s for s in cmdline):
                dict = eval(cmdline[-1])
                if dict["pid"] == ParaDict["pid"]:
                    return True
    return False

def start(ParaDict):
    """
    function: start to watch mogdb given pid
    input : ParaDict(dict)
    output: NA
    """
    # convert ParaDict to string
    strDict = str(ParaDict)
    watchPath = sys.argv[0]
    daemonPath = os.path.join(os.path.dirname(watchPath),"gs_watch_daemon.py")
    cmd = ["python3",daemonPath,strDict]
    subprocess.Popen(cmd)

def stop(ParaDict):
    """
    function: stop watching mogdb given pid
    input : ParaDict(dict)
    output: NA
    """
    for proc in psutil.process_iter():
        if "python" in proc.name().lower():
            cmdline = proc.cmdline()
            if any("gs_watch_daemon.py" in s for s in cmdline):
                dict = eval(cmdline[-1])
                if dict["pid"] == ParaDict["pid"]:
                    os.kill(proc.pid, signal.SIGTERM)
                    print("stop watching mogdb with pid %s." %ParaDict["pid"])
        

if __name__ == '__main__':
    """
    main function
    """
    try:
        ParaDict = parseCommandLine()
        checkParameter(ParaDict)
        if ParaDict["action"] == "start":
            start(ParaDict)
        if ParaDict["action"] == "stop":
            stop(ParaDict)
    except Exception as e:
        GaussLog.exitWithError(str(e))
