Example #1
0
    def _run_main(self, parsed_args, parsed_globals):
        # tccli configure
        profile_name = parsed_globals.profile \
            if parsed_globals.profile else "default"

        config = {
            OptionsDefine.Region: "ap-guangzhou",
            OptionsDefine.Output: "json"
        }

        cred = {
            OptionsDefine.SecretId: "None",
            OptionsDefine.SecretKey: "None"
        }

        is_conf_exist, config_path = self._profile_existed(profile_name +
                                                           ".configure")
        is_cred_exist, cred_path = self._profile_existed(profile_name +
                                                         ".credential")

        conf_data = {}
        cred_data = {}
        if is_conf_exist:
            conf_data = Utils.load_json_msg(config_path)
            for c in config:
                if c in conf_data and conf_data[c]:
                    config[c] = conf_data[c]
        if is_cred_exist:
            cred_data = Utils.load_json_msg(cred_path)
            for c in cred:
                if c in cred_data and cred_data[c]:
                    cred[c] = cred_data[c]

        for index, prompt_text in self.VALUES_TO_PROMPT:
            if index in config:
                response = self._compat_input("%s[%s]: " %
                                              (prompt_text, config[index]))
                conf_data[index] = response if response else config[index]
            else:
                response = self._compat_input(
                    "%s[%s]: " % (prompt_text, "*" + cred[index][-4:]
                                  if cred[index] != "None" else cred[index]))
                cred_data[index] = response if response else cred[index]

        self._init_configure(profile_name + ".configure", conf_data)
        self._init_configure(profile_name + ".credential", cred_data)
Example #2
0
 def _handle_warning(self, args):
     profile = "default"
     if "--profile" in args:
         location = args.index("--profile") + 1
         if location < len(args):
             profile = args[location]
     conf_path = os.path.join(os.path.expanduser("~"), ".tccli")
     conf = {}
     if Utils.file_existed(conf_path, profile + ".configure")[0]:
         conf = Utils.load_json_msg(
             os.path.join(conf_path, profile + ".configure"))
     if "--warning" not in args and conf.get("warning", "") != "on":
         import warnings
         warnings.filterwarnings("ignore")
Example #3
0
    def _run_main(self, args, parsed_globals):
        profile_name = parsed_globals.profile \
            if parsed_globals.profile else "default"

        is_exit, cred_path = self._profile_existed(profile_name +
                                                   ".credential")
        self._stream.write("credential:\n")
        if is_exit:
            cred = Utils.load_json_msg(cred_path)
            for config in self.cred_list:
                if config in cred and cred[config]:
                    self._stream.write("%s = %s\n" % (config, cred[config]))

        # other in x.configure
        is_exit, config_path = self._profile_existed(profile_name +
                                                     ".configure")
        self._stream.write("configure:\n")
        if is_exit:
            config = Utils.load_json_msg(config_path)
            for c in self.config_list:
                if c in config and config[c]:
                    self._stream.write("%s = %s\n" % (c, config[c]))

            modlist = sorted(config.keys())
            for c in modlist:
                if not config[c]:
                    continue
                if c in self.config_list:
                    continue
                try:
                    self._stream.write("%s.version = %s\n" %
                                       (c, config[c]["version"]))
                    self._stream.write("%s.endpoint = %s\n" %
                                       (c, config[c]["endpoint"]))
                except Exception:
                    pass
Example #4
0
 def _add_array_item(self, param_list, profile):
     is_conf_exist, conf_path = Utils.file_existed(
         os.path.join(os.path.expanduser("~"), ".tccli"),
         profile + ".configure")
     if is_conf_exist:
         array_count = Utils.load_json_msg(conf_path).get("arrayCount", 10)
     else:
         array_count = 10
     all_param_list = param_list
     for para in param_list:
         for idx, item in enumerate(para):
             if item == '0':
                 for i in range(1, int(array_count)):
                     tmp = copy.deepcopy(para)
                     tmp[idx] = str(i)
                     all_param_list.append(tmp)
     return all_param_list
