Пример #1
0
    def post(self):
        args = self.parser.parse_args()
        mainLogger.debug("## args =  {0}".format(args))
        if is_none(args.get("ServiceName")) or is_none(args.get("Application")) or is_none(args.get("Workflow")):
            raise MissingRequiredParametersException(" ServiceName and  Application and  Workflow  are/is requried")
        # return serilization type
        ret_type = args.get("RT")
        if ret_type is None:
            ret_type = "JSON"

        # current_node_envs = infa_env.get_envs(current_node.id)  # type: dict
        current_node_envs = get_current_node_infa_envs()
        os.environ.update(current_node_envs)
        mainLogger.debug("environment variables is {0}".format(current_node_envs))
        args.pop("RT")

        res = startWorkflow(**args)
        mainLogger.debug(res)
        stdout = str(res.stdout)
        if ret_type.upper() == "PROTOBUF":
            proto_resp = infaCliResponse_pb2.InfaCliResponse()
            proto_resp.retcode = res.retcode
            proto_resp.stdout = stdout
            res = proto_resp.SerializeToString()
            mainLogger.debug("protobuf: the result is {0}".format(res))
            content_type = Config.PREDEFINED_CONTENT_TYPES.get("PROTOBUF")
        else:
            output_dict = {"retcode": res.retcode,
                           "stdout": stdout
                           }
            res = json.dumps(output_dict)
            content_type = Config.PREDEFINED_CONTENT_TYPES.get("JSON")
        response = make_response(res)
        response.headers["Content-Type"] = content_type
        return response
Пример #2
0
def _checking_infacmd_env_and_ret_base_cmd(domainname, username, password, cmd, subcmd, verify_username_password=True):
    infa_home_key = Config.PREDEFINED_ENV_VARIABLES_ATTRIBUTE.INFA_HOME
    infa_default_domain_key = Config.PREDEFINED_ENV_VARIABLES_ATTRIBUTE.INFA_DEFAULT_DOMAIN
    infa_home = os.environ.get(infa_home_key)
    infa_default_domain = os.environ.get(infa_default_domain_key)

    if verify_username_password:
        infa_default_domain_password_key = Config.PREDEFINED_ENV_VARIABLES_ATTRIBUTE.INFA_DEFAULT_DOMAIN_PASSWORD
        infa_default_domain_user_key = Config.PREDEFINED_ENV_VARIABLES_ATTRIBUTE.INFA_DEFAULT_DOMAIN_USER
        infa_default_domain_password = os.environ.get(infa_default_domain_password_key)
        infa_default_domain_user = os.environ.get(infa_default_domain_user_key)

    exceptions = ""
    if is_none(infa_home):
        exceptions = infa_home_key
    if is_none(domainname) and is_none(infa_default_domain):
        exceptions += " INFA_DEFAULT_DOMAIN or domainName , "
    if verify_username_password and (is_none(username) or is_none(password)) and (
            is_none(infa_default_domain_user) or is_none(infa_default_domain_password)):
        exceptions += " INFA_DEFAULT_DOMAIN_USER/userName or INFA_DEFAULT_DOMAIN_PASSWORD/password"

    if not is_none(exceptions, treat_space_as_none=True):
        raise MissingEnvironmentVariable(exceptions + " is missing")

    return "{0}/server/bin/infacmd{1} {2} {3} ".format(infa_home, shell_suffix(), cmd, subcmd)
