#!/usr/bin/env python3
#-*- coding:utf-8 -*-
try:
    import sys
    import importlib
    importlib.reload(sys)
    import os
    import subprocess
    from gspylib.inspection.common.CheckItem import BaseItem
    from gspylib.inspection.common.CheckResult import ResultStatus
    from gspylib.common.Common import ClusterCommand
except ImportError as e:
    raise Exception("[GAUSS-52200] : Unable to import module: %s." % str(e))


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

    def doCheck(self):
        #Check the status of the cluster
        #Get cm_server Standby information
        if(self.cluster.isSingleCluster()):
            self.result.rst = ResultStatus.OK
            self.result.val = "Single cluster does not hava standby cm_servser."
            return
        cmd = ClusterCommand.getQueryStatusCmd(self.user) + 'Cd'
        if self.mpprcFile:
            cmd = "source '%s' && %s" % (self.mpprcFile, cmd)
        #Switch users
        if (os.getuid() == 0):
            cmd = "su - %s -c \"%s\" " % (self.user, cmd)
        (_, output) = subprocess.getstatusoutput(cmd)
        #Results information

        self.result.raw = cmd
        if (output.find('cm_server Standby') >= 0):
            self.result.rst = ResultStatus.OK
            self.result.val = "The standby cm_servser is normal."
        else:
            self.result.val = "The standby cm_servser is abnormal."
            self.result.rst = ResultStatus.WARNING