def parse_global_arg(parsed_globals):
    g_param = parsed_globals

    is_exist_profile = True
    if not parsed_globals["profile"]:
        is_exist_profile = False
        g_param["profile"] = "default"

    configure_path = os.path.join(os.path.expanduser("~"), ".tccli")
    is_conf_exist, conf_path = Utils.file_existed(
        configure_path, g_param["profile"] + ".configure")
    is_cred_exist, cred_path = Utils.file_existed(
        configure_path, g_param["profile"] + ".credential")

    conf = {}
    cred = {}

    if is_conf_exist:
        conf = Utils.load_json_msg(conf_path)
    if is_cred_exist:
        cred = Utils.load_json_msg(cred_path)

    if not (isinstance(conf, dict) and isinstance(cred, dict)):
        raise ConfigurationError("file: %s or %s is not json format" %
                                 (g_param["profile"] + ".configure",
                                  g_param["profile"] + ".credential"))

    if os.environ.get(OptionsDefine.ENV_SECRET_ID) and not is_exist_profile:
        cred[OptionsDefine.SecretId] = os.environ.get(
            OptionsDefine.ENV_SECRET_ID)
    if os.environ.get(OptionsDefine.ENV_SECRET_KEY) and not is_exist_profile:
        cred[OptionsDefine.SecretKey] = os.environ.get(
            OptionsDefine.ENV_SECRET_KEY)
    if os.environ.get(OptionsDefine.ENV_REGION) and not is_exist_profile:
        conf[OptionsDefine.Region] = os.environ.get(OptionsDefine.ENV_REGION)

    for param in g_param.keys():
        if g_param[param] is None:
            if param in [OptionsDefine.SecretKey, OptionsDefine.SecretId]:
                if param in cred:
                    g_param[param] = cred[param]
                else:
                    raise ConfigurationError("%s is invalid" % param)
            elif param in [OptionsDefine.Region, OptionsDefine.Output]:
                if param in conf:
                    g_param[param] = conf[param]
                else:
                    raise ConfigurationError("%s is invalid" % param)

    try:
        if g_param[OptionsDefine.ServiceVersion]:
            g_param[OptionsDefine.Version] = "v" + g_param[
                OptionsDefine.ServiceVersion].replace('-', '')
        else:
            version = conf["tdmq"][OptionsDefine.Version]
            g_param[OptionsDefine.Version] = "v" + version.replace('-', '')

        if g_param[OptionsDefine.Endpoint] is None:
            g_param[OptionsDefine.Endpoint] = conf["tdmq"][
                OptionsDefine.Endpoint]
    except Exception as err:
        raise ConfigurationError("config file:%s error, %s" %
                                 (conf_path, str(err)))

    if g_param[OptionsDefine.Version] not in AVAILABLE_VERSION_LIST:
        raise Exception("available versions: %s" %
                        " ".join(AVAILABLE_VERSION_LIST))

    return g_param
