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

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

STACK = 3072


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

    def doCheck(self):
        parRes = ""
        flag = 0
        output = g_OSlib.getUserLimits('stack size')
        self.result.raw = output
        StackValue = output.split()[-1]
        if StackValue == 'unlimited':
            pass
        elif int(StackValue) < STACK:
            flag = 1
            parRes += "The value of stack depth is %d. it can not be less than 3072" % int(StackValue)

        if self.cluster:
            pidList = g_OSlib.getProcess(os.path.join(self.cluster.appPath, 'bin/gaussdb'))
            for pid in pidList:
                limitsFile = "/proc/%s/limits" % pid
                if not os.path.isfile(limitsFile) or not os.access(limitsFile, os.R_OK):
                    continue
                output = g_file.readFile(limitsFile, 'Max stack size')[0].strip()
                self.result.raw = '%s\n[pid]%s: %s' % (self.result.raw, pid, output)
                Stack = output.split()[4]
                if Stack == 'unlimited':
                    pass
                else:
                    value = int(Stack) // 1024
                    if int(value) < STACK:
                        flag = 1
                        parRes += "The value of stack depth is %s on pid %s. it must be larger than 3072.\n" % (
                            value, pid)

        if flag == 1:
            self.result.rst = ResultStatus.NG
            self.result.val = parRes
        else:
            self.result.rst = ResultStatus.OK
            self.result.val = StackValue

    def doSet(self):
        limitPath = '/etc/security/limits.conf'
        errMsg = SharedFuncs.SetLimitsConf(["soft", "hard"], "stack", STACK, limitPath)
        if errMsg:
            self.result.val = "%s\n" % errMsg
        else:
            self.result.val = "Success to set openfile to %d\n" % STACK
