[
https://issues.apache.org/jira/browse/BEAM-8471?focusedWorklogId=334084&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-334084
]
ASF GitHub Bot logged work on BEAM-8471:
----------------------------------------
Author: ASF GitHub Bot
Created on: 25/Oct/19 11:28
Start Date: 25/Oct/19 11:28
Worklog Time Spent: 10m
Work Description: mxm commented on pull request #9872: [BEAM-8471] Flink
native job submission for portable pipelines
URL: https://github.com/apache/beam/pull/9872#discussion_r339000051
##########
File path:
runners/flink/src/main/java/org/apache/beam/runners/flink/FlinkPortableClientRunner.java
##########
@@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.beam.runners.flink;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.apache.beam.model.pipeline.v1.RunnerApi;
+import org.apache.beam.runners.fnexecution.environment.ProcessManager;
+import org.apache.beam.runners.fnexecution.jobsubmission.JobInvocation;
+import org.apache.beam.runners.fnexecution.jobsubmission.JobInvoker;
+import
org.apache.beam.runners.fnexecution.jobsubmission.PortablePipelineResult;
+import
org.apache.beam.runners.fnexecution.jobsubmission.PortablePipelineRunner;
+import org.apache.beam.runners.fnexecution.provisioning.JobInfo;
+import
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions;
+import
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
+import
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.ListeningExecutorService;
+import org.apache.flink.api.common.time.Deadline;
+import org.apache.flink.api.java.ExecutionEnvironment;
+import org.apache.flink.client.program.OptimizerPlanEnvironment;
+import org.kohsuke.args4j.CmdLineException;
+import org.kohsuke.args4j.CmdLineParser;
+import org.kohsuke.args4j.Option;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Launch a Beam pipeline via external SDK driver program in the Flink {@link
+ * OptimizerPlanEnvironment}.
+ *
+ * <p>This entry point can be used to execute an external program to launch a
Beam pipeline within
+ * the Flink {@link OptimizerPlanEnvironment}, which is present when running a
job via the REST API.
+ *
+ * <p>Designed for non-interactive Flink REST client and container with the
Beam job server jar and
+ * SDK client (for example when using the FlinkK8sOperator).
+ *
+ * <p>Eliminates the need to build jar files with materialized pipeline protos
offline. Allows the
+ * driver program to access actual execution environment and services, on par
with code executed by
+ * SDK workers.
+ *
+ * <p>The entry point starts the job server and provides the endpoint to the
the driver program.
+ *
+ * <p>The external driver program constructs the Beam pipeline and submits it
to the job service.
+ *
+ * <p>The job service defers execution of the pipeline to the plan environment
and returns the
+ * "detached" status to the driver program.
+ *
+ * <p>Upon arrival of the job invocation, the entry point executes the runner,
which prepares
+ * ("executes") the Flink job through the plan environment.
+ *
+ * <p>Finally Flink launches the job.
+ */
+public class FlinkPortableClientRunner {
+ private static final Logger LOG =
LoggerFactory.getLogger(FlinkPortableClientRunner.class);
+ private static final String DRIVER_CMD_FLAGS = "--job_endpoint=%s";
+
+ private final String driverCmd;
+ private FlinkJobServerDriver driver;
+ private Thread driverThread;
+ private DetachedJobInvokerFactory jobInvokerFactory;
+ private int jobPort = 0; // any free port
+
+ public FlinkPortableClientRunner(String driverCmd) {
+ this.driverCmd = driverCmd;
+ }
+
+ /** Main method to be called within the Flink OptimizerPlanEnvironment. */
+ public static void main(String[] args) throws Exception {
+ Preconditions.checkArgument(
+ ExecutionEnvironment.getExecutionEnvironment() instanceof
OptimizerPlanEnvironment,
+ "Can only execute in OptimizerPlanEnvironment");
+ LOG.info("entry points args: {}", Arrays.asList(args));
+ EntryPointConfiguration configuration = parseArgs(args);
+ FlinkPortableClientRunner runner = new
FlinkPortableClientRunner(configuration.driverCmd);
+ try {
+ runner.startJobService();
+ runner.runDriverProgram();
+ } catch (Exception e) {
+ throw new RuntimeException(String.format("Job %s failed.",
configuration.driverCmd), e);
+ } finally {
+ LOG.info("Stopping job service");
+ runner.stopJobService();
+ }
+ LOG.info("Job submitted successfully.");
+ }
+
+ private static class EntryPointConfiguration {
+ @Option(
+ name = "--driver-cmd",
+ required = true,
+ usage =
+ "Command that launches the Python driver program. "
+ + "(The job service endpoint will be appended as
--job_endpoint=localhost:<port>.)")
+ private String driverCmd;
+ }
+
+ private static EntryPointConfiguration parseArgs(String[] args) {
+ EntryPointConfiguration configuration = new EntryPointConfiguration();
+ CmdLineParser parser = new CmdLineParser(configuration);
+ try {
+ parser.parseArgument(args);
+ } catch (CmdLineException e) {
+ LOG.error("Unable to parse command line arguments.", e);
+ parser.printUsage(System.err);
+ throw new IllegalArgumentException("Unable to parse command line
arguments.", e);
+ }
+ return configuration;
+ }
+
+ private void startJobService() throws Exception {
+ jobInvokerFactory = new DetachedJobInvokerFactory();
+ driver =
+ FlinkJobServerDriver.fromConfig(
+ FlinkJobServerDriver.fromParams(
+ new String[] {"--job-port=" + jobPort, "--artifact-port=0",
"--expansion-port=0"}),
+ jobInvokerFactory);
+ driverThread = new Thread(driver);
+ driverThread.start();
+
+ Duration timeout = Duration.ofSeconds(30);
+ Deadline deadline = Deadline.fromNow(timeout);
+ while (driver.getJobServerUrl() == null && deadline.hasTimeLeft()) {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException interruptEx) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(interruptEx);
+ }
+ }
+
+ if (!driverThread.isAlive()) {
+ throw new IllegalStateException("Job service thread is not alive");
+ }
+
+ if (driver.getJobServerUrl() == null) {
+ String msg = String.format("Timeout of %s waiting for job service to
start.", deadline);
+ throw new TimeoutException(msg);
+ }
+ }
+
+ private void runDriverProgram() throws Exception {
+ ProcessManager processManager = ProcessManager.create();
+ String executable = "bash";
+ List<String> args =
+ ImmutableList.of(
+ "-c",
+ String.format("exec %s " + DRIVER_CMD_FLAGS, driverCmd,
driver.getJobServerUrl()));
+ String processId = "client1";
+
+ try {
+ final ProcessManager.RunningProcess driverProcess =
+ processManager.startProcess(processId, executable, args,
System.getenv());
+ driverProcess.isAliveOrThrow();
+ LOG.info("Started driver program");
+
+ // await effect of the driver program submitting the job
+ jobInvokerFactory.executeDetachedJob();
+ } catch (Exception e) {
+ try {
+ processManager.stopProcess(processId);
+ } catch (Exception processKillException) {
+ e.addSuppressed(processKillException);
+ }
+ throw e;
+ }
+ }
+
+ private void stopJobService() throws InterruptedException {
+ if (driver != null) {
+ driver.stop();
+ }
+ if (driverThread != null) {
+ driverThread.interrupt();
+ driverThread.join();
+ }
+ }
+
+ private class DetachedJobInvokerFactory implements
FlinkJobServerDriver.JobInvokerFactory {
+
+ private CountDownLatch latch = new CountDownLatch(1);
+ private PortablePipelineRunner actualPipelineRunner;
+ private RunnerApi.Pipeline pipeline;
Review comment:
```suggestion
private volatile RunnerApi.Pipeline pipeline;
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
Issue Time Tracking
-------------------
Worklog Id: (was: 334084)
Time Spent: 40m (was: 0.5h)
> Flink native job submission for portable pipelines
> --------------------------------------------------
>
> Key: BEAM-8471
> URL: https://issues.apache.org/jira/browse/BEAM-8471
> Project: Beam
> Issue Type: Improvement
> Components: runner-flink
> Reporter: Thomas Weise
> Assignee: Thomas Weise
> Priority: Major
> Labels: portability-flink
> Time Spent: 40m
> Remaining Estimate: 0h
>
> There are currently two methods to run a portable pipeline written in a
> non-JVM language to Flink:
> 1) Run the SDK client entry point which will submit the job server, which in
> turn will submit to a Flink cluster using the Flink remote environment
> 2) Run the SDK client entry point to generate a Flink jar file that can be
> used to start the Flink job using any of the Flink client tooling available.
> Either approach requires the SDK client and the job server dependency to be
> present on the client. This doesn't work well in environments such as
> FlinkK8sOperator that rely on the Flink REST API jar run endpoint (see
> [https://docs.google.com/document/d/1z3LNrRtr8kkiFHonZ5JJM_L4NWNBBNcqRc_yAf6G0VI/edit#heading=h.x7hki4bhh18l]).
> This improvement is to provide a new Flink entry point (main method) that
> invokes the SDK client entry point to generate the pipeline and submits the
> resulting Flink job like any other Flink native driver program would, via the
> optimizer plan environment ("[auto]").
>
--
This message was sent by Atlassian Jira
(v8.3.4#803005)