def parse_global_arg(parsed_globals):
    g_param = parsed_globals

    is_exist_profile = True
    if not parsed_globals["profile"]:
        is_exist_profile = False
        g_param["profile"] = "default"

    configure_path = os.path.join(os.path.expanduser("~"), ".tccli")
    is_conf_exist, conf_path = Utils.file_existed(
        configure_path, g_param["profile"] + ".configure")
    is_cred_exist, cred_path = Utils.file_existed(
        configure_path, g_param["profile"] + ".credential")

    conf = {}
    cred = {}

    if is_conf_exist:
        conf = Utils.load_json_msg(conf_path)
    if is_cred_exist:
        cred = Utils.load_json_msg(cred_path)

    if not (isinstance(conf, dict) and isinstance(cred, dict)):
        raise ConfigurationError("file: %s or %s is not json format" %
                                 (g_param["profile"] + ".configure",
                                  g_param["profile"] + ".credential"))

    if OptionsDefine.Token not in cred:
        cred[OptionsDefine.Token] = None

    if not is_exist_profile:
        if os.environ.get(OptionsDefine.ENV_SECRET_ID) and os.environ.get(
                OptionsDefine.ENV_SECRET_KEY):
            cred[OptionsDefine.SecretId] = os.environ.get(
                OptionsDefine.ENV_SECRET_ID)
            cred[OptionsDefine.SecretKey] = os.environ.get(
                OptionsDefine.ENV_SECRET_KEY)
            cred[OptionsDefine.Token] = os.environ.get(OptionsDefine.ENV_TOKEN)

        if os.environ.get(OptionsDefine.ENV_REGION):
            conf[OptionsDefine.Region] = os.environ.get(
                OptionsDefine.ENV_REGION)

        if os.environ.get(OptionsDefine.ENV_ROLE_ARN) and os.environ.get(
                OptionsDefine.ENV_ROLE_SESSION_NAME):
            cred[OptionsDefine.RoleArn] = os.environ.get(
                OptionsDefine.ENV_ROLE_ARN)
            cred[OptionsDefine.RoleSessionName] = os.environ.get(
                OptionsDefine.ENV_ROLE_SESSION_NAME)

    for param in g_param.keys():
        if g_param[param] is None:
            if param in [
                    OptionsDefine.SecretKey, OptionsDefine.SecretId,
                    OptionsDefine.Token
            ]:
                if param in cred:
                    g_param[param] = cred[param]
                elif not g_param[OptionsDefine.UseCVMRole.replace('-', '_')]:
                    raise ConfigurationError("%s is invalid" % param)
            elif param in [OptionsDefine.Region, OptionsDefine.Output]:
                if param in conf:
                    g_param[param] = conf[param]
                else:
                    raise ConfigurationError("%s is invalid" % param)
            elif param.replace('_', '-') in [
                    OptionsDefine.RoleArn, OptionsDefine.RoleSessionName
            ]:
                if param.replace('_', '-') in cred:
                    g_param[param] = cred[param.replace('_', '-')]

    try:
        if g_param[OptionsDefine.ServiceVersion]:
            g_param[OptionsDefine.Version] = "v" + g_param[
                OptionsDefine.ServiceVersion].replace('-', '')
        else:
            version = conf["oceanus"][OptionsDefine.Version]
            g_param[OptionsDefine.Version] = "v" + version.replace('-', '')

        if g_param[OptionsDefine.Endpoint] is None:
            g_param[OptionsDefine.Endpoint] = conf["oceanus"][
                OptionsDefine.Endpoint]
    except Exception as err:
        raise ConfigurationError("config file:%s error, %s" %
                                 (conf_path, str(err)))

    if g_param[OptionsDefine.Version] not in AVAILABLE_VERSION_LIST:
        raise Exception("available versions: %s" %
                        " ".join(AVAILABLE_VERSION_LIST))

    if g_param[OptionsDefine.Waiter]:
        param = eval(g_param[OptionsDefine.Waiter])
        if 'expr' not in param:
            raise Exception('`expr` in `--waiter` must be defined')
        if 'to' not in param:
            raise Exception('`to` in `--waiter` must be defined')
        if 'timeout' not in param:
            if 'waiter' in conf and 'timeout' in conf['waiter']:
                param['timeout'] = conf['waiter']['timeout']
            else:
                param['timeout'] = 180
        if 'interval' not in param:
            if 'waiter' in conf and 'interval' in conf['waiter']:
                param['interval'] = conf['waiter']['interval']
            else:
                param['timeout'] = 5
        param['interval'] = min(param['interval'], param['timeout'])
        g_param['OptionsDefine.WaiterInfo'] = param

    # 如果在配置文件中读取字段的值,python2中的json.load函数会读取unicode类型的值,因此这里要转化类型
    if six.PY2:
        for key, value in g_param.items():
            if isinstance(value, six.text_type):
                g_param[key] = value.encode('utf-8')
    return g_param