Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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(
"(?<!org\\.apache\\.streampark\\.shaded\\.)"
+ "(org\\.slf4j|ch\\.qos\\.logback|org\\.apache\\.log4j)(?=\\.)");
private final LoggerContext loggerContext;

private ShadedContextInitializer(LoggerContext loggerContext) {
ShadedContextInitializer(LoggerContext loggerContext) {
super(loggerContext);
this.loggerContext = loggerContext;
}
Expand All @@ -100,15 +104,15 @@ public void configureByResource(URL url) {
if (path.endsWith("xml")) {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
try {
try (InputStream resource = url.openStream()) {
String text =
FileUtils.readFile(new File(path))
.replaceAll("org.slf4j", SHADED_PACKAGE + ".org.slf4j")
.replaceAll("ch.qos.logback", SHADED_PACKAGE + ".ch.qos.logback")
.replaceAll("org.apache.log4j", SHADED_PACKAGE + ".org.apache.log4j");
ByteArrayInputStream input =
new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
configurator.doConfigure(input);
LOGGING_PACKAGE.matcher(new String(resource.readAllBytes(), StandardCharsets.UTF_8))
.replaceAll(SHADED_PACKAGE + ".$1");
try (
ByteArrayInputStream input =
new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))) {
configurator.doConfigure(input);
}
} catch (Exception e) {
throw new LogbackException("Failed to configure logger context from " + url, e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* 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.common.util;

import org.apache.streampark.shaded.ch.qos.logback.classic.LoggerContext;
import org.apache.streampark.shaded.ch.qos.logback.core.helpers.NOPAppender;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

import static org.assertj.core.api.Assertions.assertThat;

class StreamParkLoggerFactoryTest {

@TempDir
Path workspace;

@Test
void loadConfigurationFromJarUrl() throws Exception {
Path jar = workspace.resolve("sql client.jar");
try (JarOutputStream output = new JarOutputStream(Files.newOutputStream(jar))) {
output.putNextEntry(new JarEntry("logback.xml"));
output.write(configuration("ch.qos.logback.core.helpers.NOPAppender")
.getBytes(StandardCharsets.UTF_8));
output.closeEntry();
}
verifyConfiguration(new URL("jar:" + jar.toUri().toURL() + "!/logback.xml"));
}

@Test
void loadConfigurationFromEncodedUrl() throws Exception {
Path file = workspace.resolve("logback config.xml");
Files.writeString(file, configuration("ch.qos.logback.core.helpers.NOPAppender"));
verifyConfiguration(file.toUri().toURL());
}

@Test
void preserveAlreadyShadedClassNames() throws Exception {
Path file = workspace.resolve("logback.xml");
Files.writeString(file, configuration(
"org.apache.streampark.shaded.ch.qos.logback.core.helpers.NOPAppender"));
verifyConfiguration(file.toUri().toURL());
}

private void verifyConfiguration(URL url) {
LoggerContext context = new LoggerContext();
try {
new StreamParkLoggerFactory.ShadedContextInitializer(context).configureByResource(url);
assertThat(context.getLogger("ROOT").getAppender("NOP"))
.isInstanceOf(NOPAppender.class);
} finally {
context.stop();
}
}

private String configuration(String appenderClass) {
return "<configuration><appender name=\"NOP\" class=\"" + appenderClass
+ "\"/><root level=\"INFO\"><appender-ref ref=\"NOP\"/></root></configuration>";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ private ShutdownResponse shutdownInternal(FlinkCluster flinkCluster,
flinkCluster.getId(),
getKubernetesDeploySpec(flinkCluster, "shutdown"));
Future<ShutdownResponse> 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 {
Expand All @@ -437,7 +437,13 @@ private DeployResponse deployInternal(FlinkCluster flinkCluster) throws Interrup
getKubernetesDeploySpec(flinkCluster, "start"));
log.info("Deploy cluster request {}", deployRequest);
Future<DeployResponse> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading