#!/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_gucquery is a utility to collect, sort, export and compare 
# the GUC parameter value of MogDB.
#############################################################################

import os
import psutil
import pwd
import subprocess
import sys
import time

from base_utils.os.file_util import FileUtil
from datetime import timedelta
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


# action type
ACTION_QUERY = "query"
ACTION_COMPARE = "compare"

class Gucquery():

    def __init__(self):
        """
        function : Constructor
        input: NA
        output: NA
        """
        self.action = ""
        self.user = ""
        self.outPath = ""
        self.port = ""
        self.sourceFile = ""
        self.targetFile = ""
        self.diffFile = ""

    def usage(self):
        """
gs_gucquery is a utility to collect, sort, export and compare the GUC parameter
value of MogDB.

Usage:
  gs_gucquery -? | --help
  gs_gucquery -V | --version
  gs_gucquery -t query [-o OUTPUTDIR] [-p PORT]
  gs_gucquery -t compare --source-file=OUTPUTFILE --target-file=OUTPUTFILE
              --diff-file=OUTPUTDIR

General options:
  -t                          Operation type. It can be query or compare.
  -o                          Save the result to the specified directory.
  -p                          MogDB port number.
      --source-file           Path of source file for GUC parameter compare.
      --target-file           Path of target file for GUC parameter compare.
      --diff-file             Save the diff report to the specified 
                              directory.
  -?, --help                  Show help information for this utility,
                              and exit the command line mode.
  -V, --version               Show version information.
        """
        print(self.usage.__doc__)

    ############################################################################
    # Parse and check parameters
    ############################################################################
    def parseCommandLine(self):
        """
        function: Parse command line and save to variable
        input : NA
        output: NA
        """
        ParaObj = Parameter()
        ParaDict = ParaObj.ParameterCommandLine("gucquery")
        # If helpFlag is included in the parameter,
        # the help message is printed and exited
        if (ParaDict.__contains__("helpFlag")):
            self.usage()
            sys.exit(0)
        # save parameter value to variable
        if (ParaDict.__contains__("action")):
            self.action = ParaDict["action"]
        if (ParaDict.__contains__("outFile")):
            self.outPath = ParaDict["outFile"]
        if (ParaDict.__contains__("port")):
            self.port = ParaDict["port"]
        if (ParaDict.__contains__("source_file")):
            self.sourceFile = os.path.realpath(ParaDict["source_file"])
        if (ParaDict.__contains__("target_file")):
            self.targetFile = os.path.realpath(ParaDict["target_file"])
        if (ParaDict.__contains__("diff_file")):
            self.diffFile = os.path.realpath(ParaDict["diff_file"])

    def checkParameter(self):
        """
        function: do parameters checking
        input : NA
        output: NA
        """
        # check if the user is the right user
        self.checkUser()

        # check parameter if operation type is query
        if (self.action == ACTION_QUERY):
            self.checkQueryParameter()

        # check parameter if operation type is compare
        if (self.action == ACTION_COMPARE):
            self.checkCompareParameter()

    def checkQueryParameter(self):
        """
        Check parameter for ACTION_QUERY
        input : NA
        output: NA
        """
        # check port parameter
        self.checkPort()

        # check output path permission
        if (self.outPath != ""):
            self.checkOutPath(self.outPath)

           

    def checkCompareParameter(self):
        """
        Check parameter for ACTION_COMPARE
        input : NA
        output: NA
        """
        # check if both sourceFile and targetFile:
        # 1. exist 2.isFile 3.readable
        if (self.sourceFile != ""):
            FileUtil.check_file_permission(
                self.sourceFile, check_read_permission=True)
        else:
            GaussLog.exitWithError(
                ErrorCode.GAUSS_500["GAUSS_50001"] %"-source-file"
                + "for action_compare.")

        if (self.targetFile != ""):
            FileUtil.check_file_permission(
                self.targetFile, check_read_permission=True)
        else:
            GaussLog.exitWithError(
                ErrorCode.GAUSS_500["GAUSS_50001"] %"-target-file"
                + "for action_compare.")

        # check output path permission
        if (self.diffFile != ""):
            self.checkOutPath(self.diffFile)
        else:
            GaussLog.exitWithError(
                ErrorCode.GAUSS_500["GAUSS_50001"] %"-diff-file"
                + "for action_compare.")            


    def checkUser(self):
        """
        Check if the user is the right user
        input : NA
        output: NA
        """
        if (os.getuid() == 0):
            # check if it is root user
            GaussLog.exitWithError(ErrorCode.GAUSS_501["GAUSS_50105"])
        else:
            # get user
            self.user = pwd.getpwuid(os.getuid()).pw_name
        
        # check if user exists and if is the right user
        ClusterUser.checkUser(self.user)



    def checkOutPath(self, outPath):
        """
        Check output path permission
        input : NA
        output: NA
        """
        if os.path.isdir(outPath):
            # test write permissions
            if not FileUtil.checkDirWriteable(outPath):
                GaussLog.exitWithError(
                    "The directory %s is not writable for current user" 
                    % outPath)
        elif os.path.isfile(outPath):
            GaussLog.exitWithError(
                ErrorCode.GAUSS_502["GAUSS_50211"] % outPath)
        else:
            # path does not exist
            GaussLog.exitWithError(
                ErrorCode.GAUSS_502["GAUSS_50201"] % ("path " + outPath))



    def checkPort(self):
        """
        1. -p is not specified --> get port number and save to self.port
        2. -p is specified --> check the validity of this parameter
        input : NA
        output: NA
        """
        if (self.port != ""):
            # -p parameter is specified
            # check the validity of the specified port parameter
            databaseCount, pidList = self.getDatabaseStatus()
            validFlag = False
            for pid in pidList:
                proc = psutil.Process(pid)
                pconn = proc.connections("tcp4")
                for conn in pconn:
                    if (str(conn.laddr.port) == self.port):
                        validFlag = True
                        break
                if validFlag == True:
                    break
            # check the value of validFlag
            if (validFlag == False):
                # raise exception
                GaussLog.exitWithError(ErrorCode.GAUSS_540["GAUSS_54002"])
        else:
            # -p parameter is not specified
            # get the number of MogDB started by user
            databaseCount, pidList = self.getDatabaseStatus()
            if databaseCount == 0:
                # There is no mogdb started by user
                GaussLog.exitWithError(
                    ErrorCode.GAUSS_540["GAUSS_54000"] % self.user)
            elif databaseCount == 1:
                # only one MogDB started and user owns the database
                # get MogDB's port number through its pid
                self.port = str(self.getPortNum(pidList[0]))
            else:
                # two or more mogdb started by user
                GaussLog.exitWithError(
                    ErrorCode.GAUSS_540["GAUSS_54001"])

    def getDatabaseStatus(self):
        """
        Get number of MogDB started by user and its corresponding pid
        input : NA
        output: [int, list]
                1. int --> MogDB processes count
                2. list --> pid list
        """
        databaseCount = 0
        pidList = []
        for proc in psutil.process_iter():
            if "mogdb" in proc.name().lower() and proc.username() == self.user:
                databaseCount += 1
                pidList.append(proc.pid)
        return databaseCount, pidList

    def getPortNum(self, pid):
        """
        Given MogDB's pid, get its port number
        input : int(pid)
        output: int(port number)
        """
        proc = psutil.Process(pid)
        pconn = proc.connections("tcp4")
        portSet = set()
        for conn in pconn:
            portSet.add(conn.laddr.port)
        return portSet.pop()

    def run(self):
        """
        Do query or do compare based on action type
        input : NA
        output: NA
        """
        if self.action == "query":
            # do query
            self.doQuery()
        elif self.action == "compare":
            # do compare
            self.doCompare()

    def doQuery(self):
        """
        Do query
        input : NA
        output: NA
        """
        if (self.outPath != ""):
            # -o is specified
            fileID = self.genFileID()
            fileName = os.path.join(self.outPath,"GUCQuery_%s.csv" % fileID)
            sql = ("copy (select name, setting from pg_settings order by name, "
                "setting) to '%s' CSV;" % fileName)
            cmd = 'gsql -d postgres -p %s -c "%s"' % (self.port, sql)
            status = subprocess.call(cmd, shell=True)
            if (status != 0):
                GaussLog.exitWithError(ErrorCode.GAUSS_540["GAUSS_54003"])
            else:
                print ("GUC value is successfully output.")
                print ("Please refer to %s" % fileName)
        else:
            # -o is not specified
            sql = "select name, setting from pg_settings order by name, setting"
            cmd = 'gsql -d postgres -p %s -c "%s"' % (self.port, sql)
            (status, output) = subprocess.getstatusoutput(cmd)
            if (status != 0):
                GaussLog.exitWithError(ErrorCode.GAUSS_540["GAUSS_54003"])
            else:
                print (output)

        
    def doCompare(self):
        """
        Do compare
        input : NA
        output: NA
        """
        sourceDict = self.csvToDict(self.sourceFile)
        targetDict = self.csvToDict(self.targetFile)

        # compare two dicts
        # generate the diff Report
        diffReport, diffCount = self.generateDiffReport(sourceDict,targetDict)

        # write diff Report to diffFile
        # generate the file ID
        fileID = self.genFileID()
        diffFile = os.path.join(self.diffFile, "GUCCompare_%s" %fileID)
        FileUtil.createFile(diffFile, True)
        FileUtil.writeFile(diffFile, [diffReport])
        print ("GUC compare is completed.")
        if diffCount == 0:
            print("Source file and target file are identical.")
        else:
            print("Number of diff items:%d" %diffCount)
        print ("For more information, Please refer to %s." % diffFile)

    def genFileID(self):
        """
        function : generate ID which is unique for once querying or comparing
        input : NA
        output : fileID
        """
        # Get Time
        t = time.localtime(time.time())
        dateString = time.strftime("%Y%m%d", t)
        seconds = timedelta(hours=t.tm_hour, minutes=t.tm_min,
                            seconds=t.tm_sec).seconds
        return dateString + str(seconds)

    def csvToDict(self,file):
        """
        Read the csv file and convert it into dict
        input : str(filePath)
        output: dict
        """
        allLines = []
        dict = {}
        with open(file, 'r') as f:
            allLines = f.read().splitlines()
        for item in allLines:
            itemList = item.split(",", 1)
            if (len(itemList) == 2):
                dict[itemList[0]] = itemList[1]
        if not dict:
            GaussLog.exitWithError(ErrorCode.GAUSS_540["GAUSS_54004"] % file)
        return dict

    def generateDiffReport(self, sourceDict, targetDict):
        """
        function: generate the diff report
        input : two dicts and their corresponding fileName
        output: String (diff Report), int (number of diff items)
        """
        introMessage = self.introMessage()
        diffResult = "---------------DIFF GUC PARAMETER VALUES---------------\n"
        diffList = []
        for key in sourceDict:
            if (sourceDict[key] != targetDict[key]):
                diffStr = "%s : %s | %s" % (key, sourceDict[key], targetDict[key])
                diffList.append(diffStr)
        # sourceFile is exactly the same as targetFile
        if (len(diffList) == 0):
            diffResult += "Source file and target file are identical."
        else:
            diffResult += "\n".join(diffList)
        
        return (introMessage + diffResult), len(diffList)


    def introMessage(self):
        """
        Return the intro string of diff report
        input : NA
        output: str
        """
        introMessage = """\
This document shows all of the different GUC value between source and target \
file in the following format:

[GUC Parameter Name] : [Value in Source File] | [Value in Target File]

Example:

autovacuum : on | off

"""
        return introMessage





if __name__ == '__main__':
    """
    main function
    """
    try:
        gucQuery = Gucquery()
        gucQuery.parseCommandLine()
        gucQuery.checkParameter()
        gucQuery.run()
    except Exception as e:
        GaussLog.exitWithError(str(e))