Пример #3
0
def listApplications(
    servicename: str,
    domainname: str = None,
    username: str = None,
    password: str = None,
    securitydomain: str = "Native",
    resiliencetimeout: int = None
) -> namedtuple("ListApplicationsResult", ['retcode', "stdout", "stderr"]):
    sub_cmd = "listapplications"
    cmd = _checking_infacmd_env_and_ret_base_cmd(domainname, username,
                                                 password, base_cmd, sub_cmd)
    options = [
        "domainname", "servicename", "username", "password", "securitydomain",
        "resiliencetimeout"
    ]

    options_value_dict = locals()
    for option in options:
        cmd = _assemble_command_options(cmd, option,
                                        options_value_dict.get(option))

    mainLogger.debug(cmd)
    res = run_cmd(cmd, env=os.environ)
    mainLogger.info(res)

    stdout = res.stdout  # type: str
    stderr = res.stderr  # type: str
    if res.retcode == 0 and not is_none(res.stdout):
        # format the stdout
        stdout_formated = stdout.split("\n")  # type: list
        stdout = stdout_formated[:-1]
    else:
        stderr += stdout

    ret = namedtuple("ListApplicationsResult", ['retcode', "stdout", "stderr"])
    return ret(res.retcode, stdout, stderr)
Пример #4
0
def pmpasswd(
    passwd: str,
    encrypt_type: str = None
) -> namedtuple("pmpasswdResult", ['retcode', 'stdout']):
    """
    You can encrypt passwords to create an environment variable to use with infacmd, 
    infasetup, pmcmd, and pmrep or to define a password in a parameter file. 
    For example, you can encrypt the repository and database passwords for pmrep to maintain
    security when using pmrep in scripts. Then you can create an environment variable to store the 
    encrypted password. Or, you can define a password for a relational database connection object in 
    a parameter file.

    :param passwd: to be encrypted password
    :param encrypt_type: CRYPT_DATA | CRYPT_SYSTEM
    :return: encrypted password
    """
    infa_home_key = Config.PREDEFINED_ENV_VARIABLES_ATTRIBUTE.INFA_HOME
    infa_home = os.environ.get(infa_home_key)
    if is_none(infa_home):
        raise MissingEnvironmentVariable(
            "the {0} is not set".format(infa_home_key))

    ld_lib_path_name = get_LIBRARY_PATH_NAME()
    if ld_lib_path_name:
        existing_ld_lib_path_value = os.environ.get(ld_lib_path_name)
        infa_ld_lib_path = "{0}/server/bin:{1}/services/shared/bin".format(
            infa_home, infa_home)
        os.environ.update({
            ld_lib_path_name:
            "{0}:{1}".format(infa_ld_lib_path, existing_ld_lib_path_value)
        })

    if is_none(encrypt_type):
        command = "{infa_home}/server/bin/pmpasswd {passwd} ".format(
            infa_home=infa_home, passwd=passwd)
    elif encrypt_type is not None and encrypt_type.upper() in ('CRYPT_DATA',
                                                               'CRYPT_SYSTEM'):
        command = "{infa_home}/server/bin/pmpasswd {passwd} -e {encrypt_type}".format(
            infa_home=infa_home,
            passwd=passwd,
            encrypt_type=encrypt_type.upper())
    else:
        errmsg = "{0} is not supported in pmpasswd command".format(
            encrypt_type)
        mainLogger.error(errmsg)
        raise UnsupportedEncryptionType(errmsg)

    mainLogger.debug(os.environ)
    mainLogger.info(command)

    cmd_result = run_cmd(command, env=os.environ)
    mainLogger.debug(cmd_result)

    stdout = cmd_result.stdout  # type: str
    stderr = cmd_result.stderr  # type: str
    msg = None
    if cmd_result.retcode == 0:
        msg = stdout[stdout.index("-->") + 3:stdout.index("<--")]
    else:
        msg = stderr + " " + stdout[stdout.index("usage:"):]

    pmpasswdResult = namedtuple("pmpasswdResult", ['retcode', 'stdout'])

    return pmpasswdResult(cmd_result.retcode, msg)
