Unverified Commit a4210381 authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature][Flink]add read checkpoint (#2347)

* add read checkpoint * optimize sse complete * optimize sse complete * update MysqlCdcSource * update checkpoint read * update checkpoint read
parent 727ef635
...@@ -19,13 +19,16 @@ ...@@ -19,13 +19,16 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.data.model.CheckPointReadTable;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.vo.CascaderVO; import org.dinky.data.vo.CascaderVO;
import org.dinky.flink.checkpoint.CheckpointRead;
import org.dinky.utils.CascaderOptionsUtils; import org.dinky.utils.CascaderOptionsUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -39,7 +42,15 @@ import lombok.extern.slf4j.Slf4j; ...@@ -39,7 +42,15 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
@Api(tags = "Flink Conf Controller", hidden = true) @Api(tags = "Flink Conf Controller", hidden = true)
@RequestMapping("/api/flinkConf") @RequestMapping("/api/flinkConf")
public class FlinkConfController { public class FlinkController {
protected static final CheckpointRead INSTANCE = new CheckpointRead();
@GetMapping("/readCheckPoint")
@ApiOperation("Read Checkpoint")
public Result<Map<String, Map<String, CheckPointReadTable>>> readCheckPoint(String path, String operatorId) {
return Result.data(INSTANCE.readCheckpoint(path, operatorId));
}
@GetMapping("/configOptions") @GetMapping("/configOptions")
@ApiOperation("Query Flink Configuration Options") @ApiOperation("Query Flink Configuration Options")
public Result<List<CascaderVO>> loadDataByGroup() { public Result<List<CascaderVO>> loadDataByGroup() {
...@@ -71,6 +82,8 @@ public class FlinkConfController { ...@@ -71,6 +82,8 @@ public class FlinkConfController {
"org.apache.flink.configuration.MetricOptions", "org.apache.flink.configuration.MetricOptions",
"org.apache.flink.configuration.NettyShuffleEnvironmentOptions", "org.apache.flink.configuration.NettyShuffleEnvironmentOptions",
"org.apache.flink.configuration.RestartStrategyOptions", "org.apache.flink.configuration.RestartStrategyOptions",
"org.apache.flink.yarn.configuration.YarnConfigOptions",
"org.apache.flink.kubernetes.configuration.KubernetesConfigOptions",
"org.dinky.constant.CustomerConfigureOptions" "org.dinky.constant.CustomerConfigureOptions"
}; };
List<CascaderVO> dataList = new ArrayList<>(); List<CascaderVO> dataList = new ArrayList<>();
......
...@@ -92,7 +92,7 @@ public class StudioController { ...@@ -92,7 +92,7 @@ public class StudioController {
jobResult.setSuccess(false); jobResult.setSuccess(false);
jobResult.setStatement(studioExecuteDTO.getStatement()); jobResult.setStatement(studioExecuteDTO.getStatement());
jobResult.setError(ex.toString()); jobResult.setError(ex.toString());
return Result.failed(jobResult, Status.EXECUTE_FAILED); return Result.failed(jobResult, ex.toString());
} }
} }
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
package org.dinky.sse; package org.dinky.sse;
import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
...@@ -39,18 +38,16 @@ public class SseEmitterUTF8 extends SseEmitter { ...@@ -39,18 +38,16 @@ public class SseEmitterUTF8 extends SseEmitter {
@Override @Override
protected void extendResponse(ServerHttpResponse outputMessage) { protected void extendResponse(ServerHttpResponse outputMessage) {
super.extendResponse(outputMessage); super.extendResponse(outputMessage);
HttpHeaders headers = outputMessage.getHeaders(); HttpHeaders headers = outputMessage.getHeaders();
headers.setContentType(new MediaType(MediaType.TEXT_EVENT_STREAM, StandardCharsets.UTF_8)); headers.setContentType(new MediaType(MediaType.TEXT_EVENT_STREAM, StandardCharsets.UTF_8));
} }
@Override @Override
public void send(Object object, MediaType mediaType) throws IOException { public synchronized void complete() {
Boolean complete = (Boolean) ReflectUtil.getFieldValue(this, "complete"); Boolean complete = (Boolean) ReflectUtil.getFieldValue(this, "complete");
if (complete) { if (complete) {
log.warn("SseEmitter is complete, cannot send message: {}", object);
return; return;
} }
super.send(object, mediaType); super.complete();
} }
} }
/*
*
* 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.dinky.flink.checkpoint;
import org.dinky.data.model.CheckPointReadTable;
import org.apache.flink.runtime.state.ArrayListSerializer;
import org.apache.flink.runtime.state.PartitionableListState;
import java.util.Optional;
import cn.hutool.core.util.ReflectUtil;
public abstract class BaseCheckpointRead {
protected BaseCheckpointRead() {}
public abstract boolean isSourceCkp(PartitionableListState<?> partitionableListState);
public abstract Optional<CheckPointReadTable> create(PartitionableListState<?> partitionableListState);
protected static ArrayListSerializer<?> getArrayListSerializer(PartitionableListState<?> partitionableListState) {
return (ArrayListSerializer<?>) ReflectUtil.getFieldValue(partitionableListState, "internalListCopySerializer");
}
}
/*
*
* 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.dinky.flink.checkpoint;
import org.dinky.data.model.CheckPointReadTable;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.core.fs.FSDataInputStream;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.runtime.checkpoint.OperatorState;
import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
import org.apache.flink.runtime.checkpoint.StateObjectCollection;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.state.OperatorBackendSerializationProxy;
import org.apache.flink.runtime.state.OperatorStateHandle;
import org.apache.flink.runtime.state.PartitionableListState;
import org.apache.flink.runtime.state.RegisteredOperatorStateBackendMetaInfo;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot;
import org.apache.flink.state.api.ExistingSavepoint;
import org.apache.flink.state.api.Savepoint;
import org.apache.flink.state.api.runtime.metadata.SavepointMetadata;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
public class CheckpointRead implements CheckpointReadInterface {
@Override
public Map<String, Map<String, CheckPointReadTable>> readCheckpoint(String path, String operatorId) {
ClassLoader restoreClassLoader = Thread.currentThread().getContextClassLoader();
Map<String, Map<String, CheckPointReadTable>> result = new LinkedHashMap<>();
try {
ExistingSavepoint savepoint =
Savepoint.load(ExecutionEnvironment.getExecutionEnvironment(), path, new HashMapStateBackend());
List<OperatorState> operatorStateList =
((SavepointMetadata) ReflectUtil.getFieldValue(savepoint, "metadata")).getExistingOperators();
OperatorState existingOperator = operatorStateList.stream()
.filter(operatorState -> operatorState
.getOperatorID()
.equals(OperatorID.fromJobVertexID(JobVertexID.fromHexString(operatorId))))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("The corresponding operator ID was not found"));
Map<Integer, OperatorSubtaskState> subtaskStates = existingOperator.getSubtaskStates();
if (CollUtil.isNotEmpty(subtaskStates)) {
subtaskStates.forEach((k, v) -> {
StateObjectCollection<OperatorStateHandle> managedOperatorState = v.getManagedOperatorState();
Map<String, CheckPointReadTable> read = readState(restoreClassLoader, managedOperatorState);
result.put("managedOperatorState", read);
});
}
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Map<String, CheckPointReadTable> readState(
ClassLoader restoreClassLoader, StateObjectCollection<OperatorStateHandle> managedOperatorState) {
Map<String, CheckPointReadTable> map = new LinkedHashMap<>();
OperatorBackendSerializationProxy backendSerializationProxy =
new OperatorBackendSerializationProxy(restoreClassLoader);
boolean isRead = false;
for (OperatorStateHandle operatorStateHandle : managedOperatorState) {
try (FSDataInputStream in =
operatorStateHandle.getDelegateStateHandle().openInputStream()) {
if (!isRead) {
backendSerializationProxy.read(new DataInputViewStreamWrapper(in));
isRead = true;
}
operatorStateHandle.getStateNameToPartitionOffsets().forEach((key, value) -> {
try {
List<StateMetaInfoSnapshot> restoredOperatorMetaInfoSnapshots =
backendSerializationProxy.getOperatorStateMetaInfoSnapshots();
for (StateMetaInfoSnapshot stateMetaInfoSnapshot : restoredOperatorMetaInfoSnapshots) {
String name = stateMetaInfoSnapshot.getName();
if (!name.equals(key)) {
continue;
}
TypeSerializerSnapshot<?> valueSerializer = stateMetaInfoSnapshot
.getSerializerSnapshotsImmutable()
.get("VALUE_SERIALIZER");
PartitionableListState<?> partitionableListState = ReflectUtil.newInstance(
PartitionableListState.class,
new RegisteredOperatorStateBackendMetaInfo<>(stateMetaInfoSnapshot));
;
deserializeOperatorStateValues(partitionableListState, in, value);
partitionableListState.get().forEach(System.out::println);
// get checkpoint data
CheckpointReadFactory.getTable(partitionableListState)
.ifPresent(tableVO -> map.put(key, tableVO));
break;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return map;
}
protected static <S> void deserializeOperatorStateValues(
PartitionableListState<S> stateListForName,
FSDataInputStream in,
OperatorStateHandle.StateMetaInfo metaInfo)
throws IOException {
if (null != metaInfo) {
long[] offsets = metaInfo.getOffsets();
if (null != offsets) {
DataInputView div = new DataInputViewStreamWrapper(in);
TypeSerializer<S> serializer =
stateListForName.getStateMetaInfo().getPartitionStateSerializer();
for (long offset : offsets) {
in.seek(offset);
stateListForName.add(serializer.deserialize(div));
}
}
}
}
}
/*
*
* 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.dinky.flink.checkpoint;
import org.dinky.data.model.CheckPointReadTable;
import org.dinky.flink.checkpoint.base.BaseTypeCheckpointRead;
import org.dinky.flink.checkpoint.pojo.PojoTypeCheckpointRead;
import org.dinky.flink.checkpoint.source.CheckpointSourceRead;
import org.apache.flink.runtime.state.PartitionableListState;
import java.util.List;
import java.util.Optional;
import cn.hutool.core.collection.CollUtil;
public class CheckpointReadFactory {
public static final List<? extends BaseCheckpointRead> FACTORY_LIST = CollUtil.newArrayList(
new BaseTypeCheckpointRead(), new CheckpointSourceRead(), new PojoTypeCheckpointRead());
public static Optional<CheckPointReadTable> getTable(PartitionableListState<?> partitionableListState) {
Iterable<?> objects = partitionableListState.get();
boolean empty = CollUtil.isEmpty(objects);
if (empty) {
return Optional.empty();
}
for (BaseCheckpointRead baseCheckpointRead : FACTORY_LIST) {
if (baseCheckpointRead.isSourceCkp(partitionableListState)) {
return baseCheckpointRead.create(partitionableListState);
}
}
return Optional.empty();
}
}
/*
*
* 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.dinky.flink.checkpoint;
import org.dinky.data.model.CheckPointReadTable;
import java.util.Map;
public interface CheckpointReadInterface {
/**
* 读取checkpoint
* @param path Checkpoint路径
* @param operatorId 执行id
* @return stateType -> (stateName -> CheckPointReadTable)
*/
default Map<String, Map<String, CheckPointReadTable>> readCheckpoint(String path, String operatorId) {
throw new UnsupportedOperationException("readCheckpoint not implemented");
}
}
/*
*
* 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.dinky.flink.checkpoint;
import org.apache.flink.core.io.SimpleVersionedSerializer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SupportSplitSerializer {
Class<? extends SimpleVersionedSerializer<?>> clazz();
int order() default 1;
}
/*
*
* 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.dinky.flink.checkpoint.base;
import org.dinky.data.model.CheckPointReadTable;
import org.dinky.flink.checkpoint.BaseCheckpointRead;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.runtime.state.PartitionableListState;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONObject;
public class BaseTypeCheckpointRead extends BaseCheckpointRead {
public Optional<CheckPointReadTable> create(PartitionableListState<?> partitionableListState) {
List<JSONObject> data = CollUtil.newArrayList(partitionableListState.get()).stream()
.map(x -> {
JSONObject jsonObject = new JSONObject();
jsonObject.set("data", x);
return jsonObject;
})
.collect(Collectors.toList());
CheckPointReadTable tableVO = CheckPointReadTable.builder()
.datas(data)
.headers(CollUtil.newArrayList("data"))
.build();
return Optional.of(tableVO);
}
private static TypeSerializer<?> getTypeSerializer(PartitionableListState<?> partitionableListState) {
Map<Class<?>, BasicTypeInfo<?>> types = (Map<Class<?>, BasicTypeInfo<?>>)
ReflectUtil.getStaticFieldValue(ReflectUtil.getField(BasicTypeInfo.class, "TYPES"));
for (Map.Entry<Class<?>, BasicTypeInfo<?>> entry : types.entrySet()) {
TypeSerializer<?> serializer = entry.getValue().createSerializer(null);
boolean equals = getArrayListSerializer(partitionableListState)
.getElementSerializer()
.getClass()
.equals(serializer.getClass());
if (equals) {
return serializer;
}
}
return null;
}
public boolean isSourceCkp(PartitionableListState<?> partitionableListState) {
TypeSerializer<?> typeSerializer = getTypeSerializer(partitionableListState);
return typeSerializer != null;
}
}
/*
*
* 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.dinky.flink.checkpoint.pojo;
import org.dinky.data.model.CheckPointReadTable;
import org.dinky.flink.checkpoint.BaseCheckpointRead;
import org.apache.flink.api.java.typeutils.runtime.PojoSerializer;
import org.apache.flink.runtime.state.PartitionableListState;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONObject;
public class PojoTypeCheckpointRead extends BaseCheckpointRead {
public static final Class<?> SERIALIZER_CLASS = PojoSerializer.class;
public Optional<CheckPointReadTable> create(PartitionableListState<?> partitionableListState) {
PojoSerializer<?> typeSerializer = (PojoSerializer<?>)
getArrayListSerializer(partitionableListState).getElementSerializer();
Field[] fields = (Field[]) ReflectUtil.getFieldValue(typeSerializer, "fields");
List<String> headers =
Arrays.stream(fields).map(ReflectUtil::getFieldName).collect(Collectors.toList());
List<JSONObject> data = CollUtil.newArrayList(partitionableListState.get()).stream()
.map(JSONObject::new)
.collect(Collectors.toList());
CheckPointReadTable tableVO =
CheckPointReadTable.builder().headers(headers).datas(data).build();
return Optional.of(tableVO);
}
public boolean isSourceCkp(PartitionableListState<?> partitionableListState) {
return getArrayListSerializer(partitionableListState)
.getElementSerializer()
.getClass()
.equals(SERIALIZER_CLASS);
}
}
/*
*
* 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.dinky.flink.checkpoint.source;
import org.apache.flink.api.connector.source.SourceSplit;
import java.util.List;
public abstract class BaseCheckpointSource<T extends SourceSplit> implements CheckpointSource {
public final List<T> splits;
public BaseCheckpointSource(List<T> splits) {
this.splits = splits;
}
}
/*
*
* 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.dinky.flink.checkpoint.source;
import java.util.List;
public interface CheckpointSource {
List<String> headers();
List<?> datas();
}
/*
*
* 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.dinky.flink.checkpoint.source;
import org.dinky.data.model.CheckPointReadTable;
import org.dinky.flink.checkpoint.BaseCheckpointRead;
import org.dinky.flink.checkpoint.SupportSplitSerializer;
import org.apache.flink.api.common.typeutils.base.array.BytePrimitiveArraySerializer;
import org.apache.flink.core.io.SimpleVersionedSerializer;
import org.apache.flink.runtime.state.PartitionableListState;
import org.apache.flink.streaming.api.operators.util.SimpleVersionedListState;
import org.apache.flink.util.CollectionUtil;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
public class CheckpointSourceRead extends BaseCheckpointRead {
public static final String STATE_NAME = "SourceReaderState";
public static final Class<?> SERIALIZER_CLASS = BytePrimitiveArraySerializer.class;
private static final Map<
Supplier<Class<? extends SimpleVersionedSerializer<?>>>,
Function<List, ? extends BaseCheckpointSource<?>>>
MAPPING = new LinkedHashMap<>();
static {
ClassUtil.scanPackageBySuper("org.dinky.flink.checkpoint.source", BaseCheckpointSource.class).stream()
.filter(x -> x.getAnnotation(SupportSplitSerializer.class) != null)
.sorted((x, y) -> {
SupportSplitSerializer x1 = x.getAnnotation(SupportSplitSerializer.class);
SupportSplitSerializer y1 = y.getAnnotation(SupportSplitSerializer.class);
return x1.order() - y1.order();
})
.forEach(x -> {
SupportSplitSerializer supportSplitSerializer = x.getAnnotation(SupportSplitSerializer.class);
if (supportSplitSerializer != null) {
MAPPING.put(supportSplitSerializer::clazz, d ->
(BaseCheckpointSource<?>) ReflectUtil.newInstance(x, d));
}
});
}
public Optional<CheckPointReadTable> create(PartitionableListState<?> partitionableListState) {
for (Map.Entry<
Supplier<Class<? extends SimpleVersionedSerializer<?>>>,
Function<List, ? extends BaseCheckpointSource<?>>>
entry : MAPPING.entrySet()) {
try {
List list = CollectionUtil.iterableToList(new SimpleVersionedListState(
partitionableListState,
Singleton.get(entry.getKey().get()))
.get());
BaseCheckpointSource apply = entry.getValue().apply(list);
return Optional.of(new CheckPointReadTable(apply.headers(), apply.datas()));
} catch (Exception e) {
e.printStackTrace();
} catch (NoClassDefFoundError ignored) {
}
}
return Optional.empty();
}
public boolean isSourceCkp(PartitionableListState<?> partitionableListState) {
return partitionableListState.getStateMetaInfo().getName().equals(STATE_NAME)
&& getArrayListSerializer(partitionableListState)
.getElementSerializer()
.getClass()
.equals(SERIALIZER_CLASS);
}
}
/*
*
* 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.dinky.flink.checkpoint.source;
import org.dinky.flink.checkpoint.SupportSplitSerializer;
import org.apache.flink.connector.kafka.source.split.KafkaPartitionSplit;
import org.apache.flink.connector.kafka.source.split.KafkaPartitionSplitSerializer;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
@SupportSplitSerializer(clazz = KafkaPartitionSplitSerializer.class)
public class KafkaSource extends BaseCheckpointSource<KafkaPartitionSplit> {
public KafkaSource(List<KafkaPartitionSplit> splits) {
super(splits);
}
public List<String> headers() {
return CollUtil.newArrayList("partition", "starting-offset", "stopping-offset");
}
public List<?> datas() {
return splits.stream()
.map(d -> {
JSONObject jsonObject = new JSONObject();
jsonObject.set("partition", d.getTopicPartition().toString());
jsonObject.set("starting-offset", d.getStartingOffset());
jsonObject.set(
"stopping-offset", d.getStoppingOffset().orElse(KafkaPartitionSplit.NO_STOPPING_OFFSET));
return jsonObject;
})
.collect(Collectors.toList());
}
}
/*
*
* 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.dinky.flink.checkpoint.source;
import org.dinky.flink.checkpoint.SupportSplitSerializer;
import java.util.List;
import java.util.stream.Collectors;
import com.ververica.cdc.connectors.mysql.source.split.MySqlBinlogSplit;
import com.ververica.cdc.connectors.mysql.source.split.MySqlSnapshotSplit;
import com.ververica.cdc.connectors.mysql.source.split.MySqlSplit;
import com.ververica.cdc.connectors.mysql.source.split.MySqlSplitSerializer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
@SupportSplitSerializer(clazz = MySqlSplitSerializer.class, order = -1)
public class MysqlCdcSource extends BaseCheckpointSource<MySqlSplit> {
/**
* MySqlSnapshotSplit{tableId=cdc-test.user, splitId='cdc-test.user:28', splitKeyType=[`id` INT NOT NULL], splitStart=[227165], splitEnd=[235278], highWatermark=null}
*/
public MysqlCdcSource(List<MySqlSplit> splits) {
super(splits);
}
public List<String> headers() {
MySqlSplit mySqlSplit = splits.get(0);
if (mySqlSplit.isBinlogSplit()) {
return CollUtil.newArrayList(
"split-id", "starting-offset", "ending-offset", "table-schemas", "finished-snapshot-split-infos");
} else if (mySqlSplit.isSnapshotSplit()) {
return CollUtil.newArrayList(
"table-id", "split-id", "split-key-type", "split-start", "split-end", "high-watermark");
}
return null;
}
public List<?> datas() {
return splits.stream()
.map(d -> {
JSONObject jsonObject = new JSONObject();
if (d.isBinlogSplit()) {
MySqlBinlogSplit split = d.asBinlogSplit();
jsonObject.set("split-id", split.splitId());
jsonObject.set(
"starting-offset", split.getStartingOffset().toString());
jsonObject.set(
"ending-offset-id", split.getEndingOffset().toString());
String tableSchemas = split.getTableSchemas().entrySet().stream()
.map(e -> {
JSONObject tableSchema = new JSONObject();
tableSchema.set("table-id", e.getKey().identifier());
tableSchema.set("table-schema", e.getValue().toString());
return tableSchema;
})
.collect(Collectors.toCollection(JSONArray::new))
.toString();
jsonObject.set("table-schemas", tableSchemas);
jsonObject.set(
"finished-snapshot-split-infos",
JSONUtil.toJsonPrettyStr(split.getFinishedSnapshotSplitInfos()));
} else if (d.isSnapshotSplit()) {
MySqlSnapshotSplit split = d.asSnapshotSplit();
jsonObject.set("table-id", split.getTableId());
jsonObject.set("split-id", split.splitId());
jsonObject.set("split-key-type", split.getSplitKeyType());
jsonObject.set("split-start", split.getSplitStart());
jsonObject.set("split-end", split.getSplitEnd());
jsonObject.set("high-watermark", split.getHighWatermark());
}
return jsonObject;
})
.collect(Collectors.toList());
}
}
/*
*
* 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.dinky.data.model;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
@AllArgsConstructor
public class CheckPointReadTable {
private List<String> headers;
private List<?> datas;
}
...@@ -325,7 +325,7 @@ public class JobManager { ...@@ -325,7 +325,7 @@ public class JobManager {
currentSql = item.getValue(); currentSql = item.getValue();
executor.executeSql(item.getValue()); executor.executeSql(item.getValue());
} }
if (jobParam.getTrans().size() > 0) { if (!jobParam.getTrans().isEmpty()) {
// Use statement set or gateway only submit inserts. // Use statement set or gateway only submit inserts.
if (useStatementSet && useGateway) { if (useStatementSet && useGateway) {
List<String> inserts = new ArrayList<>(); List<String> inserts = new ArrayList<>();
...@@ -355,7 +355,7 @@ public class JobManager { ...@@ -355,7 +355,7 @@ public class JobManager {
inserts.add(item.getValue()); inserts.add(item.getValue());
} }
} }
if (inserts.size() > 0) { if (!inserts.isEmpty()) {
currentSql = String.join(sqlSeparator, inserts); currentSql = String.join(sqlSeparator, inserts);
// Remote mode can get the table result. // Remote mode can get the table result.
TableResult tableResult = executor.executeStatementSet(inserts); TableResult tableResult = executor.executeStatementSet(inserts);
...@@ -449,7 +449,7 @@ public class JobManager { ...@@ -449,7 +449,7 @@ public class JobManager {
} }
} }
} }
if (jobParam.getExecute().size() > 0) { if (!jobParam.getExecute().isEmpty()) {
if (useGateway) { if (useGateway) {
for (StatementParam item : jobParam.getExecute()) { for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue()); executor.executeSql(item.getValue());
......
...@@ -52,11 +52,15 @@ public class AddJarSqlParser { ...@@ -52,11 +52,15 @@ public class AddJarSqlParser {
.map(x -> ReUtil.findAll(ADD_JAR_PATTERN, x, 2).get(0)) .map(x -> ReUtil.findAll(ADD_JAR_PATTERN, x, 2).get(0))
.distinct() .distinct()
.forEach(urlPath -> { .forEach(urlPath -> {
File file = URLUtils.toFile(urlPath); try {
if (file == null || !file.exists()) { File file = URLUtils.toFile(urlPath);
throw new DinkyException(StrUtil.format("file : {} not exists!", urlPath)); if (file == null || !file.exists()) {
throw new DinkyException(StrUtil.format("file : {} not exists!", urlPath));
}
fileSet.add(file);
} catch (Exception e) {
throw new DinkyException(StrUtil.format("url:{} request failed!", urlPath), e);
} }
fileSet.add(file);
}); });
return fileSet; return fileSet;
} }
......
...@@ -169,5 +169,10 @@ ...@@ -169,5 +169,10 @@
<artifactId>flink-runtime-web_${scala.binary.version}</artifactId> <artifactId>flink-runtime-web_${scala.binary.version}</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-state-processor-api_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -193,5 +193,10 @@ ...@@ -193,5 +193,10 @@
<artifactId>flink-runtime-web_${scala.binary.version}</artifactId> <artifactId>flink-runtime-web_${scala.binary.version}</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-state-processor-api_${scala.binary.version}</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -192,6 +192,11 @@ ...@@ -192,6 +192,11 @@
<artifactId>flink-runtime-web</artifactId> <artifactId>flink-runtime-web</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-state-processor-api</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -144,6 +144,11 @@ ...@@ -144,6 +144,11 @@
<artifactId>flink-runtime-web</artifactId> <artifactId>flink-runtime-web</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-state-processor-api</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies> </dependencies>
<repositories> <repositories>
......
...@@ -137,5 +137,10 @@ ...@@ -137,5 +137,10 @@
<artifactId>flink-runtime-web</artifactId> <artifactId>flink-runtime-web</artifactId>
<version>${flink.version}</version> <version>${flink.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-state-processor-api</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -20,53 +20,74 @@ ...@@ -20,53 +20,74 @@
import DagDataNode from '@/components/FlinkDag/component/DagDataNode'; import DagDataNode from '@/components/FlinkDag/component/DagDataNode';
import DagPlanNode from '@/components/FlinkDag/component/DagPlanNode'; import DagPlanNode from '@/components/FlinkDag/component/DagPlanNode';
import { import {
edgeConfig, edgeConfig,
graphConfig, graphConfig,
layoutConfig, layoutConfig,
portConfig, portConfig,
zoomOptions zoomOptions
} from '@/components/FlinkDag/config'; } from '@/components/FlinkDag/config';
import { buildDag, regConnect, updateDag } from '@/components/FlinkDag/functions'; import {buildDag, regConnect, updateDag} from '@/components/FlinkDag/functions';
import { Jobs } from '@/types/DevOps/data'; import {Jobs} from '@/types/DevOps/data';
import { DagreLayout } from '@antv/layout'; import {DagreLayout} from '@antv/layout';
import { Edge, Graph } from '@antv/x6'; import {Edge, Graph} from '@antv/x6';
import { Selection } from '@antv/x6-plugin-selection'; import {Selection} from '@antv/x6-plugin-selection';
import { register } from '@antv/x6-react-shape'; import {register} from '@antv/x6-react-shape';
import { Drawer } from 'antd'; import {Drawer, Select, Slider, Table, Tabs, TabsProps, Typography} from 'antd';
import { useEffect, useRef, useState } from 'react'; import {useEffect, useRef, useState} from 'react';
import './index.css'; import './index.css';
import {getData} from "@/services/api";
import {API_CONSTANTS} from "@/services/endpoints";
import {Rectangle} from "@antv/x6-geometry";
import {Options as GraphOptions} from "@antv/x6/src/graph/options";
import path from "path";
export type DagProps = { export type DagProps = {
job: Jobs.Job; job: Jobs.Job;
onlyPlan?: boolean; onlyPlan?: boolean;
checkPoints?: any;
}; };
const {Paragraph} = Typography;
const FlinkDag = (props: DagProps) => { const FlinkDag = (props: DagProps) => {
const container = useRef(null); const container = useRef(null);
const { job, onlyPlan = false } = props; const {job, onlyPlan = false, checkPoints = {}} = props;
const [graph, setGraph] = useState<Graph>(); const [graph, setGraph] = useState<Graph>();
const [currentJob, setCurrentJob] = useState<string>(); const [currentJob, setCurrentJob] = useState<string>();
const [currentSelect, setCurrentSelect] = useState<any>(); const [currentSelect, setCurrentSelect] = useState<any>();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [zoom, setZoom] = useState<number>(1);
const handleClose = () => { let originPosition = {
setOpen(false); zoom: 1
setCurrentSelect(undefined); };
graph?.zoomToFit(zoomOptions);
graph?.centerContent(); const handleClose = () => {
}; setOpen(false);
setCurrentSelect(undefined);
const initListen = (graph: Graph) => { graph?.zoomToFit(zoomOptions);
graph.on('node:selected', ({ cell }) => { graph?.centerContent();
setOpen(true); };
setCurrentSelect(cell);
graph.positionCell(cell, 'center'); const initListen = (graph: Graph) => {
}); graph.on('node:selected', ({cell}) => {
if (!onlyPlan) {
graph.on('node:unselected', ({ cell }) => handleClose()); setOpen(true);
}; setZoom(oldValue => {
originPosition = {zoom: oldValue}
return 1;
})
graph.zoomTo(1)
setCurrentSelect(cell);
graph.positionPoint(Rectangle.create(cell.getBBox()).getLeftMiddle(), '10%', '50%');
}
});
graph.on('node:unselected', ({cell}) => {
setZoom(originPosition.zoom)
handleClose();
});
};
const initGraph = (flinkData: any) => { const initGraph = (flinkData: any) => {
register({ register({
...@@ -77,69 +98,156 @@ const FlinkDag = (props: DagProps) => { ...@@ -77,69 +98,156 @@ const FlinkDag = (props: DagProps) => {
ports: portConfig ports: portConfig
}); });
Edge.config(edgeConfig); Edge.config(edgeConfig);
Graph.registerConnector('curveConnector', regConnect, true); Graph.registerConnector('curveConnector', regConnect, true);
Graph.registerEdge('data-processing-curve', Edge, true); Graph.registerEdge('data-processing-curve', Edge, true);
const graph: Graph = new Graph({ const graph: Graph = new Graph({
// @ts-ignore // @ts-ignore
container: container.current, container: container.current,
...graphConfig ...graphConfig
}); });
graph.use( graph.use(
new Selection({ new Selection({
enabled: true, enabled: true,
multiple: false, multiple: false,
rubberband: false, rubberband: false,
showNodeSelectionBox: true showNodeSelectionBox: true
}) })
); );
// Adaptive layout // Adaptive layout
const model = new DagreLayout(layoutConfig).layout(flinkData); const model = new DagreLayout(layoutConfig).layout(flinkData);
graph.fromJSON(model); graph.fromJSON(model);
// Automatically zoom to fit // Automatically zoom to fit
graph.zoomToFit(zoomOptions); graph.zoomToFit(zoomOptions);
graph.centerContent(); graph.on('scale', ({sx}) => setZoom(sx));
updateDag(job?.vertices, graph); graph.centerContent();
initListen(graph); graph?.zoomTo(zoom)
return graph; updateDag(job?.vertices, graph);
}; initListen(graph);
return graph;
useEffect(() => { };
const flinkData = buildDag(job?.plan);
// Clean up old data useEffect(() => {
if (graph) { const flinkData = buildDag(job?.plan);
graph.clearCells(); // Clean up old data
if (graph) {
graph.clearCells();
}
setGraph(initGraph(flinkData));
setZoom(1 / flinkData.nodes.length + 0.5)
}, [currentJob]);
useEffect(() => {
updateDag(job?.vertices, graph);
if (currentJob != job?.jid) {
setCurrentJob(job?.jid);
}
}, [job]);
useEffect(() => {
graph?.zoomTo(zoom)
}, [zoom]);
const renderCheckpoint = (id: string) => {
const [selectPath, setSelectPath] = useState<string>('');
const key = id + selectPath;
const [itemChildren, setItemChildren] = useState({[key]: [] as TabsProps['items']});
const checkpointArray = (checkPoints.history as any[]).filter(x => x.status === "COMPLETED").map(x => {
return {checkpointType: x.checkpoint_type, path: x.external_path, id: x.id}
});
useEffect(() => {
if (selectPath && id) {
if (!itemChildren[key]) {
getData(API_CONSTANTS.READ_CHECKPOINT, {path: selectPath, operatorId: id}).then(res => {
const genData = Object.keys(res.datas).map(x => {
const datum = res.datas[x];
return {
key: x,
label: x,
children:
<Tabs items={
Object.keys(datum).map(y => {
return {
key: y,
label: y,
children: <Table dataSource={datum[y].datas}
columns={(datum[y].headers as string[]).map(z => {
return {
title: z,
dataIndex: z,
key: z,
render: (text) => <Paragraph copyable
ellipsis={{rows: 3}}>{text}</Paragraph>,
}
})}/>
}
})
} tabBarStyle={{marginBlock: 0}} tabBarGutter={10}/>
}
})
setItemChildren({...itemChildren, [key]: genData})
})
}
}
}, [selectPath, id])
return <>
<Select
defaultValue={selectPath}
style={{width: "100%"}}
placeholder="Select a person"
optionFilterProp="children"
options={
checkpointArray.map(x => {
return {label: x.id, value: x.path}
})
}
onChange={path => {
setSelectPath(path)
}}
/>
<Tabs items={itemChildren[key]} tabBarStyle={{marginBlock: 0}} tabBarGutter={10}/>
</>
} }
setGraph(initGraph(flinkData)); return (
}, [currentJob]); <span>
<div style={{height: 200, position: "absolute", top: "50%", right: 12, marginTop: -100, zIndex: 2}}>
useEffect(() => { <Slider vertical value={zoom} min={0.5} max={1.5} tooltip={{open: false}} step={0.01}
updateDag(job?.vertices, graph); onChange={setZoom}/>
if (currentJob != job?.jid) { </div>
setCurrentJob(job?.jid); <div style={{height: '100%', width: '100%'}} ref={container}/>
} <Drawer
}, [job]); headerStyle={{paddingBlock: 5}}
bodyStyle={{paddingBlock: 5}}
return ( open={open}
<> getContainer={false}
<div style={{ height: '100%', width: '100%' }} ref={container} /> width={'65%'}
<Drawer mask={false}
title={currentSelect?.data?.id} onClose={handleClose}
open={open} destroyOnClose={true}
getContainer={false} closable={false}
width={'35%'} >
mask={false} {onlyPlan ? <></> : <Tabs defaultActiveKey="1" items={[
onClose={() => handleClose()} {
destroyOnClose={true} key: '1',
> label: 'Detail',
<p>{currentSelect?.getData().description}</p> children: <p>{currentSelect?.getData().description}</p>,
</Drawer> },
</> {
); key: '2',
label: 'CheckPoint Read',
children: renderCheckpoint(currentSelect?.id),
},
]} tabBarGutter={10}/>}
</Drawer>
</span>
);
}; };
export default FlinkDag; export default FlinkDag;
...@@ -36,7 +36,7 @@ const JobConfigTab = (props: JobProps) => { ...@@ -36,7 +36,7 @@ const JobConfigTab = (props: JobProps) => {
height: '40vh' height: '40vh'
}} }}
> >
{job ? <FlinkDag job={job} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />} {job ? <FlinkDag job={job} checkPoints={jobDetail.jobDataDto.checkpoints} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
</ProCard> </ProCard>
<FlinkTable jobDetail={jobDetail} /> <FlinkTable jobDetail={jobDetail} />
......
...@@ -76,7 +76,7 @@ const JobDetail = (props: any) => { ...@@ -76,7 +76,7 @@ const JobDetail = (props: any) => {
useRequest( useRequest(
{ {
url: API_CONSTANTS.REFESH_JOB_DETAIL, url: API_CONSTANTS.REFRESH_JOB_DETAIL,
params: { id: id } params: { id: id }
}, },
{ {
......
...@@ -17,290 +17,290 @@ ...@@ -17,290 +17,290 @@
* *
*/ */
import { ChartData, JobMetrics, MetricsLayout, SubTask, Task } from '@/pages/Metrics/Job/data'; import {ChartData, JobMetrics, MetricsLayout, SubTask, Task} from '@/pages/Metrics/Job/data';
import { import {
buildMetricsList, buildMetricsList,
buildRunningJobList, buildRunningJobList,
buildSubTaskList buildSubTaskList
} from '@/pages/Metrics/Job/function'; } from '@/pages/Metrics/Job/function';
import { getFlinkRunTask, saveFlinkMetrics } from '@/pages/Metrics/Job/service'; import {getFlinkRunTask, saveFlinkMetrics} from '@/pages/Metrics/Job/service';
import { getData } from '@/services/api'; import {getData} from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints'; import {API_CONSTANTS} from '@/services/endpoints';
import { l } from '@/utils/intl'; import {l} from '@/utils/intl';
import { ProCard, ProFormSelect } from '@ant-design/pro-components'; import {ProCard, ProFormSelect} from '@ant-design/pro-components';
import { Button, Input, Row } from 'antd'; import {Button, Input, Row} from 'antd';
import { useEffect, useState } from 'react'; import {useEffect, useState} from 'react';
import FlinkChart from '../../../components/FlinkChart'; import FlinkChart from '../../../components/FlinkChart';
const getJobMetrics = async (job: JobMetrics) => { const getJobMetrics = async (job: JobMetrics) => {
const url = const url =
API_CONSTANTS.FLINK_PROXY + API_CONSTANTS.FLINK_PROXY +
'/' + '/' +
job.url + job.url +
'/jobs/' + '/jobs/' +
job.flinkJobId + job.flinkJobId +
'/vertices/' + '/vertices/' +
job.subTaskId + job.subTaskId +
'/metrics' + '/metrics' +
'?get=' + '?get=' +
encodeURIComponent(job.metrics); encodeURIComponent(job.metrics);
const json = await getData(url); const json = await getData(url);
json[0].time = new Date(); json[0].time = new Date();
return json[0] as ChartData; return json[0] as ChartData;
}; };
const Job = () => { const Job = () => {
const [metricsData, setMetricsData] = useState({ const [metricsData, setMetricsData] = useState({
url: '', url: '',
jid: '', jid: '',
flinkName: '', flinkName: '',
selectTaskId: 0, selectTaskId: 0,
selectSubTask: '', selectSubTask: '',
selectMetrics: [] as string[] selectMetrics: [] as string[]
}); });
const [subTaskList, setSubTaskList] = useState<SubTask[]>([]); const [subTaskList, setSubTaskList] = useState<SubTask[]>([]);
const [metrics, setMetrics] = useState<string[]>([]); const [metrics, setMetrics] = useState<string[]>([]);
const [taskData, setTaskData] = useState<Task[]>([]); const [taskData, setTaskData] = useState<Task[]>([]);
const [jobMetricsList, setJobMetricsList] = useState<JobMetrics[]>([]); const [jobMetricsList, setJobMetricsList] = useState<JobMetrics[]>([]);
const [chartData, setChartData] = useState<Record<string, ChartData[]>>({}); const [chartData, setChartData] = useState<Record<string, ChartData[]>>({});
const [layoutName, setLayoutName] = useState<string>(''); const [layoutName, setLayoutName] = useState<string>('');
const [timers, setTimers] = useState<Record<string, NodeJS.Timer>>({}); const [timers, setTimers] = useState<Record<string, NodeJS.Timer>>({});
useEffect(() => { useEffect(() => {
getFlinkRunTask().then((res) => { getFlinkRunTask().then((res) => {
setTaskData(res.data); setTaskData(res.data);
}); });
}, []); }, []);
useEffect(() => { useEffect(() => {
Object.keys(timers) Object.keys(timers)
.filter((x) => !jobMetricsList.map((x) => x.metrics).includes(x)) .filter((x) => !jobMetricsList.map((x) => x.metrics).includes(x))
// @ts-ignore // @ts-ignore
.forEach((x) => clearInterval(timers[x])); .forEach((x) => clearInterval(timers[x]));
}, [jobMetricsList]); }, [jobMetricsList]);
/** /**
* query flink job detail * query flink job detail
* @param {number} id * @param {number} id
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
const getFlinkTaskDetail = async (id: number) => { const getFlinkTaskDetail = async (id: number) => {
return await getData(API_CONSTANTS.REFESH_JOB_DETAIL, { id: id }); return await getData(API_CONSTANTS.REFRESH_JOB_DETAIL, {id: id});
}; };
/** /**
* query flink job sub task * query flink job sub task
* @param {string} url * @param {string} url
* @param {string} jid * @param {string} jid
* @returns {Promise<[]>} * @returns {Promise<[]>}
*/ */
const getFlinkJobSubTask = async (url: string, jid: string) => { const getFlinkJobSubTask = async (url: string, jid: string) => {
const flinkJobVertices = await getData(API_CONSTANTS.FLINK_PROXY + '/' + url + '/jobs/' + jid); const flinkJobVertices = await getData(API_CONSTANTS.FLINK_PROXY + '/' + url + '/jobs/' + jid);
return flinkJobVertices.vertices as SubTask[]; return flinkJobVertices.vertices as SubTask[];
}; };
/** /**
* query flink job metrics list * query flink job metrics list
* @param {string} url * @param {string} url
* @param {string} jid * @param {string} jid
* @param subTask * @param subTask
* @returns {Promise<string[]>} * @returns {Promise<string[]>}
*/ */
const getFlinkJobMetrics = async (url: string, jid: string, subTask: string) => { const getFlinkJobMetrics = async (url: string, jid: string, subTask: string) => {
const flinkJobMetrics = await getData( const flinkJobMetrics = await getData(
API_CONSTANTS.FLINK_PROXY + '/' + url + '/jobs/' + jid + '/vertices/' + subTask + '/metrics' API_CONSTANTS.FLINK_PROXY + '/' + url + '/jobs/' + jid + '/vertices/' + subTask + '/metrics'
); );
return (flinkJobMetrics as any[]).map((x) => x.id as string); return (flinkJobMetrics as any[]).map((x) => x.id as string);
}; };
/** /**
* 1 level , change running job * 1 level , change running job
* @returns {Promise<void>} * @returns {Promise<void>}
* @param taskId * @param taskId
*/ */
const handleRunningJobChange = async (taskId: number) => { const handleRunningJobChange = async (taskId: number) => {
// query data of flink running job // query data of flink running job
const taskDetail = await getFlinkTaskDetail(taskId); const taskDetail = await getFlinkTaskDetail(taskId);
// 解构出 flink job url , job name , job id // 解构出 flink job url , job name , job id
const { const {
cluster: { hosts: url }, cluster: {hosts: url},
instance: { name: flinkJobName, jid: flinkJobId } instance: {name: flinkJobName, jid: flinkJobId}
} = taskDetail.datas; } = taskDetail.datas;
setMetricsData((prevState) => ({ setMetricsData((prevState) => ({
...prevState, ...prevState,
url: url, url: url,
flinkName: flinkJobName, flinkName: flinkJobName,
jid: flinkJobId, jid: flinkJobId,
selectTaskId: taskId selectTaskId: taskId
})); }));
const subTasks = await getFlinkJobSubTask(url, flinkJobId); const subTasks = await getFlinkJobSubTask(url, flinkJobId);
setSubTaskList(subTasks); setSubTaskList(subTasks);
}; };
/** /**
* 2 level , change subtask * 2 level , change subtask
* @returns {Promise<void>} * @returns {Promise<void>}
* @param subTaskName * @param subTaskName
*/ */
const handleSubTaskChange = async (subTaskName: string) => { const handleSubTaskChange = async (subTaskName: string) => {
setMetricsData((prevState) => ({ setMetricsData((prevState) => ({
...prevState, ...prevState,
selectSubTask: subTaskName selectSubTask: subTaskName
})); }));
const jobMetricsDataList = await getFlinkJobMetrics( const jobMetricsDataList = await getFlinkJobMetrics(
metricsData.url, metricsData.url,
metricsData.jid, metricsData.jid,
subTaskName subTaskName
); );
setMetrics(jobMetricsDataList.sort()); setMetrics(jobMetricsDataList.sort());
}; };
/** /**
* 3 level , change metrics list * 3 level , change metrics list
* @returns {Promise<void>} * @returns {Promise<void>}
* @param selectList * @param selectList
*/ */
const handleMetricsChange = async (selectList: string[]) => { const handleMetricsChange = async (selectList: string[]) => {
setMetricsData((prevState) => ({ setMetricsData((prevState) => ({
...prevState, ...prevState,
selectMetrics: selectList selectMetrics: selectList
})); }));
const d: JobMetrics[] = selectList.map((item) => { const d: JobMetrics[] = selectList.map((item) => {
return { return {
taskId: metricsData.selectTaskId, taskId: metricsData.selectTaskId,
url: metricsData.url, url: metricsData.url,
flinkJobId: metricsData.jid, flinkJobId: metricsData.jid,
jobName: metricsData.flinkName, jobName: metricsData.flinkName,
subTaskId: metricsData.selectSubTask, subTaskId: metricsData.selectSubTask,
metrics: item, metrics: item,
layoutName: layoutName, layoutName: layoutName,
title: item, title: item,
showSize: '25%', showSize: '25%',
showType: 'Chart' showType: 'Chart'
}; };
});
d.forEach((j) => {
const data: ChartData[] = [];
chartData[j.taskId + j.subTaskId + j.metrics] = data;
setChartData(chartData);
timers[j.metrics] = setInterval(() => {
getJobMetrics(j).then((res) => {
data.push(res);
}); });
}, 1000); d.forEach((j) => {
setTimers(timers); const data: ChartData[] = [];
}); chartData[j.taskId + j.subTaskId + j.metrics] = data;
setJobMetricsList(d); setChartData(chartData);
}; timers[j.metrics] = setInterval(() => {
/** getJobMetrics(j).then((res) => {
* render metrics card list data.push(res);
* @param {JobMetrics[]} metricsList });
* @returns {JSX.Element} }, 1000);
*/ setTimers(timers);
const renderMetricsCardList = (metricsList: JobMetrics[]) => { });
setJobMetricsList(d);
};
/**
* render metrics card list
* @param {JobMetrics[]} metricsList
* @returns {JSX.Element}
*/
const renderMetricsCardList = (metricsList: JobMetrics[]) => {
return (
<>
<Row gutter={[8, 16]}>
{metricsList.map((j) => {
return (
<FlinkChart
key={j.taskId + j.subTaskId + j.metrics}
chartSize={j.showSize}
chartType={j.showType}
onChangeJobState={(chartSize, chartType) => {
j.showSize = chartSize;
j.showType = chartType;
}}
data={chartData[j.taskId + j.subTaskId + j.metrics]}
title={j.metrics}
extraType={'size'}
/>
);
})}
</Row>
</>
);
};
return ( return (
<> <>
<Row gutter={[8, 16]}> <ProCard
{metricsList.map((j) => { ghost
return ( hoverable
<FlinkChart bordered
key={j.taskId + j.subTaskId + j.metrics} headerBordered
chartSize={j.showSize} gutter={[0, 8]}
chartType={j.showType} title={
onChangeJobState={(chartSize, chartType) => { <Input
j.showSize = chartSize; placeholder='Flink Job Metrics'
j.showType = chartType; onChange={(e) => setLayoutName(e.target.value)}
}} style={{width: '100vh'}}
data={chartData[j.taskId + j.subTaskId + j.metrics]} />
title={j.metrics} }
extraType={'size'} extra={
/> <Button
); size='small'
})} onClick={() => {
</Row> const saveThisLayout = () => {
</> const metricsLayouts: MetricsLayout[] = jobMetricsList.map((job, index) => {
return {
layoutName: layoutName,
position: index,
metrics: job.metrics,
showSize: job.showSize,
showType: job.showType,
taskId: job.taskId,
vertices: job.subTaskId,
title: job.metrics
} as MetricsLayout;
});
saveFlinkMetrics(metricsLayouts).then((res) => {
if (res.success) {
setSubTaskList([]);
setMetrics([]);
setJobMetricsList([]);
}
});
};
saveThisLayout();
}}
>
{l('button.submit')}
</Button>
}
>
<ProFormSelect
name='job'
label={l('metrics.flink.job.name')}
placeholder={l('metrics.flink.job.placeholder')}
options={buildRunningJobList(taskData)}
fieldProps={{onChange: (value) => handleRunningJobChange(value as number)}}
/>
{metricsData.selectTaskId !== 0 && (
<ProFormSelect
name='vertices'
label={l('metrics.flink.subTask')}
placeholder={l('metrics.flink.subTask.placeholder')}
options={buildSubTaskList(subTaskList)}
fieldProps={{onChange: (value) => handleSubTaskChange(value as string)}}
/>
)}
{metricsData.selectSubTask !== '' && (
<ProFormSelect
name='metrics'
label={l('metrics.flink.metrics.name')}
placeholder={l('metrics.flink.metrics.placeholder')}
options={buildMetricsList(metrics)}
mode='multiple'
fieldProps={{onChange: (value) => handleMetricsChange(value as string[])}}
/>
)}
{/* render metrics list */}
{jobMetricsList.length > 0 && renderMetricsCardList(jobMetricsList)}
</ProCard>
</>
); );
};
return (
<>
<ProCard
ghost
hoverable
bordered
headerBordered
gutter={[0, 8]}
title={
<Input
placeholder='Flink Job Metrics'
onChange={(e) => setLayoutName(e.target.value)}
style={{ width: '100vh' }}
/>
}
extra={
<Button
size='small'
onClick={() => {
const saveThisLayout = () => {
const metricsLayouts: MetricsLayout[] = jobMetricsList.map((job, index) => {
return {
layoutName: layoutName,
position: index,
metrics: job.metrics,
showSize: job.showSize,
showType: job.showType,
taskId: job.taskId,
vertices: job.subTaskId,
title: job.metrics
} as MetricsLayout;
});
saveFlinkMetrics(metricsLayouts).then((res) => {
if (res.success) {
setSubTaskList([]);
setMetrics([]);
setJobMetricsList([]);
}
});
};
saveThisLayout();
}}
>
{l('button.submit')}
</Button>
}
>
<ProFormSelect
name='job'
label={l('metrics.flink.job.name')}
placeholder={l('metrics.flink.job.placeholder')}
options={buildRunningJobList(taskData)}
fieldProps={{ onChange: (value) => handleRunningJobChange(value as number) }}
/>
{metricsData.selectTaskId !== 0 && (
<ProFormSelect
name='vertices'
label={l('metrics.flink.subTask')}
placeholder={l('metrics.flink.subTask.placeholder')}
options={buildSubTaskList(subTaskList)}
fieldProps={{ onChange: (value) => handleSubTaskChange(value as string) }}
/>
)}
{metricsData.selectSubTask !== '' && (
<ProFormSelect
name='metrics'
label={l('metrics.flink.metrics.name')}
placeholder={l('metrics.flink.metrics.placeholder')}
options={buildMetricsList(metrics)}
mode='multiple'
fieldProps={{ onChange: (value) => handleMetricsChange(value as string[]) }}
/>
)}
{/* render metrics list */}
{jobMetricsList.length > 0 && renderMetricsCardList(jobMetricsList)}
</ProCard>
</>
);
}; };
export default Job; export default Job;
...@@ -216,7 +216,8 @@ export enum API_CONSTANTS { ...@@ -216,7 +216,8 @@ export enum API_CONSTANTS {
GET_JOB_LIST = '/api/jobInstance', GET_JOB_LIST = '/api/jobInstance',
GET_JOB_BY_ID = '/api/jobInstance/getOneById', GET_JOB_BY_ID = '/api/jobInstance/getOneById',
GET_JOB_DETAIL = '/api/jobInstance/getJobInfoDetail', GET_JOB_DETAIL = '/api/jobInstance/getJobInfoDetail',
REFESH_JOB_DETAIL = '/api/jobInstance/refreshJobInfoDetail', REFRESH_JOB_DETAIL = '/api/jobInstance/refreshJobInfoDetail',
READ_CHECKPOINT = '/api/flinkConf/readCheckPoint',
GET_JOB_VERSION = '/api/task/version', GET_JOB_VERSION = '/api/task/version',
GET_JOBMANAGER_LOG = 'api/jobInstance/getJobManagerLog', GET_JOBMANAGER_LOG = 'api/jobInstance/getJobManagerLog',
GET_JOBMANAGER_STDOUT = 'api/jobInstance/getJobManagerStdOut', GET_JOBMANAGER_STDOUT = 'api/jobInstance/getJobManagerStdOut',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment