diff --git a/streampark-common/src/main/java/org/apache/streampark/common/util/StreamParkLoggerFactory.java b/streampark-common/src/main/java/org/apache/streampark/common/util/StreamParkLoggerFactory.java index f56c784e6e..414f509c17 100644 --- a/streampark-common/src/main/java/org/apache/streampark/common/util/StreamParkLoggerFactory.java +++ b/streampark-common/src/main/java/org/apache/streampark/common/util/StreamParkLoggerFactory.java @@ -29,9 +29,10 @@ import org.apache.streampark.shaded.org.slf4j.spi.LoggerFactoryBinder; import java.io.ByteArrayInputStream; -import java.io.File; +import java.io.InputStream; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.util.regex.Pattern; /** Shaded logback SLF4J logger factory binder. */ public final class StreamParkLoggerFactory implements LoggerFactoryBinder { @@ -83,12 +84,15 @@ public String getLoggerFactoryClassStr() { return CONTEXT_SELECTOR_BINDER.getClass().getName(); } - private static final class ShadedContextInitializer extends ContextInitializer { + static final class ShadedContextInitializer extends ContextInitializer { private static final String SHADED_PACKAGE = "org.apache.streampark.shaded"; + private static final Pattern LOGGING_PACKAGE = Pattern.compile( + "(?"; + } +} diff --git a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationActionServiceImpl.java b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationActionServiceImpl.java index 32ae0d0fed..b816b87999 100644 --- a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationActionServiceImpl.java +++ b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationActionServiceImpl.java @@ -642,7 +642,8 @@ private BuildResult resolveBuildResultForSubmit( FlinkApplication application, BuildResult buildResult, String flinkUserJar) { - if (FlinkDeployMode.YARN_APPLICATION == application.getDeployModeEnum()) { + if (FlinkDeployMode.YARN_APPLICATION == application.getDeployModeEnum() + && !application.isFlinkSqlJob()) { return new ShadedBuildResponse(null, flinkUserJar, true); } if (!(buildResult instanceof ShadedBuildResponse)) { diff --git a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildPipelineServiceImpl.java b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildPipelineServiceImpl.java index 07fdf8d81f..baafeb4ee6 100644 --- a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildPipelineServiceImpl.java +++ b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildPipelineServiceImpl.java @@ -372,7 +372,7 @@ private BuildPipeline createPipelineInstance(@Nonnull FlinkApplication app) { localWorkspace = app.getLocalAppHome(); } FlinkYarnApplicationBuildRequest yarnAppRequest = buildFlinkYarnApplicationBuildRequest(app, mainClass, - localWorkspace, yarnProvidedPath); + localWorkspace, yarnProvidedPath, flinkEnv, flinkUserJar); log.info("Submit params to building pipeline : {}", yarnAppRequest); return FlinkYarnApplicationBuildPipeline.of(yarnAppRequest); case YARN_PER_JOB: @@ -404,14 +404,18 @@ private FlinkYarnApplicationBuildRequest buildFlinkYarnApplicationBuildRequest( @Nonnull FlinkApplication app, String mainClass, String localWorkspace, - String yarnProvidedPath) { + String yarnProvidedPath, + FlinkEnv flinkEnv, + String flinkUserJar) { return new FlinkYarnApplicationBuildRequest( app.getJobName(), mainClass, - localWorkspace, + app.isFlinkSqlJob() ? app.getLocalAppHome() : localWorkspace, yarnProvidedPath, app.getJobTypeEnum(), - getMergedDependencyInfo(app)); + getMergedDependencyInfo(app), + FlinkEnvUtils.version(flinkEnv), + flinkUserJar); } @Nonnull diff --git a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/impl/FlinkClusterServiceImpl.java b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/impl/FlinkClusterServiceImpl.java index f88b5c5af4..fd557b4e1a 100644 --- a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/impl/FlinkClusterServiceImpl.java +++ b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/service/impl/FlinkClusterServiceImpl.java @@ -424,7 +424,7 @@ private ShutdownResponse shutdownInternal(FlinkCluster flinkCluster, flinkCluster.getId(), getKubernetesDeploySpec(flinkCluster, "shutdown")); Future future = executorService.submit(() -> FlinkClient.shutdown(stopRequest)); - return future.get(60, TimeUnit.SECONDS); + return future.get(clusterOperationTimeout(flinkCluster), TimeUnit.SECONDS); } private DeployResponse deployInternal(FlinkCluster flinkCluster) throws InterruptedException, ExecutionException, TimeoutException { @@ -437,7 +437,13 @@ private DeployResponse deployInternal(FlinkCluster flinkCluster) throws Interrup getKubernetesDeploySpec(flinkCluster, "start")); log.info("Deploy cluster request {}", deployRequest); Future future = executorService.submit(() -> FlinkClient.deploy(deployRequest)); - return future.get(60, TimeUnit.SECONDS); + return future.get(clusterOperationTimeout(flinkCluster), TimeUnit.SECONDS); + } + + private long clusterOperationTimeout(FlinkCluster flinkCluster) { + return flinkCluster.getFlinkDeployModeEnum() == FlinkDeployMode.KUBERNETES_NATIVE_SESSION + ? 300L + : 60L; } private void checkActiveIfNeeded(FlinkCluster flinkCluster) { diff --git a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcher.java b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcher.java index 4de04a7bef..64ebaebdb7 100644 --- a/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcher.java +++ b/streampark-console/streampark-console-service/src/main/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcher.java @@ -197,6 +197,7 @@ private ClusterState httpYarnSessionClusterState(FlinkCluster flinkCluster) { private ClusterState httpClusterState(FlinkCluster flinkCluster) { switch (flinkCluster.getFlinkDeployModeEnum()) { case REMOTE: + case KUBERNETES_NATIVE_SESSION: return httpRemoteClusterState(flinkCluster); case YARN_SESSION: return httpYarnSessionClusterState(flinkCluster); diff --git a/streampark-console/streampark-console-service/src/test/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildResultTest.java b/streampark-console/streampark-console-service/src/test/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildResultTest.java new file mode 100644 index 0000000000..bc33017aac --- /dev/null +++ b/streampark-console/streampark-console-service/src/test/java/org/apache/streampark/console/core/service/application/impl/FlinkApplicationBuildResultTest.java @@ -0,0 +1,57 @@ +/* + * 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.streampark.console.core.service.application.impl; + +import org.apache.streampark.common.enums.FlinkDeployMode; +import org.apache.streampark.common.enums.FlinkJobType; +import org.apache.streampark.console.core.entity.FlinkApplication; +import org.apache.streampark.flink.packer.pipeline.ShadedBuildResponse; +import org.apache.streampark.flink.packer.pipeline.SimpleBuildResponse; + +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +class FlinkApplicationBuildResultTest { + + @Test + void submitBuiltYarnSqlJar() { + FlinkApplication application = application(FlinkJobType.FLINK_SQL); + ShadedBuildResponse built = new ShadedBuildResponse("/app", "/app/sql-fat.jar"); + Object resolved = ReflectionTestUtils.invokeMethod( + new FlinkApplicationActionServiceImpl(), "resolveBuildResultForSubmit", + application, built, "/client/sql-client.jar"); + assertThat(resolved).isSameAs(built); + } + + @Test + void preserveYarnJarArtifact() { + Object resolved = ReflectionTestUtils.invokeMethod( + new FlinkApplicationActionServiceImpl(), "resolveBuildResultForSubmit", + application(FlinkJobType.FLINK_JAR), new SimpleBuildResponse(), "/app/user.jar"); + assertThat(((ShadedBuildResponse) resolved).shadedJarPath()).isEqualTo("/app/user.jar"); + } + + private FlinkApplication application(FlinkJobType jobType) { + FlinkApplication application = new FlinkApplication(); + application.setDeployMode(FlinkDeployMode.YARN_APPLICATION.getMode()); + application.setJobType(jobType.getMode()); + return application; + } +} diff --git a/streampark-console/streampark-console-service/src/test/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcherTest.java b/streampark-console/streampark-console-service/src/test/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcherTest.java new file mode 100644 index 0000000000..daade17ba8 --- /dev/null +++ b/streampark-console/streampark-console-service/src/test/java/org/apache/streampark/console/core/watcher/FlinkClusterWatcherTest.java @@ -0,0 +1,88 @@ +/* + * 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.streampark.console.core.watcher; + +import org.apache.streampark.common.enums.ClusterState; +import org.apache.streampark.common.enums.FlinkDeployMode; +import org.apache.streampark.console.core.entity.FlinkCluster; + +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; + +class FlinkClusterWatcherTest { + + private HttpServer server; + private String address; + + @BeforeEach + void startRestEndpoint() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/overview", exchange -> { + byte[] response = "{\"taskmanagers\":1,\"slots-total\":2,\"slots-available\":2}" + .getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, response.length); + try (java.io.OutputStream output = exchange.getResponseBody()) { + output.write(response); + } + }); + server.start(); + address = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopRestEndpoint() { + server.stop(0); + } + + @Test + void verifyKubernetesSessionRestEndpoint() { + FlinkCluster cluster = cluster(FlinkDeployMode.KUBERNETES_NATIVE_SESSION); + cluster.setJobManagerUrl(address); + FlinkClusterWatcher watcher = new FlinkClusterWatcher(); + assertThat(watcher.verifyClusterConnection(cluster)).isTrue(); + assertThat(watcher.getClusterState(cluster)).isEqualTo(ClusterState.RUNNING); + } + + @Test + void preserveRemoteRestHealthCheck() { + assertThat(new FlinkClusterWatcher().verifyClusterConnection(cluster(FlinkDeployMode.REMOTE))) + .isTrue(); + } + + @Test + void rejectUnreachableKubernetesSession() { + FlinkCluster cluster = cluster(FlinkDeployMode.KUBERNETES_NATIVE_SESSION); + server.stop(0); + assertThat(new FlinkClusterWatcher().verifyClusterConnection(cluster)).isFalse(); + } + + private FlinkCluster cluster(FlinkDeployMode mode) { + FlinkCluster cluster = new FlinkCluster(); + cluster.setId(4508L); + cluster.setDeployMode(mode.getMode()); + cluster.setAddress(address); + return cluster; + } +} diff --git a/streampark-flink/streampark-flink-client/streampark-flink-client-core/src/main/java/org/apache/streampark/flink/client/impl/YarnApplicationClient.java b/streampark-flink/streampark-flink-client/streampark-flink-client-core/src/main/java/org/apache/streampark/flink/client/impl/YarnApplicationClient.java index 4a08f13adc..4deb743f6e 100644 --- a/streampark-flink/streampark-flink-client/streampark-flink-client-core/src/main/java/org/apache/streampark/flink/client/impl/YarnApplicationClient.java +++ b/streampark-flink/streampark-flink-client/streampark-flink-client-core/src/main/java/org/apache/streampark/flink/client/impl/YarnApplicationClient.java @@ -71,8 +71,6 @@ protected void setConfig(ResolvedSubmitRequest resolved, Configuration flinkConf providedLibs.add(hdfsWorkspace.appJars()); if (submitRequest.jobType() == FlinkJobType.FLINK_SQL) { - providedLibs.add( - WORKSPACE.shims + "/flink-" + submitRequest.flinkVersion().majorVersion()); String jobLib = WORKSPACE.workspace + "/" + submitRequest.id() + "/lib"; try { if (HdfsUtils.exists(jobLib)) { diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/docker/FlinkHadoopDockerfileTemplate.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/docker/FlinkHadoopDockerfileTemplate.java index 97f15d2586..a0bb4fec9f 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/docker/FlinkHadoopDockerfileTemplate.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/docker/FlinkHadoopDockerfileTemplate.java @@ -53,14 +53,12 @@ public FlinkHadoopDockerfileTemplate( this.flinkExtraLibPaths = flinkExtraLibPaths; this.hadoopConfDirPath = hadoopConfDirPath; this.hiveConfDirPath = hiveConfDirPath; - this.hadoopConfDir = - workspace() - .relativize(Paths.get(hadoopConfDirPath == null ? "" : hadoopConfDirPath)) - .toString(); - this.hiveConfDir = - workspace() - .relativize(Paths.get(hiveConfDirPath == null ? "" : hiveConfDirPath)) - .toString(); + this.hadoopConfDir = hadoopConfDirPath == null || hadoopConfDirPath.isEmpty() + ? "" + : workspace().relativize(Paths.get(hadoopConfDirPath).toAbsolutePath()).toString(); + this.hiveConfDir = hiveConfDirPath == null || hiveConfDirPath.isEmpty() + ? "" + : workspace().relativize(Paths.get(hiveConfDirPath).toAbsolutePath()).toString(); } @Override diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/FlinkSqlDependencySupport.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/FlinkSqlDependencySupport.java new file mode 100644 index 0000000000..9c356fab31 --- /dev/null +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/FlinkSqlDependencySupport.java @@ -0,0 +1,42 @@ +/* + * 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.streampark.flink.packer.maven; + +import java.io.File; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** Runtime dependencies excluded from the packaged SQL client. */ +public final class FlinkSqlDependencySupport { + + private static final Artifact SNAKEYAML = new Artifact("org.yaml", "snakeyaml", "2.0"); + + private FlinkSqlDependencySupport() { + } + + public static DependencyInfo withRuntimeDependencies(DependencyInfo dependencies) { + return dependencies.merge(Collections.singletonList(SNAKEYAML), null); + } + + public static Set resolveRuntimeJars() throws Exception { + List jars = MavenTool.resolveArtifacts(Collections.singleton(SNAKEYAML)); + return jars.stream().map(File::getAbsolutePath).collect(Collectors.toSet()); + } +} diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/MavenTool.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/MavenTool.java index 888a8081ef..ddb3ae462e 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/MavenTool.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/maven/MavenTool.java @@ -57,7 +57,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -167,7 +169,12 @@ private File buildFatJarInternal( } logInfo("start shaded fat-jar: " + String.join(",", jarLibs)); ShadeRequest shadeRequest = new ShadeRequest(); - shadeRequest.setJars(jarSet); + // The shader keeps the first duplicate class. Target shims must override the + // baseline classes embedded in the SQL client and the shared shim artifact. + shadeRequest.setJars(jarSet.stream() + .sorted(Comparator.comparingInt(MavenTool::shimPriority) + .thenComparing(File::getAbsolutePath)) + .collect(Collectors.toCollection(LinkedHashSet::new))); shadeRequest.setUberJar(uberJar); List transformer = new ArrayList<>(); transformer.add(new ServicesResourceTransformer()); @@ -186,6 +193,16 @@ private File buildFatJarInternal( return uberJar; } + private static int shimPriority(File jar) { + if (jar.getName().startsWith("streampark-flink-shims_flink-")) { + return 0; + } + if (jar.getName().startsWith("streampark-flink-shims-base-")) { + return 1; + } + return 2; + } + /** * Build a fat-jar with custom jar libraries and maven artifacts. * @@ -307,10 +324,7 @@ public boolean isFiltered(String name) { boolean isFilteredState = name.startsWith("META-INF/") && name.endsWith(".SF") || name.endsWith(".DSA") - || name.endsWith(".RSA") - || name.startsWith("org/yaml/") - || name.startsWith("META-INF/versions/") - && name.contains("/org/yaml/"); + || name.endsWith(".RSA"); if (isFilteredState) { INSTANCE.logInfo("shade ignore file: " + name); return true; diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkBuildParam.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkBuildParam.java index d1ddfb8bdc..d909d04079 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkBuildParam.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkBuildParam.java @@ -22,6 +22,7 @@ import org.apache.streampark.common.enums.FlinkDeployMode; import org.apache.streampark.common.enums.FlinkJobType; import org.apache.streampark.flink.packer.maven.DependencyInfo; +import org.apache.streampark.flink.packer.maven.FlinkSqlDependencySupport; import java.util.Arrays; import java.util.HashSet; @@ -51,7 +52,10 @@ default DependencyInfo providedLibs() { + "/flink-" + flinkVersion().majorVersion()); } - return dependencyInfo().merge(libs); + DependencyInfo dependencies = dependencyInfo().merge(libs); + return flinkJobType() == FlinkJobType.FLINK_SQL + ? FlinkSqlDependencySupport.withRuntimeDependencies(dependencies) + : dependencies; } default String getShadedJarPath(String rootWorkspace) { diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkYarnApplicationBuildRequest.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkYarnApplicationBuildRequest.java index b61f39ea8e..aa6de51862 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkYarnApplicationBuildRequest.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/FlinkYarnApplicationBuildRequest.java @@ -17,10 +17,12 @@ package org.apache.streampark.flink.packer.pipeline; +import org.apache.streampark.common.core.FlinkVersion; +import org.apache.streampark.common.enums.FlinkDeployMode; import org.apache.streampark.common.enums.FlinkJobType; import org.apache.streampark.flink.packer.maven.DependencyInfo; -public class FlinkYarnApplicationBuildRequest implements BuildParam { +public class FlinkYarnApplicationBuildRequest implements FlinkBuildParam { private final String appName; private final String mainClass; @@ -28,6 +30,8 @@ public class FlinkYarnApplicationBuildRequest implements BuildParam { private final String yarnProvidedPath; private final FlinkJobType flinkJobType; private final DependencyInfo dependencyInfo; + private final FlinkVersion flinkVersion; + private final String customFlinkUserJar; public FlinkYarnApplicationBuildRequest( String appName, @@ -35,13 +39,17 @@ public FlinkYarnApplicationBuildRequest( String localWorkspace, String yarnProvidedPath, FlinkJobType flinkJobType, - DependencyInfo dependencyInfo) { + DependencyInfo dependencyInfo, + FlinkVersion flinkVersion, + String customFlinkUserJar) { this.appName = appName; this.mainClass = mainClass; this.localWorkspace = localWorkspace; this.yarnProvidedPath = yarnProvidedPath; this.flinkJobType = flinkJobType; this.dependencyInfo = dependencyInfo; + this.flinkVersion = flinkVersion; + this.customFlinkUserJar = customFlinkUserJar; } @Override @@ -58,6 +66,26 @@ public String localWorkspace() { return localWorkspace; } + @Override + public String workspace() { + return localWorkspace; + } + + @Override + public FlinkDeployMode deployMode() { + return FlinkDeployMode.YARN_APPLICATION; + } + + @Override + public FlinkVersion flinkVersion() { + return flinkVersion; + } + + @Override + public String customFlinkUserJar() { + return customFlinkUserJar; + } + public String yarnProvidedPath() { return yarnProvidedPath; } diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/PipelineTypeEnum.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/PipelineTypeEnum.java index 025412ca9e..305976fb12 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/PipelineTypeEnum.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/PipelineTypeEnum.java @@ -67,10 +67,10 @@ public enum PipelineTypeEnum { "flink yarn application mode task building pipeline", ImmutableMap.builder() .put(1, "Prepare hadoop yarn environment and building workspace") - .put(2, "Resolve maven dependencies") - .put(3, "upload jar to yarn.provided.lib.dirs") + .put(2, "Resolve dependencies and build application jar") + .put(3, "Upload application dependencies") .build(), - SimpleBuildResponse.class), + ShadedBuildResponse.class), FLINK_K8S_APPLICATION_V2( 5, diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkK8sApplicationBuildPipeline.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkK8sApplicationBuildPipeline.java index f4c121c146..5e1fb573cf 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkK8sApplicationBuildPipeline.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkK8sApplicationBuildPipeline.java @@ -17,6 +17,7 @@ package org.apache.streampark.flink.packer.pipeline.impl; +import org.apache.streampark.common.enums.FlinkJobType; import org.apache.streampark.common.fs.LfsOperator; import org.apache.streampark.flink.kubernetes.PodTemplateTool; import org.apache.streampark.flink.kubernetes.ingress.IngressController; @@ -24,6 +25,7 @@ import org.apache.streampark.flink.packer.docker.FlinkDockerfileTemplate; import org.apache.streampark.flink.packer.docker.FlinkDockerfileTemplateTrait; import org.apache.streampark.flink.packer.docker.FlinkHadoopDockerfileTemplate; +import org.apache.streampark.flink.packer.maven.FlinkSqlDependencySupport; import org.apache.streampark.flink.packer.maven.MavenTool; import org.apache.streampark.flink.packer.pipeline.DockerImageBuildResponse; import org.apache.streampark.flink.packer.pipeline.FlinkK8sApplicationBuildRequest; @@ -33,6 +35,7 @@ import org.apache.commons.lang3.StringUtils; import java.io.File; +import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -94,12 +97,15 @@ public DockerImageBuildResponse buildProcess() { logInfo("Output shaded flink job jar: " + jar.getAbsolutePath()); return jar; }); - final Set extJarLibs = request.dependencyInfo().extJarLibs(); Object[] dockerResult = execStep( 4, () -> { + Set extJarLibs = new HashSet<>(request.dependencyInfo().extJarLibs()); + if (request.flinkJobType() == FlinkJobType.FLINK_SQL) { + extJarLibs.addAll(FlinkSqlDependencySupport.resolveRuntimeJars()); + } FlinkDockerfileTemplateTrait template; if (request.integrateWithHadoop()) { template = diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkRemoteBuildPipeline.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkRemoteBuildPipeline.java index 9c3dd496c6..1bc38f2cd6 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkRemoteBuildPipeline.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkRemoteBuildPipeline.java @@ -20,7 +20,7 @@ import org.apache.streampark.common.enums.FlinkJobType; import org.apache.streampark.common.fs.FsOperator; import org.apache.streampark.common.fs.LfsOperator; -import org.apache.streampark.flink.packer.maven.Artifact; +import org.apache.streampark.flink.packer.maven.FlinkSqlDependencySupport; import org.apache.streampark.flink.packer.maven.MavenTool; import org.apache.streampark.flink.packer.pipeline.BuildPipeline; import org.apache.streampark.flink.packer.pipeline.FlinkRemotePerJobBuildRequest; @@ -99,12 +99,7 @@ public ShadedBuildResponse buildProcess() { return paths; } if (request.flinkJobType() == FlinkJobType.FLINK_SQL) { - List snakeyaml = - MavenTool.resolveArtifacts( - Collections.singleton(new Artifact("org.yaml", "snakeyaml", "2.0"))); - return snakeyaml.stream() - .map(File::getAbsolutePath) - .collect(Collectors.toList()); + return new java.util.ArrayList<>(FlinkSqlDependencySupport.resolveRuntimeJars()); } return Collections.emptyList(); }); diff --git a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkYarnApplicationBuildPipeline.java b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkYarnApplicationBuildPipeline.java index 249ca08fbf..c3fef1b34e 100644 --- a/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkYarnApplicationBuildPipeline.java +++ b/streampark-flink/streampark-flink-packer/src/main/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkYarnApplicationBuildPipeline.java @@ -18,10 +18,22 @@ package org.apache.streampark.flink.packer.pipeline.impl; import org.apache.streampark.common.enums.FlinkJobType; +import org.apache.streampark.common.fs.FsOperator; +import org.apache.streampark.common.fs.HdfsOperator; +import org.apache.streampark.common.fs.LfsOperator; +import org.apache.streampark.flink.packer.maven.DependencyInfo; +import org.apache.streampark.flink.packer.maven.FlinkSqlDependencySupport; +import org.apache.streampark.flink.packer.maven.MavenTool; import org.apache.streampark.flink.packer.pipeline.BuildPipeline; import org.apache.streampark.flink.packer.pipeline.FlinkYarnApplicationBuildRequest; import org.apache.streampark.flink.packer.pipeline.PipelineTypeEnum; -import org.apache.streampark.flink.packer.pipeline.SimpleBuildResponse; +import org.apache.streampark.flink.packer.pipeline.ShadedBuildResponse; +import org.apache.streampark.flink.packer.pipeline.YarnJarUploader; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; /** Building pipeline for flink yarn application mode */ public class FlinkYarnApplicationBuildPipeline extends BuildPipeline { @@ -43,16 +55,36 @@ public FlinkYarnApplicationBuildRequest offerBuildParam() { } @Override - public SimpleBuildResponse buildProcess() { - boolean sqlMode = - request.flinkJobType() == FlinkJobType.FLINK_SQL - || request.flinkJobType() == FlinkJobType.PYFLINK; - runYarnSqlBuildSteps( - request.localWorkspace(), - request.yarnProvidedPath(), - sqlMode, - request.dependencyInfo()); - return new SimpleBuildResponse(); + public ShadedBuildResponse buildProcess() { + if (request.flinkJobType() != FlinkJobType.FLINK_SQL) { + runYarnSqlBuildSteps( + request.localWorkspace(), + request.yarnProvidedPath(), + request.flinkJobType() == FlinkJobType.PYFLINK, + request.dependencyInfo()); + return new ShadedBuildResponse(request.workspace(), null); + } + + execStep(1, () -> { + LfsOperator.mkCleanDirs(request.workspace()); + HdfsOperator.mkCleanDirs(request.yarnProvidedPath()); + return null; + }); + File shadedJar = execStep(2, () -> MavenTool.buildFatJar( + request.mainClass(), request.providedLibs(), request.getShadedJarPath(request.workspace()))); + execStep(3, () -> { + DependencyInfo dependencies = + FlinkSqlDependencySupport.withRuntimeDependencies(request.dependencyInfo()); + Set jars = MavenTool.resolveArtifacts(dependencies.mavenArts()).stream() + .map(File::getAbsolutePath).collect(Collectors.toCollection(HashSet::new)); + jars.addAll(dependencies.extJarLibs()); + for (String jar : jars) { + YarnJarUploader.uploadJarToHdfsOrLfs(FsOperator.lfs(), jar, request.workspace() + "/lib"); + YarnJarUploader.uploadJarToHdfsOrLfs(FsOperator.hdfs(), jar, request.yarnProvidedPath()); + } + return null; + }); + return new ShadedBuildResponse(request.workspace(), shadedJar.getAbsolutePath()); } public static FlinkYarnApplicationBuildPipeline of(FlinkYarnApplicationBuildRequest request) { diff --git a/streampark-flink/streampark-flink-packer/src/test/java/org/apache/streampark/flink/packer/maven/MavenToolMergeOrderTest.java b/streampark-flink/streampark-flink-packer/src/test/java/org/apache/streampark/flink/packer/maven/MavenToolMergeOrderTest.java new file mode 100644 index 0000000000..6f529d776c --- /dev/null +++ b/streampark-flink/streampark-flink-packer/src/test/java/org/apache/streampark/flink/packer/maven/MavenToolMergeOrderTest.java @@ -0,0 +1,70 @@ +/* + * 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.streampark.flink.packer.maven; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; + +import static org.assertj.core.api.Assertions.assertThat; + +class MavenToolMergeOrderTest { + + @TempDir + Path workspace; + + @Test + void preferTargetShimOverEmbeddedClasses() throws Exception { + for (int index = 0; index < 10; index++) { + Path directory = Files.createDirectories(workspace.resolve("app-" + index)); + Path client = createJar(directory, "streampark-flink-sqlclient-3.0.0.jar", (byte) 0); + Path base = createJar(directory, "streampark-flink-shims-base-3.0.0.jar", (byte) 1); + Path shim = createJar(directory, "streampark-flink-shims_flink-2.2-3.0.0.jar", (byte) 2); + Path output = directory.resolve("job.jar"); + MavenTool.buildFatJar("org.apache.streampark.flink.cli.SqlClient", + new LinkedHashSet<>(List.of(client.toString(), base.toString(), shim.toString())), + output.toString()); + try (JarFile jar = new JarFile(output.toFile())) { + assertThat(jar.getInputStream(jar.getJarEntry("target-shim.class")).readAllBytes()) + .containsExactly((byte) 2); + assertThat(jar.getManifest().getMainAttributes().getValue("Main-Class")) + .isEqualTo("org.apache.streampark.flink.cli.SqlClient"); + } + } + } + + private Path createJar(Path directory, String name, byte content) throws Exception { + Path jar = directory.resolve(name); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar), manifest)) { + output.putNextEntry(new JarEntry("target-shim.class")); + output.write(new byte[]{content}); + output.closeEntry(); + } + return jar; + } +} diff --git a/streampark-flink/streampark-flink-packer/src/test/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkSqlApplicationBuildTest.java b/streampark-flink/streampark-flink-packer/src/test/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkSqlApplicationBuildTest.java new file mode 100644 index 0000000000..2891f63890 --- /dev/null +++ b/streampark-flink/streampark-flink-packer/src/test/java/org/apache/streampark/flink/packer/pipeline/impl/FlinkSqlApplicationBuildTest.java @@ -0,0 +1,176 @@ +/* + * 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.streampark.flink.packer.pipeline.impl; + +import org.apache.streampark.common.configuration.Configuration; +import org.apache.streampark.common.configuration.GlobalConfiguration; +import org.apache.streampark.common.configuration.Workspace; +import org.apache.streampark.common.configuration.option.MavenOptions; +import org.apache.streampark.common.core.FlinkVersion; +import org.apache.streampark.common.enums.FlinkDeployMode; +import org.apache.streampark.common.enums.FlinkJobType; +import org.apache.streampark.flink.kubernetes.model.KubernetesPodTemplates; +import org.apache.streampark.flink.packer.docker.DockerConf; +import org.apache.streampark.flink.packer.maven.DependencyInfo; +import org.apache.streampark.flink.packer.pipeline.DockerImageBuildResponse; +import org.apache.streampark.flink.packer.pipeline.FlinkK8sApplicationBuildRequest; +import org.apache.streampark.flink.packer.pipeline.FlinkYarnApplicationBuildRequest; +import org.apache.streampark.flink.packer.pipeline.PipelineTypeEnum; +import org.apache.streampark.flink.packer.pipeline.ShadedBuildResponse; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.yaml.snakeyaml.Yaml; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.concurrent.Callable; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.JarOutputStream; + +import static org.assertj.core.api.Assertions.assertThat; + +class FlinkSqlApplicationBuildTest { + + @TempDir + Path workspace; + + private Configuration original; + + @BeforeEach + void prepareRuntimeRepository() throws Exception { + original = GlobalConfiguration.current(); + Path repository = workspace.resolve("repository/org/yaml/snakeyaml/2.0"); + Files.createDirectories(repository); + Files.copy(Path.of(Yaml.class.getProtectionDomain().getCodeSource().getLocation().toURI()), + repository.resolve("snakeyaml-2.0.jar")); + Files.writeString(repository.resolve("snakeyaml-2.0.pom"), + "4.0.0org.yaml" + + "snakeyaml2.0"); + GlobalConfiguration.set(MavenOptions.REPOSITORY_URL, + workspace.resolve("repository").toUri().toString(), "local test repository"); + } + + @AfterEach + void restoreConfiguration() { + GlobalConfiguration.update(original); + } + + @Test + void buildSqlArtifactWithRuntimeDependencies() throws Exception { + Path client = createJar("sql-client.jar", "org/apache/streampark/flink/cli/SqlClient.class"); + Path connector = createJar("connector.jar", "test/Connector.class"); + FlinkYarnApplicationBuildRequest request = new FlinkYarnApplicationBuildRequest( + "SQL job", "org.apache.streampark.flink.cli.SqlClient", + workspace.resolve("app").toString(), "/remote/app/lib", FlinkJobType.FLINK_SQL, + new DependencyInfo(Collections.emptySet(), Collections.singleton(connector.toString())), + new FlinkVersion(workspace.toString()) { + + @Override + public String majorVersion() { + return "2.2"; + } + }, client.toString()); + assertThat(request.providedLibs().extJarLibs()) + .contains(Workspace.LOCAL.shims + "/flink-2.2", client.toString()); + Files.createDirectories(Path.of(request.workspace())); + FlinkYarnApplicationBuildPipeline pipeline = new FlinkYarnApplicationBuildPipeline(request) { + + @Override + protected R execStep(int seq, Callable process) { + // Exercise the packaging step without requiring an HDFS cluster. + if (seq != 2) { + return null; + } + try { + return process.call(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + }; + ShadedBuildResponse result = pipeline.buildProcess(); + assertThat(result.pass()).isTrue(); + assertThat(PipelineTypeEnum.FLINK_YARN_APPLICATION.getResultType()) + .isEqualTo(ShadedBuildResponse.class); + assertThat(result.shadedJarPath()).endsWith("/app/streampark-flinkjob_SQL_job.jar"); + try (JarFile jar = new JarFile(result.shadedJarPath())) { + assertThat(jar.getJarEntry("org/apache/streampark/flink/cli/SqlClient.class")).isNotNull(); + assertThat(jar.getJarEntry("test/Connector.class")).isNotNull(); + assertThat(jar.getJarEntry("org/yaml/snakeyaml/Yaml.class")).isNotNull(); + assertThat(jar.getManifest().getMainAttributes().getValue("Main-Class")) + .isEqualTo(request.mainClass()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void buildKubernetesSqlImageContext(boolean hadoop) throws Exception { + Path client = createJar("sql-client.jar", "org/apache/streampark/flink/cli/SqlClient.class"); + Path connector = createJar("connector.jar", "test/Connector.class"); + DependencyInfo dependencies = new DependencyInfo(Collections.emptySet(), + Collections.singleton(connector.toString())); + FlinkK8sApplicationBuildRequest request = new FlinkK8sApplicationBuildRequest( + "SQL job", workspace.resolve("app").toString(), "org.apache.streampark.flink.cli.SqlClient", + client.toString(), FlinkDeployMode.KUBERNETES_NATIVE_APPLICATION, FlinkJobType.FLINK_SQL, + new FlinkVersion(workspace.toString()) { + + @Override + public String majorVersion() { + return "2.2"; + } + }, dependencies, "sql-job", "default", "flink:2.2.1", KubernetesPodTemplates.empty(), + hadoop, DockerConf.of("registry.example.org", "streampark", "", ""), ""); + FlinkK8sApplicationBuildPipeline pipeline = new FlinkK8sApplicationBuildPipeline(request) { + + @Override + protected void runDockerBuildSteps(String buildWorkspace, java.io.File dockerfile, + DockerConf dockerConf, String baseImageTag, String pushImageTag, + boolean checkLocalImageFirst) { + // Verify the build context without contacting a Docker daemon or registry. + assertThat(dockerfile).isFile(); + assertThat(Path.of(buildWorkspace, "lib", "snakeyaml-2.0.jar")).isRegularFile(); + assertThat(Path.of(buildWorkspace, "lib", "connector.jar")).isRegularFile(); + } + }; + DockerImageBuildResponse result = pipeline.buildProcess(); + assertThat(result.pass()).isTrue(); + assertThat(result.dockerInnerMainJarPath()) + .isEqualTo("local:///opt/flink/usrlib/streampark-flinkjob_SQL_job.jar"); + assertThat(dependencies.extJarLibs()).containsExactly(connector.toString()); + assertThat(dependencies.mavenArts()).isEmpty(); + assertThat(Files.readString(Path.of(result.workspacePath(), "Dockerfile"))) + .contains("$FLINK_HOME/lib/", "$FLINK_HOME/usrlib/streampark-flinkjob_SQL_job.jar"); + } + + private Path createJar(String name, String entry) throws Exception { + Path jar = workspace.resolve(name); + try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar))) { + output.putNextEntry(new JarEntry(entry)); + output.write(new byte[]{1}); + output.closeEntry(); + } + return jar; + } +}