def getNetWorkConfFile(networkCardNum):
    """
    function: get network conf file
    input  : NA
    output : NA
    """
    SuSENetWorkConfPath = "/etc/sysconfig/network"
    RedHatNetWorkConfPath = "/etc/sysconfig/network-scripts"
    if isSupportSystemOs():
        NetWorkConfFile = "%s/ifcfg-%s" % (
        RedHatNetWorkConfPath, networkCardNum)
    else:
        NetWorkConfFile = "%s/ifcfg-%s" % (SuSENetWorkConfPath, networkCardNum)

    if (not os.path.exists(NetWorkConfFile)):
        if isSupportSystemOs():
            cmd = "find %s -iname 'ifcfg-*-%s' -print" % (
            RedHatNetWorkConfPath, networkCardNum)
        else:
            cmd = "find %s -iname 'ifcfg-*-%s' -print" % (
            SuSENetWorkConfPath, networkCardNum)
        output = runShellCmd(cmd)
        if (DefaultValue.checkDockerEnv() and
                output.find("No such file or directory") >= 0):
            return output.strip()
        if (output.strip() == "" or len(output.split('\n')) != 1):
            if DefaultValue.checkDockerEnv():
                return ""
            raise Exception(ErrorCode.GAUSS_502["GAUSS_50201"]
                            % NetWorkConfFile)
        NetWorkConfFile = output.strip()
    return NetWorkConfFile
Esempio n. 2
0
    def doCheck(self):
        flag = "open"
        idList = []
        idCount = 0
        cores = 0
        cpuCount = 0
        cpuInfo = g_file.readFile('/proc/cpuinfo')
        for eachLine in cpuInfo:
            if (eachLine.find('physical id') >= 0):
                # get different CPU id
                cpuID = eachLine.split(':')[1].strip()
                if (not cpuID in idList):
                    idList.append(cpuID)
                    # Calculate the number of CPUs
                    idCount += 1
            if (eachLine.find('cores') >= 0):
                cores = int(eachLine.split(':')[1].strip())
            if (eachLine.find('processor') >= 0):
                cpuCount += 1

        if (cpuCount == 2 * idCount * cores):
            self.result.rst = ResultStatus.OK
        else:
            if DefaultValue.checkDockerEnv():
                return
            flag = "down"
            self.result.rst = ResultStatus.NG

        self.result.val = "Hyper-threading is %s." % flag
        self.result.raw = "the number of physical id: %d, cores: %d," \
                          " cpu counts: %d" % (idCount, cores, cpuCount)
def runShellCmd(cmd, user=None, mpprcFile=""):
    """
    function: run shell cmd
    input  : md, user, mpprcFile
    output : str
    """
    if (mpprcFile):
        cmd = "source '%s'; %s" % (mpprcFile, cmd)
    # Set the output LANG to English
    cmd = "export LC_ALL=C; %s" % cmd
    # change user but can not be root user
    if (user and user != getCurrentUser()):
        cmd = "su - %s -c \"source /etc/profile 2>/dev/null; %s\"" % (
        user, cmd)
        cmd = cmd.replace("$", "\$")
    (status, output) = subprocess.getstatusoutput(cmd)
    if (status != 0 and DefaultValue.checkDockerEnv()):
        return output
    if (status != 0):
        raise ShellCommandException(cmd, output)
    return output
def CheckNetWorkBonding(serviceIP):
    """
    function: check network bonding
    input  : NA
    output : NA
    """
    networkCardNum = getNICNum(serviceIP)
    NetWorkConfFile = getNetWorkConfFile(networkCardNum)
    if ((NetWorkConfFile.find("No such file or directory") >= 0
         or NetWorkConfFile == "") and DefaultValue.checkDockerEnv()):
        return "Shell command faild"
    bondingConfFile = "/proc/net/bonding/%s" % networkCardNum
    networkCardNumList = [networkCardNum]
    cmd = "grep -i 'BONDING_OPTS\|BONDING_MODULE_OPTS' %s" % NetWorkConfFile
    (status, output) = subprocess.getstatusoutput(cmd)
    if ((status == 0) and (output.strip() != "")):
        if ((output.find("mode") > 0) and os.path.exists(bondingConfFile)):
            networkCardNumList = networkCardNumList + checkBondMode(
                bondingConfFile)
        else:
            raise Exception(ErrorCode.GAUSS_506["GAUSS_50611"] +
                            "The cmd is %s " % cmd)
    return networkCardNumList
