如何在 Scala 中获取部署到 YARN 的 Spark 应用程序的 applicationId?

How to get applicationId of Spark application deployed to YARN in Scala?

我正在使用以下 Scala 代码(作为自定义 spark-submit 包装器)将 Spark 应用程序提交到 YARN 集群:

val result = Seq(spark_submit_script_here).!!

提交时我只有 spark-submit 和 Spark 应用程序的 jar(没有 SparkContext)。我想从 result 捕获 applicationId,但它是空的。

我可以在我的命令行输出中看到 applicationId 和其余的 Yarn 消息:

INFO yarn.Client: Application report for application_1450268755662_0110

如何在代码中读取它并获取 applicationId?

Spark issue 5439 中所述,您可以使用 SparkContext.applicationId 或解析 stderr 输出。现在,当您用自己的 script/object 包装 spark-submit 命令时,我会说您需要阅读标准错误并获取应用程序 ID。

如果您通过 Python 提交作业,那么您可以通过以下方式获取 yarn 应用程序 ID:

    cmd_list = [{
            'cmd': '/usr/bin/spark-submit --name %s --master yarn --deploy-mode cluster '
                   '--executor-memory %s --executor-cores %s --num-executors %s '
                   '--class %s %s %s'
                   % (
                       app_name,
                       config.SJ_EXECUTOR_MEMORY,
                       config.SJ_EXECUTOR_CORES,
                       config.SJ_NUM_OF_EXECUTORS,
                       config.PRODUCT_SNAPSHOT_SKU_PRESTO_CLASS,
                       config.SPARK_JAR_LOCATION,
                       config.SPARK_LOGGING_ENABLED
                   ),
            'cwd': config.WORK_DIR
        }]
cmd_output = subprocess.run(cmd_obj['cmd'], shell=True, check=True, cwd=cwd, stderr=subprocess.PIPE)
cmd_output = cmd_output.stderr.decode("utf-8")
yarn_application_ids = re.findall(r"application_\d{13}_\d{4}", cmd_output)
                if len(yarn_application_ids):
                    yarn_application_id = yarn_application_ids[0]
                    yarn_command = "yarn logs -applicationId " + yarn_application_id

使用 spark 上下文获取应用程序信息。

sc.getConf.getAppId 
res7: String = application_1532296406128_16555

作为 Rajiv 的回答,正则表达式 'application_\d{13}_\d{4}' 不正确

实际上,job id 会比 9999 增加更多, 所以 application_\d{13}_\d{4,} 的正则表达式将正常工作

和java代码

   public static final String APPLICATION_REGEX="application_\d+_\d{4,}+";

   /**
     * get yarn application id list
     * @param log   log content
     * @return app id list
     */
    public static List<String> getAppIds(String log) {
        List<String> appIds = new ArrayList<>();
        Matcher matcher = APPLICATION_REGEX.matcher(log);
        while (matcher.find()) {
            String appId = matcher.group();
            if(!appIds.contains(appId)){
                appIds.add(appId);
            }
        }
        return appIds;
    }