#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#############################################################################
# Copyright (c): 2012-2017, Huawei Tech. Co., Ltd.
# Description  : ParameterParsecheck.py is a utility to get Parameter information and check it.
#############################################################################
from __future__ import print_function

try:
    import os
    import getopt
    import sys
    import re

    sys.path.append(sys.path[0] + "/../../")
    from gspylib.common.ErrorCode import ErrorCode
    from gspylib.common.Common import DefaultValue
    from gspylib.common.GaussLog import GaussLog
    from gspylib.os.gsfile import g_file
    from gspylib.common.VersionInfo import VersionInfo
    from gspylib.common.parameter_const import ParameterDict, VALUE_CHECK_LIST, PARA_CHECK_LIST, PATH_CHEKC_LIST, \
        special_list, estimate_list, action_om, action_replace, action_upgradectl, action_expand, action_resize, \
        action_loadbalance, action_lcctl
except ImportError as ie:
    sys.exit("[GAUSS-52200] : Unable to import module: %s." % str(ie))

PARAMETER_VALUEDICT = {}
Itemstr = []
skipItems = []
user_passwd = []
EnvParams = []
DbInitParam = []
GtmInitParam = []
CooGucParam = []
DataGucParam = []
NODE_NAME = []

for keyTmp in ParameterDict:
    ParameterDict[keyTmp].append("--uuid=")