Esempio n. 5
0
    def doCheck(self):

        parRes = ""
        flag = "Normal"
        cmd = "ls -l /lib/modules/`uname -r`/kernel/net/sctp/sctp.ko*"
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status != 0 or output == "" or output.find(
                "No such file or directory") > 0):
            if DefaultValue.checkDockerEnv():
                return
            flag = "Error"
            parRes += "There is no sctp service."
        else:
            cmd = "modprobe sctp;"
            cmd += "lsmod |grep sctp"
            (status, output) = subprocess.getstatusoutput(cmd)
            if (output == ""):
                flag = "Error"
                parRes += "sctp service is not loaded."

        cmd = "cat %s | grep '^insmod.*sctp.ko'" % DefaultValue.getOSInitFile()
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status != 0 or output == ""):
            if (flag == "Normal"):
                flag = "Warning"
            parRes += "Sctp service is not set to boot from power on."

        self.result.val = parRes
        self.result.raw = output
        if (flag == "Error"):
            self.result.rst = ResultStatus.NG
        elif (flag == "Warning"):
            self.result.rst = ResultStatus.WARNING
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = "Sctp service is Normal."
def checkSysctlParameter(kernelParameter, isSet):
    """
    function: check and set the OS parameters
    input: kernelParameter: OS parameters list will be check and set
           isSet: the flag, when it is only True then will set OS parameters
    output: NA
    """
    setParameterList = {}
    patchlevel = ""

    # get the suggest parameters and updata kernelParameter
    suggestParameterList = DefaultValue.getConfigFilePara(
        configFile, 'SUGGEST:%s' % actioItemMap["Check_SysCtl_Parameter"][0])
    kernelParameter.update(suggestParameterList)

    # check the OS parameters
    if ("fs.aio-max-nr" in kernelParameter):
        g_logger.log("        Warning reason: Checking or setting the"
                     " parameter 'fs.aio-max-nr' should be use "
                     "'gs_checkos -i A10' or 'gs_checkos -i B4'.")
        kernelParameter.pop("fs.aio-max-nr")
    # Get OS version
    distname, version = g_Platform.dist()[0:2]
    if (distname == "SuSE" and version == "11"):
        cmd = "grep -i 'PATCHLEVEL' /etc/SuSE-release  |" \
              " awk -F '=' '{print $2}'"
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status == 0 and output != ""):
            patchlevel = output.strip()
    # Gs_check get NetWork card MTU
    if (g_opts.action == "osKernelParameterCheck"):
        checkrestult = checkNetWorkMTU()
        if checkrestult != 0:
            resultList.append(checkrestult)

    for key in kernelParameter:
        # The SuSE 11 SP1 operating system
        # does not have vm.extfrag_threshold parameter, skip check
        if (patchlevel == "1" and key == "vm.extfrag_threshold"):
            continue
        sysFile = "/proc/sys/%s" % key.replace('.', '/')
        # High version of linux no longer supports tcp_tw_recycle
        if not os.path.exists(
                sysFile) and key == "net.ipv4.tcp_tw_recycle":
            continue
        if (DefaultValue.checkDockerEnv() and key in docker_no_need_check):
            continue
        # The parameter sctpchecksumerrors check method is independent
        if (key == "sctpchecksumerrors"):
            cmd = "cat /proc/net/sctp/snmp | grep SctpChecksumErrors" \
                  " | awk '{print $2}'"
        else:
            cmd = "cat %s" % ("/proc/sys/%s" % key.replace('.', '/'))
        (status, output) = subprocess.getstatusoutput(cmd)
        if (status == 0):
            if (key == "vm.min_free_kbytes"
                    and output.split() != kernelParameter[key].split()):
                expected_min = float(kernelParameter[key].split()[0]) * 0.9
                expected_max = float(kernelParameter[key].split()[0]) * 1.1
                if (int(output.split()[0]) > expected_max
                        or int(output.split()[0]) < expected_min):
                    resultList.append(1)
                    g_logger.log("        Abnormal reason: variable '%s'"
                                 " RealValue '%s' ExpectedValue '%s'."
                                 % (key, output, kernelParameter[key]))
                    setParameterList[key] = kernelParameter[key]
            elif (key == "net.ipv4.ip_local_port_range"
                  and output.split() != kernelParameter[key].split()):
                expected_min = int(kernelParameter[key].split()[0])
                expected_max = int(kernelParameter[key].split()[1])
                if (int(output.split()[0]) < expected_min
                        or int(output.split()[1]) > expected_max):
                    resultList.append(2)
                    g_logger.log("        Warning reason: variable '%s'"
                                 " RealValue '%s' ExpectedValue '%s'."
                                 % (key, output, kernelParameter[key]))
            elif (output.split() != kernelParameter[key].split() and
                  key not in list(suggestParameterList.keys())):
                resultList.append(1)
                g_logger.log("        Abnormal reason: variable '%s'"
                             " RealValue '%s' ExpectedValue '%s'."
                             % (key, output, kernelParameter[key]))
                setParameterList[key] = kernelParameter[key]
            elif output.split() != kernelParameter[key].split():
                if (key == "vm.overcommit_ratio"):
                    cmd = "cat /proc/sys/vm/overcommit_memory"
                    (status, value) = subprocess.getstatusoutput(cmd)
                    if (status == 0 and value == "0"):
                        continue
                resultList.append(2)
                g_logger.log("        Warning reason: variable '%s' RealValue"
                             " '%s' ExpectedValue '%s'."
                             % (key, output, kernelParameter[key]))
        else:
            resultList.append(1)
            g_logger.log("        Abnormal reason: Failed to obtain the OS "
                         "kernel parameter [%s]. Error: \n        %s"
                         % (key, output))
            setParameterList[key] = kernelParameter[key]

    if (1 in resultList and 'Check' in g_opts.action):
        g_logger.log("        %s failed." % g_opts.action)
    elif (2 in resultList and 'Check' in g_opts.action):
        g_logger.log("        %s warning." % g_opts.action)
    else:
        g_logger.log("        All values about system control"
                     " parameters are correct: Normal")

    # set the OS parameters
    if isSet:
        setOSParameter(setParameterList, patchlevel)
    def doCheck(self):
        global needRepairNetworkCardNum
        global networkCardNums
        flag = "Normal"

        self.result.val = ""
        self.result.raw = ""
        if self.cluster:
            LocalNodeInfo = self.cluster.getDbNodeByName(self.host)
            backIP = LocalNodeInfo.backIps[0]
        elif self.ipAddr:
            backIP = self.ipAddr
        else:
            backIP = SharedFuncs.getIpByHostName(self.host)
        # Get the network card number
        allNetworkInfo = g_network.getAllNetworkInfo()
        for network in allNetworkInfo:
            if network.ipAddress == backIP:
                networkNum = network.NICNum
                BondMode = network.networkBondModeInfo
                confFile = network.networkConfigFile
                break

        if not networkNum or not BondMode or not confFile:
            if DefaultValue.checkDockerEnv():
                return
            raise Exception(ErrorCode.GAUSS_506["GAUSS_50619"])
        if BondMode != "BondMode Null":
            bondFile = '/proc/net/bonding/%s' % networkNum
            bondInfoList = g_file.readFile(bondFile, "Slave Interface")
            for bondInfo in bondInfoList:
                networkNum = bondInfo.split(':')[-1].strip()
                networkCardNums.append(networkNum)
        else:
            networkCardNums.append(networkNum)

        for networkCardNum in networkCardNums:
            cmdGetSpeedStr = "/sbin/ethtool %s | grep 'Speed:'" \
                             % networkCardNum
            (status, output) = subprocess.getstatusoutput(cmdGetSpeedStr)
            if len(output.split('\n')) > 1:
                for line in output.split('\n'):
                    if line.find("Speed:") >= 0:
                        output = line
                        break
            if output.find("Speed:") >= 0 and output.find("Mb/s") >= 0:
                netLevel = int(output.split(':')[1].strip()[:-4])
                if netLevel >= int(netWorkLevel):
                    cmd = "for i in `cat /proc/interrupts | grep '%s-' |" \
                          " awk -F ' ' '{print $1}' | " \
                          "awk -F ':' '{print $1}'`; " \
                          "do cat /proc/irq/$i/smp_affinity ; done" \
                          % networkCardNum
                    (status, output) = subprocess.getstatusoutput(cmd)
                    if status != 0:
                        self.result.val += "Failed to obtain network card" \
                                           " [%s] interrupt value. " \
                                           "Commands for getting interrupt" \
                                           " value: %s.\n" % (networkCardNum,
                                                              cmd)
                        if networkCardNum not in needRepairNetworkCardNum:
                            needRepairNetworkCardNum.append(networkCardNum)
                        flag = "Error"
                        continue

                    # cpu core number followed by 1 2 4 8,every 4 left shift 1
                    Mapping = {0: "1", 1: "2", 2: "4", 3: "8"}
                    for index, eachLine in enumerate(output.split()):
                        # Remove the ','
                        eachLine = eachLine.replace(",", "")
                        # Replace 0000,00001000 to 1,Remove invalid content
                        validValue = eachLine.replace("0", "")
                        # Convert the row index to the expected value
                        expandNum = Mapping[index % 4]
                        # Convert line index to expected position
                        expandBit = index / 4 * -1 - 1
                        # value and position is correct
                        if (len(eachLine) * -1) > expandBit:
                            self.result.val += "Network card [%s] " \
                                               "multi-queue support is not" \
                                               " enabled.\n" % networkCardNum
                            flag = "Error"
                            break
                        if (eachLine[expandBit] == expandNum
                                and validValue == expandNum):
                            continue
                        else:
                            self.result.val += "Network card [%s] " \
                                               "multi-queue support is " \
                                               "not enabled.\n" \
                                               % networkCardNum
                            if (networkCardNum
                                    not in needRepairNetworkCardNum):
                                needRepairNetworkCardNum.append(networkCardNum)
                            flag = "Error"
                            break

                    self.result.raw += "%s: \n %s \n" \
                                       % (networkCardNum, output)
                else:
                    self.result.val += "Warning: The speed of current card" \
                                       " \"%s\" is less than %s Mb/s.\n" \
                                       % (networkCardNum, netWorkLevel)
            else:
                if output.find("Speed:") >= 0:
                    if (networkCardNum not in needRepairNetworkCardNum):
                        needRepairNetworkCardNum.append(networkCardNum)
                    flag = "Error"
                    self.result.val += "Failed to obtain the network card" \
                                       " [%s] speed value. Maybe the network" \
                                       " card is not working.\n" \
                                       % networkCardNum
                else:
                    self.result.val += "Failed to obtain the network" \
                                       " card [%s] speed value. Commands" \
                                       " for obtain the network card speed:" \
                                       " %s. Error:\n%s\n" \
                                       % (networkCardNum, cmdGetSpeedStr,
                                          output)
        if flag == "Normal":
            self.result.rst = ResultStatus.OK
        elif flag == "Warning":
            self.result.rst = ResultStatus.WARNING
        else:
            self.result.rst = ResultStatus.NG