Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
* 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.hudi.metrics;

import org.apache.hudi.common.util.VisibleForTesting;
import org.apache.hudi.source.split.HoodieSourceSplit;

import org.apache.flink.metrics.MetricGroup;

import javax.annotation.Nullable;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/** Tracks queued and assigned splits until the reader finishes emitting them. */
public class FlinkStreamReadLagMetrics extends HoodieFlinkMetrics {
private final Clock clock;
// A null time means the split is already counted and its timestamp is still unknown.
private final Map<String, Instant> pending = new HashMap<>();
private final TreeMap<Instant, Integer> completionTimes = new TreeMap<>();
@Nullable
private Instant oldestUndiscovered;

public FlinkStreamReadLagMetrics(MetricGroup metricGroup, String tableName) {
this(metricGroup, tableName, Clock.systemUTC());
}

@VisibleForTesting
FlinkStreamReadLagMetrics(MetricGroup metricGroup, String tableName, Clock clock) {
super(metricGroup.addGroup("table", tableName));
this.clock = clock;
}

@Override
public void registerMetrics() {
metricGroup.gauge("readLagSeconds", this::getReadLagSeconds);
metricGroup.gauge("pendingSplits", this::getPendingSplits);
}

public synchronized List<HoodieSourceSplit> addSplits(Collection<HoodieSourceSplit> splits) {
List<HoodieSourceSplit> added = new ArrayList<>();
for (HoodieSourceSplit split : splits) {
String key = split.trackingKey();
if (!pending.containsKey(key)) {
pending.put(key, null);
added.add(split);
}
}
return added;
}

public synchronized void resolveCompletionTimes(Map<String, Instant> resolved) {
resolved.forEach((key, time) -> {
// A reader can finish a split while the timestamp lookup is in progress.
if (time != null && pending.replace(key, null, time)) {
completionTimes.merge(time, 1, Integer::sum);
}
});
}

public synchronized void finishSplits(Collection<String> keys) {
for (String key : keys) {
Instant time = pending.remove(key);
if (time != null) {
completionTimes.computeIfPresent(time, (k, count) -> count == 1 ? null : count - 1);
}
}
}

public synchronized void setOldestUndiscovered(@Nullable Instant time) {
oldestUndiscovered = time;
}

private synchronized long getPendingSplits() {
return pending.size();
}

private synchronized long getReadLagSeconds() {
Instant oldest = oldestUndiscovered;
if (!completionTimes.isEmpty() && (oldest == null || completionTimes.firstKey().isBefore(oldest))) {
oldest = completionTimes.firstKey();
}
return oldest == null ? 0L : Math.max(0L, Duration.between(oldest, clock.instant()).getSeconds());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,25 @@

import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.StringUtils;
import org.apache.hudi.metrics.FlinkStreamReadLagMetrics;
import org.apache.hudi.source.HoodieScanContext;
import org.apache.hudi.source.split.HoodieContinuousSplitBatch;
import org.apache.hudi.source.split.HoodieContinuousSplitDiscover;
import org.apache.hudi.source.split.HoodieSourceSplit;
import org.apache.hudi.source.split.HoodieSourceSplitState;
import org.apache.hudi.source.split.HoodieSplitProvider;
import org.apache.hudi.source.split.SplitRequestEvent;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.connector.source.SourceEvent;
import org.apache.flink.api.connector.source.SplitEnumeratorContext;

import javax.annotation.Nullable;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
* Continuous Hoodie enumerator that discovers Hoodie splits from new Hoodie commits of upstream Hoodie table.
Expand All @@ -46,6 +55,12 @@ public class HoodieContinuousSplitEnumerator extends AbstractHoodieSplitEnumerat
*/
private final AtomicReference<HoodieEnumeratorPosition> position;

// Read lag metrics, null when the context has no metric group
private final FlinkStreamReadLagMetrics lagMetrics;

private long nextRefresh;
private long appliedRefresh;

public HoodieContinuousSplitEnumerator(
String tableName,
SplitEnumeratorContext<HoodieSourceSplit> enumeratorContext,
Expand All @@ -66,11 +81,22 @@ public HoodieContinuousSplitEnumerator(
// while for continuous incremental read, the start instant is exclusive.
this.position.set(HoodieEnumeratorPosition.of(Option.empty(), Option.empty()));
}

if (enumeratorContext.metricGroup() != null) {
this.lagMetrics = new FlinkStreamReadLagMetrics(enumeratorContext.metricGroup(), tableName);
this.lagMetrics.registerMetrics();
} else {
this.lagMetrics = null;
}
}

@Override
public void start() {
super.start();
if (lagMetrics != null && splitProvider.pendingSplitCount() > 0) {
// HoodieSource already loaded the checkpoint's pending splits into the provider.
trackSplits(splitProvider.state().stream().map(HoodieSourceSplitState::getSplit).collect(Collectors.toList()));
}
enumeratorContext.callAsync(
this::discoverSplits,
this::processDiscoveredSplits,
Expand All @@ -88,22 +114,74 @@ public HoodieSplitEnumeratorState snapshotState(long checkpointId) throws Except
return new HoodieSplitEnumeratorState(splitProvider.state(), position.get().getIssuedInstant(), position.get().getIssuedOffset());
}

@Override
public void handleSourceEvent(int subtaskId, SourceEvent event) {
super.handleSourceEvent(subtaskId, event);
if (lagMetrics != null && event instanceof SplitRequestEvent) {
lagMetrics.finishSplits(((SplitRequestEvent) event).finishedSplitKeys());
}
}

@Override
public void addSplitsBack(List<HoodieSourceSplit> splits, int subtaskId) {
super.addSplitsBack(splits, subtaskId);
trackSplits(splits);
}

private void trackSplits(Collection<HoodieSourceSplit> splits) {
if (lagMetrics == null || splits.isEmpty()) {
return;
}
List<HoodieSourceSplit> added = lagMetrics.addSplits(splits);
if (!added.isEmpty()) {
enumeratorContext.callAsync(() -> splitDiscover.getSplitCompletionTimes(added), (times, error) -> {
if (error != null) {
log.warn("Failed to resolve split completion times", error);
} else {
lagMetrics.resolveCompletionTimes(times);
}
});
}
}

/** A paused discovery needs a fresh timeline when measuring undiscovered lag. */
@Nullable
private HoodieContinuousSplitBatch discoverSplits() {
int pendingSplitNumber = splitProvider.pendingSplitCount();
if (pendingSplitNumber > scanContext.getMaxPendingSplits()) {
log.info(
"Pause split discovery as the assigner already has too many pending splits: {}",
pendingSplitNumber);
return HoodieContinuousSplitBatch.EMPTY;
return null;
}
return splitDiscover.discoverSplits(position.get().getIssuedOffset().isPresent() ? position.get().getIssuedOffset().get() : null);
return splitDiscover.discoverSplits(position.get().getIssuedOffset().orElse(null));
}

private void processDiscoveredSplits(HoodieContinuousSplitBatch result, Throwable throwable) {
private void refreshUndiscovered(boolean paused) {
if (lagMetrics == null) {
return;
}
String offset = position.get().getIssuedOffset().orElse(null);
long refresh = ++nextRefresh;
enumeratorContext.callAsync(() -> splitDiscover.getOldestUndiscovered(offset, paused), (time, error) -> {
if (error != null) {
log.warn("Failed to get the oldest undiscovered commit after {}", offset, error);
} else if (refresh > appliedRefresh) {
appliedRefresh = refresh;
lagMetrics.setOldestUndiscovered(time);
}
});
}

private void processDiscoveredSplits(@Nullable HoodieContinuousSplitBatch result, Throwable throwable) {
if (throwable != null) {
throw new RuntimeException("Failed to discover new splits", throwable);
}

if (result == null) {
refreshUndiscovered(true);
return;
}
if (!result.getSplits().isEmpty()) {
splitProvider.onDiscoveredSplits(result.getSplits());
if (enumeratorMetrics != null) {
Expand All @@ -128,6 +206,7 @@ private void processDiscoveredSplits(HoodieContinuousSplitBatch result, Throwabl
position.set(HoodieEnumeratorPosition.of(result.getEndInstant(), result.getOffset()));
log.info("Update enumerator position to {}", position.get());
}
refreshUndiscovered(false);
trackSplits(result.getSplits());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
* The reader implementation of Hoodie Source.
Expand Down Expand Up @@ -80,7 +81,7 @@ public void start() {
// We request a split only if we did not get splits during the checkpoint restore.
// Otherwise, reader restarts will keep requesting more and more splits.
if (getNumberOfCurrentlyAssignedSplits() == 0) {
requestSplit(Collections.emptyList());
requestSplit(Collections.emptyList(), Collections.emptyList());
}
}

Expand All @@ -89,7 +90,10 @@ protected void onSplitFinished(Map<String, HoodieSourceSplit> finishedSplitIds)
// Called on the task thread after all records of the splits are emitted, unlike the split
// reader, which finishes a split on the fetcher thread while its last batches are still queued.
finishedSplitIds.keySet().forEach(readerMetrics::finishSplit);
requestSplit(new ArrayList<>(finishedSplitIds.keySet()));
Collection<String> finishedSplitKeys = finishedSplitIds.values().stream()
.map(HoodieSourceSplit::trackingKey)
.collect(Collectors.toList());
requestSplit(new ArrayList<>(finishedSplitIds.keySet()), finishedSplitKeys);
}

@Override
Expand All @@ -102,7 +106,7 @@ protected HoodieSourceSplit toSplitType(String splitId, HoodieSourceSplit hoodie
return hoodieSourceSplit;
}

private void requestSplit(Collection<String> finishedSplitIds) {
context.sendSourceEventToCoordinator(new SplitRequestEvent(finishedSplitIds));
private void requestSplit(Collection<String> finishedSplitIds, Collection<String> finishedSplitKeys) {
context.sendSourceEventToCoordinator(new SplitRequestEvent(finishedSplitIds, finishedSplitKeys, null));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,25 @@
package org.apache.hudi.source.split;

import org.apache.hudi.common.table.HoodieTableMetaClient;
import org.apache.hudi.common.util.VisibleForTesting;
import org.apache.hudi.configuration.HadoopConfigurations;
import org.apache.hudi.source.HoodieScanContext;
import org.apache.hudi.source.IncrementalInputSplits;
import org.apache.hudi.util.StreamerUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.core.fs.Path;
import org.apache.hadoop.conf.Configuration;

import javax.annotation.Nullable;

import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
* Default implementation of HoodieContinuousSplitDiscover.
*/
@Slf4j
public class DefaultHoodieSplitDiscover implements HoodieContinuousSplitDiscover {
private final HoodieScanContext scanContext;
private final IncrementalInputSplits incrementalInputSplits;
Expand Down Expand Up @@ -65,8 +69,31 @@ public HoodieContinuousSplitBatch discoverSplits(String lastInstant) {
return incrementalInputSplits.inputHoodieSourceSplits(client, lastInstant, scanContext.isCdcEnabled());
}

@Override
@Nullable
public Instant getOldestUndiscovered(@Nullable String offset, boolean reloadTimeline) {
HoodieTableMetaClient client = getOrCreateMetaClient();
if (client == null || offset == null) {
return null;
}
if (reloadTimeline) {
client.reloadActiveTimeline();
}
return SplitReadLagUtils.getOldestUndiscovered(client, scanContext, offset);
}

@Override
public Map<String, Instant> getSplitCompletionTimes(Collection<HoodieSourceSplit> splits) {
HoodieTableMetaClient client = getOrCreateMetaClient();
if (client == null || splits.isEmpty()) {
return Collections.emptyMap();
}
return SplitReadLagUtils.getSplitCompletionTimes(client, splits);
}

@VisibleForTesting
@Nullable
private HoodieTableMetaClient getOrCreateMetaClient() {
HoodieTableMetaClient getOrCreateMetaClient() {
if (metaClient == null && StreamerUtil.tableExists(scanContext.getPath().toString(), hadoopConf)) {
metaClient = StreamerUtil.createMetaClient(scanContext.getPath().toString(), hadoopConf);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@

import org.apache.flink.annotation.Internal;

import javax.annotation.Nullable;

import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;

/**
* Interface for continuously discover new splits from active timeline.
*/
Expand All @@ -28,4 +35,15 @@ public interface HoodieContinuousSplitDiscover {

/** Discover the files appended between {@code lastInstant} and the last commit of current table */
HoodieContinuousSplitBatch discoverSplits(String lastInstant);

/** Earliest completion of a readable commit left after this discovery offset. */
@Nullable
default Instant getOldestUndiscovered(@Nullable String offset, boolean reloadTimeline) {
return null;
}

/** Oldest known commit completion time for each split, keyed by its tracking key. */
default Map<String, Instant> getSplitCompletionTimes(Collection<HoodieSourceSplit> splits) {
return Collections.emptyMap();
}
}
Loading