#!/usr/bin/env python3
# -*- coding:utf-8 -*-
try:
    import sys
    import importlib

    importlib.reload(sys)
    import os
    import subprocess
    from gspylib.inspection.common import SharedFuncs
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
except ImportError as e:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(e))


class CheckDBConnection(BaseItem):
    def __init__(self):
        super(CheckDBConnection, self).__init__(self.__class__.__name__)

    def doCheck(self):
        instanceList = []
        AbnormalInst = []
        nodeInfo = self.cluster.getDbNodeByName(self.host)
        if nodeInfo.cooNum > 0:
            instanceList.append(nodeInfo.coordinators[0])
        localDnList = nodeInfo.datanodes
        for dn in localDnList:
            if dn.instanceId in self.master_dn_list:
                instanceList.append(dn)
        sqlcmd = "select pg_catalog.pg_sleep(1);"
        for instance in instanceList:
            cmd = "gsql postgresql://:%s/%s?application_name='OM' -c '%s' -m" % (instance.port, "postgres", sqlcmd)
            if self.mpprcFile:
                cmd = "source '%s' && %s" % (self.mpprcFile, cmd)
            if os.getuid() == 0:
                cmd = "su - %s -c \"%s\" " % (self.user, cmd)
            self.result.raw = "%s\n%s" % (self.result.raw, cmd)
            (status, output) = subprocess.getstatusoutput(cmd)
            if status != 0 or output.find("connect to server failed") > 0:
                AbnormalInst.append(instance.instanceId)
                self.result.val += "The instance %s can not be connected.\n" % instance.instanceId
                self.result.raw += "\nError: %s" % output
        if AbnormalInst:
            self.result.rst = ResultStatus.NG
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "The database connection is normal."