class Parameter():
    '''
    get Parameter information and check it.
    '''

    def __init__(self):
        """
        """
        self.action = ""
        self.mode = ""
        self.helpflag = False
        self.versionflag = False

    def ParseParameterValue(self, module):
        """
        function: parse the parameter value
        input : parameter_list
        output: options
        """
        # get the parameter list
        opts = []
        args = []
        (shortParameter, longParameter) = self.getParseParameter(module)

        try:
            # check delete parameter -h and -f, if specified lcname, not required -h or -f.
            check_delete_name = False
            for check_i in sys.argv[1:]:
                if "--name" in check_i:
                    check_delete_name = True
                    break
            if (module == "lcctl" and "delete" in sys.argv[1:] and check_delete_name and (
                    '-h' in sys.argv[1:] or '-f' in sys.argv[1:])):
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50002"] % 'h or -f')
            (opts, args) = getopt.getopt(sys.argv[1:], shortParameter, longParameter)
        except Exception as e:
            s1 = str(e).split(" ")
            option = s1[1]
            if "requires argument" in str(e):
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] %
                                       option[1:] + " Error:\n%s" % str(e))
            elif "not recognized" in str(e):
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50000"] % option)
            elif "not a unique prefix" in str(e):
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50006"] % option)
            else:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50000"] % str(e))

        if len(args) > 0:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50000"] % str(args[0]))

        return opts

    def moveCrypto(self, module):
        """
        function: Parse the parameter
        input : parameter_list
        output: PARAMETER_VALUEDICT
        """
        if module in ("preinstall", "sshexkey"):
            DefaultValue.doConfigForParamiko()

    def printVersionInfo(self):
        """
        """
        if self.versionflag:
            print("%s %s" % (sys.argv[0].split("/")[-1], VersionInfo.COMMON_VERSION))
            sys.exit(0)

    def ParameterCommandLine(self, module):
        """
        function: Parse the parameter
        input : parameter_list
        output: PARAMETER_VALUEDICT
        """
        # copy crypto
        self.moveCrypto(module)

        # Determines whether help and version information is output
        self.helpflag, self.versionflag = self.getHelpAndVersionStatus()
        if self.helpflag:
            PARAMETER_VALUEDICT['helpFlag'] = self.helpflag
            return PARAMETER_VALUEDICT

        # print version information
        self.printVersionInfo()

        # Special handling of the -t parameter
        self.getActionParameterValue(module)

        # get the parameter list
        opts = self.ParseParameterValue(module)

        parameterNeedValue = {
            "-t": "action",
            "-c": "cmd",
            "-m": "Mode",
            "--mode": "Mode",
            "-d": "destPath",
            "-s": "sourcePath",
            "-j": "jobs",
            "-U": "user",
            "-G": "group",
            "-I": "instance_name",
            "-e": "scenes",
            "--format": "format",
            "--cid": "cid",
            "--routing": "routing",
            "--ShrinkNodes": "shrinkNodes",
            "--az": "az_name",
            "--root-passwd": "rootPasswd",
            "--alarm-type": "warningType",
            "--alarm-server-addr": "warningserverip",
            "--autostart": "autostart",
            "--time-out": "time_out", "": "",
            "--alarm-component": "alarm_component",
            "--SSD-fault-time": "SSDFaultTime",
            "--begin-time": "begintime",
            "--end-time": "endtime",
            "--keyword": "keyword",
            "--redis-mode": "redismode",
            "--failure-limit": "failure_limit",
            "--virtual-ip": "virtual-ip",
            "--master": "master",
            "--standby": "standby",
            "--lvs-addr": "lvsAddr",
            "--disk-threshold": "disk-threshold",
            "--target": "target",
            "--name": "name",
            "-N": "DSN",
            "--type": "type",
            "--remote-host": "remote_host",
            "--ignore-host": "ignore_host",
            "--remote-env-file": "remote_mpprcfile",
            "--dilatation-mode": "dilatation_mode",
            "--nodegroup-name": "nodegroup_name",
            "--new-nodegroup-name": "new_nodegroup_name",
            "--speed-limit": "speedLimit",
            # add "resourcectl" for resource control
            # in data redistribution
            "--resource-level": "resource_level",
            "--redis-track-task": "redis_track_task",
            "-p": "port",
            "--dn-port": "dn-port",
            "--dn-ip": "dn-ip",
            # Adapt 200 and 300 versions
            "--product": "productVersion",
            "--interval": "interval",
            "--threshold": "threshold",
            "--check-count": "check_count",
            "--wait-count": "wait_count",
            "--option": "option",
            "--uuid": "uuid",
            "--logAction": "logAction",
            "--logStep": "logStep",
            "--schedule-path": "sche_path",
            "--categoryid": "categoryid",
            "--category": "category",
            "--maintenance": "maintenance",
            "--parallel-min": "parallelmin",
            "--parallel-max": "parallelmax",
            "--retrytimes": "retrytimes",
            "--retrytimes-max": "retrytimesmax",
            "--set": "set",
            "--get": "get",
            "--priority": "priority",
            "--nodes": "nodes_number",
            "--collector": "sche_collection",
            "--white-list": "whitelist",
            "--keep-name": "keep-name"
        }
        parameterNeedValue_keys = parameterNeedValue.keys()

        parameterIsBool = {
            "-L": "localMode",
            "--set": "set",
            "--skip-root-items": "skipRootItems",
            "--non-interactive": "preMode",
            "--skip-os-set": "skipOSSet",
            "--skip-hostname-set": "skipHostnameSet",
            "--reset": "reset",
            "--parameter": "isParameter",
            "--binary": "isBinary",
            "--delete-data": "cleanInstance",
            "--delete-user": "delete-user",
            "--delete-group": "delete-group",
            "--delete-virtual-IP": "delete-virtual-IP",
            "--dws-mode": "dws-mode",
            "--detail": "show_detail",
            "--detail-all": "show_detail_all",
            "--rollback": "rollback",
            "--vacuum-full": "enable_vacuum",
            "--fast-redis": "enable_fast",
            "--distribute": "distribute",
            "--build-redistb": "buildTable",
            "--check-consistency": "consistencyCheck",
            "--key-files": "key-files",
            "--all": "all",
            "--force": "force",
            "--upgrade": "upgrade",
            "--lcname-only": "lcname-only",
            "--add-to-elastic": "add-to-elastic",
            "--skip-clean-node": "skip-clean-node",
            "--high-perform": "high-perform",
            "--elastic-group": "elastic-group",
            "--addto-elastic-group": "isAddElasticGroup",
            "--express": "express",
            "--online": "online",
            "--checkdisk": "checkdisk",
            "--close-hba": "closehba",
            "--lc-cluster": "lccluster",
            "--restore-hba": "restorehba",
            "--binary-only": "binaryOnly",
            "--parallel": "parallel",
            "--retrytimes": "retrytimes",
            "--alterinfo": "alterinfo",
            "--crontab": "crontab",
            "--json": "json",
            "--redistribution": "do_redis",
            "--dilatation": "do_dilate",
            "--risk-assess": "riskassess",
            "--check": "check",
            "--refresh-static-conf-only": "refresh-static-conf-only",
        }
        parameterIsBool_keys = parameterIsBool.keys()
        key_dict = {
            "-h": Parameter.get_para_for_help,
            "-D": Parameter.get_para_for_dir,
            "-M": Parameter.get_para_for_mount_cgroup,
            "-o": Parameter.get_para_for_out_file,
            "-i": Parameter.get_para_for_item,
            "--skip-items": Parameter.get_para_for_skip_items,
            "-X": Parameter.get_para_for_conf_file,
            "--env-var": Parameter.get_para_for_env_var,
            "--sep-env-file": Parameter.get_para_for_sep_env_file,
            "--gsinit-parameter": Parameter.get_para_for_gsinit_parameter,
            "--gtminit-parameter": Parameter.get_para_for_gtminit_parameter,
            "--cn-guc": Parameter.get_para_for_cn_guc,
            "--dn-guc": Parameter.get_para_for_dn_guc,
            "-l": Parameter.get_para_for_log_file,
            "--backup-dir": Parameter.get_para_for_backup_dir,
            "--all": Parameter.get_para_for_all,
            "--parallel-jobs": Parameter.get_para_for_parallel_jobs,
            "--ring-num": Parameter.get_para_for_ring_num,
            "--cert-file": Parameter.get_para_for_cert_file,
            "--priority-tables": Parameter.get_para_for_priority_tables,
            "--exclude-tables": Parameter.get_para_for_exclude_tables,
            "--remote-config-file": Parameter.get_para_for_remote_config_file,
            "--waiting-for-killing": Parameter.get_para_for_waiting_for_killing,
            "--static-config-file": Parameter.get_para_for_static_config_file,
        }

        # Parameter assignment and return
        for (key, value) in opts:
            if key in parameterNeedValue_keys:
                PARAMETER_VALUEDICT[parameterNeedValue[key]] = value
            elif key in parameterIsBool_keys:
                PARAMETER_VALUEDICT[parameterIsBool[key]] = True
            elif key in key_dict.keys():
                key_dict[key](value=value, key=key, module=module)
            elif key == "-W" or key == "--password":
                user_passwd.append(value)
            elif self.action != "license" and (key == "-f" or key == "--hosts"):
                hostFile = self.checkPath(key, value)
                PARAMETER_VALUEDICT['hostfile'] = os.path.realpath(hostFile)
            # Only check / symbol for gs_lcct.
            if key in ("--name", "--nodegroup-name", "--new-nodegroup-name"):
                self.checkLcGroupName(key, value)
            if key in "--uuid":
                PATTERN = "^[a-zA-Z0-9-]{36}$"
                pattern = re.compile(PATTERN)
                result = pattern.match(value)
                if result is None:
                    raise Exception(ErrorCode.GAUSS_500["GAUSS_50004"] % key[1:] +
                                    " The value of the uuid does not len 36 characters "
                                    "and can only contain letters, numbers, and underscores.")

            Parameter.checkParaVaild(key, value)

        parameterIsList = {"passwords": user_passwd,
                           "envparams": EnvParams,
                           "dbInitParams": DbInitParam,
                           "gtmInitParams": GtmInitParam,
                           "cooGucParams": CooGucParam,
                           "dataGucParams": DataGucParam,
                           "itemstr": Itemstr,
                           "skipItems": skipItems,
                           "nodename": NODE_NAME
                           }
        parameterlenkeys = parameterIsList.keys()
        for key in parameterlenkeys:
            if len(parameterIsList[key]) > 0:
                PARAMETER_VALUEDICT[key] = parameterIsList[key]
        return PARAMETER_VALUEDICT

    @staticmethod
    def get_para_for_help(value, module="", key=""):
        # Only obtain the last value of hostname
        del NODE_NAME[:]
        for node in value.strip().split(","):
            if node is not None and node != "" and (node not in NODE_NAME):
                NODE_NAME.append(node)

    @staticmethod
    def get_para_for_dir(value, module="", key=""):
        PARAMETER_VALUEDICT['dataDir'] = os.path.normpath(value)

    @staticmethod
    def get_para_for_mount_cgroup(value, module="", key=""):
        PARAMETER_VALUEDICT['cgroupMountDir'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_out_file(value, module, key=""):
        PARAMETER_VALUEDICT['outFile'] = os.path.realpath(value)
        if module not in ["collector", "check", "gsom"]:
            parameter = Parameter()
            parameter.createOutputDir(os.path.realpath(value))

    @staticmethod
    def get_para_for_item(value, module="", key=""):
        for item in value.strip().split(","):
            if item is not None and item != "" and (item not in Itemstr):
                Itemstr.append(item)

    @staticmethod
    def get_para_for_skip_items(value, module="", key=""):
        for item in value.strip().split(","):
            if item is not None and item != "" and (item not in skipItems):
                skipItems.append(item)

    @staticmethod
    def get_para_for_conf_file(value, key, module):
        if module != "uninstall":
            para = Parameter()
            xmlFile = para.checkPath(key, value)
            PARAMETER_VALUEDICT['confFile'] = os.path.realpath(xmlFile)
        else:
            xmlFile = str(value)
            PARAMETER_VALUEDICT['confFile'] = os.path.realpath(xmlFile)

    @staticmethod
    def get_para_for_env_var(value, module="", key=""):
        EnvParams.append(value)

    @staticmethod
    def get_para_for_sep_env_file(value, module="", key=""):
        PARAMETER_VALUEDICT['mpprcFile'] = os.path.realpath(value)

    @staticmethod
    def get_para_for_gsinit_parameter(value, module="", key=""):
        DbInitParam.append(value)

    @staticmethod
    def get_para_for_gtminit_parameter(value, module="", key=""):
        GtmInitParam.append(value)

    @staticmethod
    def get_para_for_cn_guc(value, module="", key=""):
        CooGucParam.append(value)

    @staticmethod
    def get_para_for_dn_guc(value, module="", key=""):
        DataGucParam.append(value)

    @staticmethod
    def get_para_for_log_file(value, module="", key=""):
        PARAMETER_VALUEDICT['logFile'] = os.path.realpath(value)

    @staticmethod
    def get_para_for_backup_dir(value, module="", key=""):
        PARAMETER_VALUEDICT['backupDir'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_all(value="", module="", key=""):
        PARAMETER_VALUEDICT['isParameter'] = True
        PARAMETER_VALUEDICT['isBinary'] = True

    @staticmethod
    def get_para_for_parallel_jobs(value, key, module=""):
        para = Parameter()
        paralleljobs = para.checkParamternum(key, value)
        PARAMETER_VALUEDICT['paralleljobs'] = paralleljobs

    @staticmethod
    def get_para_for_ring_num(value, key, module=""):
        para = Parameter()
        ringNumbers = para.checkParamternum(key, value)
        PARAMETER_VALUEDICT['ringNumbers'] = ringNumbers

    @staticmethod
    def get_para_for_cert_file(value, module="", key=""):
        PARAMETER_VALUEDICT['cert-file'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_priority_tables(value, module="", key=""):
        PARAMETER_VALUEDICT['priority-tables'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_exclude_tables(value, module="", key=""):
        PARAMETER_VALUEDICT['exclude-tables'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_remote_config_file(value, module="", key=""):
        PARAMETER_VALUEDICT['remote-config-file'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_static_config_file(value, module="", key=""):
        PARAMETER_VALUEDICT['static-config-file'] = os.path.realpath(value.strip())

    @staticmethod
    def get_para_for_waiting_for_killing(value, module="", key=""):
        waiting_time = Parameter.check_parameter_special_num(key=key, value=value)
        PARAMETER_VALUEDICT['waiting-for-killing'] = waiting_time

    @staticmethod
    def checkParaVaild(para, value):
        """
        function: check para valid
        input : NA
        output: NA
        """
        for role in VALUE_CHECK_LIST:
            if PARA_CHECK_LIST.__contains__(para):
                if value.find(role) >= 0:
                    GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50011"] %
                                           (para, value) + " Invalid value: %s." % role)
            if PATH_CHEKC_LIST.__contains__(para):
                if os.path.realpath(value).find(role) >= 0:
                    GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50011"] %
                                           (para, value) + " Invalid value: %s." % role)

    def checkLcGroupName(self, lcPara, lcGroupName):
        """
        function: Check if the virtual cluster name is legal.
        input : lcGroupName
        output: NA
        """
        PATTERN = "^[a-zA-Z0-9_]{1,63}$"
        pattern = re.compile(PATTERN)
        result = pattern.match(lcGroupName)
        if result is None:
            raise Exception(ErrorCode.GAUSS_500["GAUSS_50004"] % lcPara[1:] +
                            " The name of the logical cluster does not exceed 63 characters "
                            "and can only contain letters, numbers, and underscores.")
        if lcGroupName in ["group_version1", "group_version2", "group_version3", "elastic_group"]:
            raise Exception(ErrorCode.GAUSS_500["GAUSS_50004"] % lcPara[1:] +
                            " The name of the logical cluster cannot be 'group_version1' "
                            "or 'group_version2' or 'group_version3' or 'elastic_group'.")

    def getHelpAndVersionStatus(self):
        """
        function: get help and version information status
        input : NA
        output: helpflag, versionflag
        """
        helpflag = False
        versionflag = False
        for parameter in sys.argv[1:]:
            if parameter == "-?" or parameter == "--help":
                helpflag = True
            if parameter == "-V" or parameter == "--version":
                versionflag = True
        return helpflag, versionflag

    def getActionParameterValue(self, module):
        """
        function: get the action value
        input : parameter_list
        output: NA
        """
        actions = []
        getMode = False
        if module in special_list:
            if not sys.argv[1:]:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50014"] % module)
            elif '-t' in sys.argv[1:] and module == "shrink":
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50002"] % "t" + ".")

            if sys.argv[1:][-1] == "-t":
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t" + " option -t requires argument.")

            for n, value in enumerate(sys.argv[1:]):
                if sys.argv[1:][n - 1] == "-t":
                    actions.append(value)
                    if len(actions) != 1:
                        GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50006"] % actions[0])
                    self.action = value

            if self.action == "" and module != "shrink":
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50001"] % "t" + ".")

            self.verify_action_not_in_self(module)
        if self.action == "estimate":
            self.verify_estimate_para(getMode)

    def verify_estimate_para(self, get_mode):
        if sys.argv[1:][-1] == "-m":
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "m" + " option -m requires argument.")
        if sys.argv[1:][-1] == "--mode":
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "-mode" + " option --mode requires argument.")

        for n, value in enumerate(sys.argv[1:]):
            if sys.argv[1:][n - 1] == "-m" or sys.argv[1:][n - 1] == "--mode":
                self.mode = value
            if value.startswith("--mode="):
                self.mode = value[len("--mode="):]
                get_mode = True

        if self.mode == "":
            if get_mode:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] %
                                       "-mode" + " option --mode requires argument.")
            else:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50001"] % "m or --mode" + ".")

        if self.mode not in estimate_list:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "m or --mode")

    def verify_action_not_in_self(self, module):
        """
        """
        if ((module == "gsom" and self.action not in action_om) or
                (module == "replace" and self.action not in action_replace) or
                (module == "upgradectl" and self.action not in action_upgradectl) or
                (module == "expand" and self.action not in action_expand) or
                (module == "clusterresize" and self.action not in action_resize) or
                (module == "loadbalance" and self.action not in action_loadbalance) or
                (module == "lcctl" and self.action not in action_lcctl)):
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")

    def createOutputDir(self, path):
        """
        function: create output directory
        input : path
        output: NA
        """
        try:
            DefaultValue.checkOutputFile(path)
        except Exception as e:
            GaussLog.exitWithError(str(e))
        dirName = os.path.dirname(os.path.realpath(path))
        if not os.path.isdir(dirName):
            try:
                os.makedirs(dirName, 0o750)
            except Exception as e:
                GaussLog.exitWithError(ErrorCode.GAUSS_502["GAUSS_50206"] %
                                       ("outputfile[%s]" % path) + "Error:\n%s" % str(e))

    def checkParamternum(self, key, value):
        """
        function: Check some number parameters
        input : key, value
        output: numvalue
        """
        numvalue = 0
        try:
            numvalue = int(value)
            if numvalue <= 0:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] %
                                       key[1:] + " Parameter '%s' must be greater than or equal to 1." % key)
        except Exception as e:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50003"] %
                                   (key[1:], "integer") + " Error:\n%s" % str(e))

        return numvalue

    @staticmethod
    def check_parameter_special_num(key, value):
        """
        function: Check parameter waiting_for_killing that must be 0 or [30, 1200].
        input : key, value
        output: num_value
        """
        num_value = 1200
        try:
            num_value = int(value)
            if not (num_value == 0 or 30 <= num_value <= 1200):
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] %
                                       key[1:] + " Parameter '%s' must be 0 or [30, 1200]." % key)
        except Exception as e:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50003"] %
                                   (key[1:], "integer") + " Error:\n%s" % str(e))
        return num_value

    def checkPath(self, key, value):
        """
        function: Check some path parameters
        input : key, value
        output: path
        """
        # Check that the path parameter is a file
        try:
            if not value:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % key[1:] +
                                       "Error:\noption %s requires argument" % key)
            path = str(value)
            g_file.checkFilePermission(path, True)
            return path
        except Exception as e:
            GaussLog.exitWithError(str(e))

    def get_replace_para(self):
        para_meter_list = []
        parameter_map = {"warm-standby": "WarmStandby",
                         "install": "replaceinstall",
                         "config": "replaceconfig",
                         "start": "replacestart"}
        if self.action in parameter_map.keys():
            para_meter_list = ParameterDict.get(parameter_map[self.action])
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def get_expand_para(self):
        """
        """
        para_meter_list = []
        if self.action in action_expand:
            para_meter_list = ParameterDict.get(self.action)
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def get_cluster_resize_para(self):
        """
        """
        para_meter_list = []
        action_map = {"resize": "cr_resize",
                      "clean": "cr_clean",
                      "progress": "cr_progress"
                      }
        if self.action in action_map.keys():
            para_meter_list = ParameterDict.get(action_map[self.action])
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def get_upgradectl_para(self):
        """
        """
        para_meter_list = []
        parameter_map = {"chose-strategy": "chose_strategy",
                         "auto-rollback": "auto_rollback",
                         "auto-upgrade": "auto_upgrade",
                         "commit-upgrade": "commit_upgrade"}
        if self.action in parameter_map.keys():
            para_meter_list = ParameterDict.get(parameter_map[self.action])
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def get_gs_om_para(self):
        """
        """
        para_meter_list = []
        if self.action == "estimate":
            parameter_map = {"addCN": "estimate_addCN",
                             "expand": "estimate_expand",
                             "replace": "estimate_replace_warm_standby",
                             "warm-standby": "estimate_replace_warm_standby"}
            if self.mode in parameter_map.keys():
                para_meter_list = ParameterDict.get(parameter_map[self.mode])
            else:
                GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "m")
        elif self.action in action_om:
            para_meter_list = ParameterDict.get(self.action)
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def get_loadbalance_para(self):
        """
        """
        para_meter_list = []
        parameter_map = {"install": "loadbalance_install",
                         "reload": "loadbalance_reload",
                         "uninstall": "loadbalance_uninstall"}
        if self.action in parameter_map.keys():
            para_meter_list = ParameterDict.get(parameter_map[self.action])
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def get_lcctl_para(self):
        """
        """
        para_meter_list = []
        parameter_map = {"create": "lcctlcreate",
                         "transform": "lcctltransform",
                         "add": "lcctladd",
                         "rollback": "lcctlrollback",
                         "display": "lcctldisplay",
                         "delete": "lcctldelete",
                         "clean": "lcctlclean",
                         "progress": "lcctlprogress"}
        if self.action in parameter_map.keys():
            para_meter_list = ParameterDict.get(parameter_map[self.action])
        else:
            GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS_50004"] % "t")
        return para_meter_list

    def getParseParameter(self, module):
        """
        function: get parse parameters
        input : parameter_list
        output: shortPara,longPara
        """

        shortPara = ""
        longPara = []
        var = "--"
        module_dict = {
            "replace": self.get_replace_para,
            "expand": self.get_expand_para,
            "clusterresize": self.get_cluster_resize_para,
            "upgradectl": self.get_upgradectl_para,
            "gsom": self.get_gs_om_para,
            "loadbalance": self.get_loadbalance_para,
            "lcctl": self.get_lcctl_para
        }
        if module in module_dict.keys():
            ParameterList = module_dict[module]()
        else:
            ParameterList = ParameterDict.get(module)

        for para in ParameterList:
            if var in para:
                varlong = para.strip("--")
                longPara.append(varlong)
            else:
                varshort = para.strip("-")
                shortPara += varshort

        return shortPara, longPara