Пример #5
0
def backupDomain(domainname,
                 databasetype,
                 databaseaddress = None,
                 databaseconnectionstring = None,
                 databaseusername = None,
                 databaseservicename = None,
                 backupfile = None,
                 force = False,
                 tablespace = None,
                 schemaname = None,
                 databasetlsenabled = None,
                 databasetruststorepassword = None,
                 trustedconnection = False,
                 encryptionkeylocation = None,
                 databasetruststorelocation = None)\
        -> namedtuple("CommandResult", ['retcode', "stdout", "backupfile"]):
    """备份domain 元数据
    Backs up the configuration metadata for the domain. infasetup stores the backup domain metadata in a backup file
    with an extension of .mrep. You must shut down the domain before you run this command.
    When you run this command, infasetup backs up the domain configuration database tables to restore the domain to
    another database. You must back up the ISP_RUN_LOG table contents manually to get the previous workflow and session
    logs. If the command fails with a Java memory error, increase the system memory available for infasetup. To increase
     the system memory, set the -Xmx value in the INFA_JAVA_CMD_OPTS environment variable.
    :param domain_name:
    :param databaseaddress:
    :param databaseconnectionstring:
    :param databaseusername:
    :param databasetype:
    :param databaseservicename:
    :param backupfile:
    :param force:
    :param tablespace:
    :param schemaname:
    :param databasetlsenabled:
    :param databasetruststorepassword:
    :param trustedconnection:
    :param encryptionkeylocation:
    :param databasetruststorelocation:
    :param db_host:
    :param db_port:
    :param db_user:
    :param db_type:
    :param db_service_name:
    :param envs: 环境变量
    :param backup_path: 备份绝对路径或者绝对路径的备份文件
    :return: namedtuple("CommandResult", ['retcode', "stdout", "backupfile"])
    """
    mainLogger.info("invoking the backupdomain command")
    """ get environment parameters"""
    infa_default_database_password_key = Config.PREDEFINED_ENV_VARIABLES.get(
        "INFA_DEFAULT_DATABASE_PASSWORD")
    infa_default_database_password = os.environ.get(
        infa_default_database_password_key)

    infa_home_key = Config.PREDEFINED_ENV_VARIABLES.get("INFA_HOME")
    infa_home = os.environ.get(infa_home_key)

    if is_none(infa_default_database_password) or is_none(infa_home):
        raise MissingEnvironmentVariable("the {0} or {1} is missing ".format(
            infa_home_key, infa_default_database_password_key))
    """Backup direcotry or filename"""
    filename = "{0}.{1}".format(
        datetime.strftime(datetime.now(), "%Y-%m-%d-%H-%M-%S-%s"), "mrep")

    if backupfile is None:
        backupfile = os.path.join(get_backup_dir(domain_name=domainname),
                                  filename)
    # if the backupfile is existing and directory, then it will use our defined backup directory
    elif backupfile is not None and os.path.isdir(backupfile):
        backupfile = os.path.join(
            get_backup_dir(backup_path=backupfile, domain_name=domainname),
            filename)
    elif backupfile is not None and os.path.isfile(backupfile):
        # backupfile = backupfile
        pass
    else:
        raise Exception(
            "Backup directory you specified is not existing, please make sure it's existing and direcotry!"
        )
    """assemble the backup commands"""
    commands = "{INFA_HOME}/isp/bin/infasetup{scipt_suffix} backupdomain ".format(
        INFA_HOME=infa_home, scipt_suffix=shell_suffix())

    options = [
        "domainname", "databaseaddress", "databaseconnectionstring",
        "databaseusername", "databasetype", "databaseservicename",
        "backupfile", "force", "tablespace", "schemaname",
        "databasetlsenabled", "databasetruststorepassword",
        "trustedconnection", "encryptionkeylocation",
        "databasetruststorelocation"
    ]
    options_value_dict = locals()
    for option in options:
        commands = _assemble_command_options(commands, option,
                                             options_value_dict.get(option))

    mainLogger.debug(os.environ)
    mainLogger.info(commands)
    """invoke the command"""
    cmd = run_cmd(commands, env=os.environ, live=False)
    """reformat the outputs and return the outputs"""
    msg = cmd.stdout
    # 0 stands for success, others stand for failure
    # if fails, the concatenates the stderr messages
    if cmd.retcode != 0:
        msg = "{0}; {1}".format(msg, cmd.stderr.decode())
    result = namedtuple("CommandResult", ['retcode', "stdout", "backupfile"])
    mainLogger.info(msg)
    return result(cmd.retcode, msg, backupfile)