guozhangwang commented on a change in pull request #8833:
URL: https://github.com/apache/kafka/pull/8833#discussion_r437767910
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -378,42 +320,88 @@ public void prepareCommit() {
break;
case CREATED:
- case SUSPENDED:
case CLOSED:
throw new IllegalStateException("Illegal state " + state() + "
while preparing active task " + id + " for committing");
default:
throw new IllegalStateException("Unknown state " + state() + "
while preparing active task " + id + " for committing");
}
+
+ return committableOffsetsAndMetadata();
}
- @Override
- public void postCommit() {
+ private Map<TopicPartition, OffsetAndMetadata>
committableOffsetsAndMetadata() {
+ final Map<TopicPartition, OffsetAndMetadata> committableOffsets;
+
switch (state()) {
- case RUNNING:
- commitNeeded = false;
- commitRequested = false;
+ case CREATED:
+ case RESTORING:
+ committableOffsets = Collections.emptyMap();
- if (!eosEnabled) {
- stateMgr.checkpoint(checkpointableOffsets());
- }
+ break;
- log.debug("Committed");
+ case RUNNING:
+ case SUSPENDED:
+ final Map<TopicPartition, Long> partitionTimes =
extractPartitionTimes();
+
+ committableOffsets = new HashMap<>(consumedOffsets.size());
Review comment:
Maybe we can make an optimization by remembering the
`committableOffsets`, and then if the value (both offset and time) does not
change we do not need to give it out to consumer to commit.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StandbyTask.java
##########
@@ -108,13 +107,20 @@ public void completeRestoration() {
}
@Override
- public void prepareSuspend() {
- log.trace("No-op prepareSuspend with state {}", state());
+ public void suspendDirty() {
+ log.trace("No-op suspend dirty with state {}", state());
+ if (state() == State.RUNNING) {
Review comment:
nit: we can throw illegal-state if the state() == RESTORING since it
should never happen.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -247,82 +246,23 @@ public void completeRestoration() {
}
}
- /**
- * <pre>
- * the following order must be followed:
- * 1. first close topology to make sure all cached records in the
topology are processed
- * 2. then flush the state, send any left changelog records
- * 3. then flush the record collector
- * 4. then commit the record collector -- for EOS this is the
synchronization barrier
- * 5. then checkpoint the state manager -- even if we crash before this
step, EOS is still guaranteed
- * </pre>
- *
- * @throws TaskMigratedException if committing offsets failed (non-EOS)
- * or if the task producer got fenced (EOS)
- */
- @Override
- public void prepareSuspend() {
- switch (state()) {
- case CREATED:
- case SUSPENDED:
- // do nothing
- log.trace("Skip prepare suspending since state is {}",
state());
-
- break;
-
- case RESTORING:
- stateMgr.flush();
- log.info("Prepare suspending restoring");
-
- break;
-
- case RUNNING:
- closeTopology(true);
-
- stateMgr.flush();
- recordCollector.flush();
-
- log.info("Prepare suspending running");
-
- break;
-
- case CLOSED:
- throw new IllegalStateException("Illegal state " + state() + "
while suspending active task " + id);
-
- default:
- throw new IllegalStateException("Unknown state " + state() + "
while suspending active task " + id);
- }
- }
-
@Override
public void suspend() {
switch (state()) {
case CREATED:
case SUSPENDED:
- // do nothing
- log.trace("Skip suspending since state is {}", state());
-
- break;
-
- case RUNNING:
- stateMgr.checkpoint(checkpointableOffsets());
- partitionGroup.clear();
-
- transitionTo(State.SUSPENDED);
- log.info("Suspended running");
+ log.info("Skip suspending since state is {}", state());
break;
case RESTORING:
- // we just checkpoint the position that we've restored up to
without
- // going through the commit process
- stateMgr.checkpoint(emptyMap());
-
- // we should also clear any buffered records of a task when
suspending it
- partitionGroup.clear();
-
- transitionTo(State.SUSPENDED);
- log.info("Suspended restoring");
+ case RUNNING:
+ try {
+ closeTopology();
Review comment:
Maybe we can skip calling this if we are in `RESTORING`; I have another
comment below.
Also could we add javadoc on top explaining what exception can be thrown?
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -504,88 +438,66 @@ public void update(final Set<TopicPartition>
topicPartitions, final Map<String,
@Override
public void closeAndRecycleState() {
- prepareClose(true);
-
+ suspend();
+ prepareCommit();
writeCheckpointIfNeed();
switch (state()) {
case CREATED:
- case RESTORING:
- case RUNNING:
case SUSPENDED:
stateMgr.recycle();
recordCollector.close();
+
break;
+
+ case RESTORING: // we should have transitioned to `SUSPENDED`
already
+ case RUNNING: // we should have transitioned to `SUSPENDED` already
case CLOSED:
throw new IllegalStateException("Illegal state " + state() + "
while recycling active task " + id);
default:
throw new IllegalStateException("Unknown state " + state() + "
while recycling active task " + id);
}
- partitionGroup.close();
+ partitionGroup.clear();
closeTaskSensor.record();
transitionTo(State.CLOSED);
log.info("Closed clean and recycled state");
}
- /**
- * <pre>
- * the following order must be followed:
- * 1. first close topology to make sure all cached records in the
topology are processed
- * 2. then flush the state, send any left changelog records
- * 3. then flush the record collector
- * </pre>
- *
- * @param clean shut down cleanly (ie, incl. flush) if {@code true} --
- * otherwise, just close open resources
- * @throws TaskMigratedException if the task producer got fenced (EOS)
- */
- private void prepareClose(final boolean clean) {
- // Reset any previously scheduled checkpoint.
- checkpoint = null;
-
+ private void maybeScheduleCheckpoint() {
switch (state()) {
- case CREATED:
- // the task is created and not initialized, just re-write the
checkpoint file
- scheduleCheckpoint(emptyMap());
+ case RESTORING:
+ this.checkpoint = checkpointableOffsets();
+
break;
case RUNNING:
- closeTopology(clean);
-
- if (clean) {
- stateMgr.flush();
- recordCollector.flush();
- scheduleCheckpoint(checkpointableOffsets());
- } else {
- executeAndMaybeSwallow(false, stateMgr::flush, "state
manager flush", log);
+ if (!eosEnabled) {
+ this.checkpoint = checkpointableOffsets();
}
break;
- case RESTORING:
- executeAndMaybeSwallow(clean, stateMgr::flush, "state manager
flush", log);
- scheduleCheckpoint(emptyMap());
+ case SUSPENDED:
+ this.checkpoint = checkpointableOffsets();
break;
- case SUSPENDED:
+ case CREATED:
case CLOSED:
- // not need to checkpoint, since when suspending we've already
committed the state
- break;
+ throw new IllegalStateException("Illegal state " + state() + "
while scheduling checkpoint for active task " + id);
default:
- throw new IllegalStateException("Unknown state " + state() + "
while prepare closing active task " + id);
+ throw new IllegalStateException("Unknown state " + state() + "
while scheduling checkpoint for active task " + id);
}
}
- private void scheduleCheckpoint(final Map<TopicPartition, Long>
checkpoint) {
- this.checkpoint = checkpoint;
- }
-
private void writeCheckpointIfNeed() {
+ if (commitNeeded) {
Review comment:
Why we need this check?
Also nit: how about `maybeWriteCheckpoint` to align with
`maybeScheduleCheckpoint`.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -378,42 +320,88 @@ public void prepareCommit() {
break;
case CREATED:
- case SUSPENDED:
case CLOSED:
throw new IllegalStateException("Illegal state " + state() + "
while preparing active task " + id + " for committing");
default:
throw new IllegalStateException("Unknown state " + state() + "
while preparing active task " + id + " for committing");
}
+
+ return committableOffsetsAndMetadata();
}
- @Override
- public void postCommit() {
+ private Map<TopicPartition, OffsetAndMetadata>
committableOffsetsAndMetadata() {
+ final Map<TopicPartition, OffsetAndMetadata> committableOffsets;
+
switch (state()) {
- case RUNNING:
- commitNeeded = false;
- commitRequested = false;
+ case CREATED:
+ case RESTORING:
+ committableOffsets = Collections.emptyMap();
- if (!eosEnabled) {
- stateMgr.checkpoint(checkpointableOffsets());
- }
+ break;
- log.debug("Committed");
+ case RUNNING:
+ case SUSPENDED:
+ final Map<TopicPartition, Long> partitionTimes =
extractPartitionTimes();
+
+ committableOffsets = new HashMap<>(consumedOffsets.size());
+ for (final Map.Entry<TopicPartition, Long> entry :
consumedOffsets.entrySet()) {
+ final TopicPartition partition = entry.getKey();
+ Long offset = partitionGroup.headRecordOffset(partition);
+ if (offset == null) {
+ try {
+ offset = mainConsumer.position(partition);
+ } catch (final TimeoutException error) {
+ // the `consumer.position()` call should never
block, because we know that we did process data
+ // for the requested partition and thus the
consumer should have a valid local position
+ // that it can return immediately
+
+ // hence, a `TimeoutException` indicates a bug and
thus we rethrow it as fatal `IllegalStateException`
+ throw new IllegalStateException(error);
+ } catch (final KafkaException fatal) {
+ throw new StreamsException(fatal);
+ }
+ }
+ final long partitionTime = partitionTimes.get(partition);
+ committableOffsets.put(partition, new
OffsetAndMetadata(offset, encodeTimestamp(partitionTime)));
+ }
break;
+ case CLOSED:
+ throw new IllegalStateException("Illegal state " + state() + "
while getting commitable offsets for active task " + id);
+
+ default:
+ throw new IllegalStateException("Unknown state " + state() + "
while post committing active task " + id);
+ }
+
+ return committableOffsets;
+ }
+
+ @Override
+ public void postCommit() {
+ switch (state()) {
case RESTORING:
- commitNeeded = false;
+ case RUNNING:
+ case SUSPENDED:
commitRequested = false;
+ commitNeeded = false;
+
+ if (state() == State.RESTORING || state() == State.SUSPENDED) {
+ writeCheckpointIfNeed();
+ } else if (!eosEnabled) { // if RUNNING, checkpoint only for
non-eos
+ writeCheckpointIfNeed();
+ }
- stateMgr.checkpoint(checkpointableOffsets());
+ if (state() == State.SUSPENDED) {
+ partitionGroup.clear();
Review comment:
Hmm... this reads a bit weird to me. Can we call this in `suspend`
instead? Also in that case we do not need to call this in close and
closeAndRecycle.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -504,88 +438,66 @@ public void update(final Set<TopicPartition>
topicPartitions, final Map<String,
@Override
public void closeAndRecycleState() {
- prepareClose(true);
-
+ suspend();
+ prepareCommit();
Review comment:
I think we actually do not need to commit (including write-checkpoint)
when closeAndRecycle actually, and only need to suspend the task before recycle
it. But this is out of the scope and we can discuss about this in another PR
(cc @ableegoldman ).
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -504,88 +438,66 @@ public void update(final Set<TopicPartition>
topicPartitions, final Map<String,
@Override
public void closeAndRecycleState() {
- prepareClose(true);
-
+ suspend();
+ prepareCommit();
writeCheckpointIfNeed();
switch (state()) {
case CREATED:
- case RESTORING:
- case RUNNING:
case SUSPENDED:
stateMgr.recycle();
recordCollector.close();
+
break;
+
+ case RESTORING: // we should have transitioned to `SUSPENDED`
already
+ case RUNNING: // we should have transitioned to `SUSPENDED` already
case CLOSED:
throw new IllegalStateException("Illegal state " + state() + "
while recycling active task " + id);
default:
throw new IllegalStateException("Unknown state " + state() + "
while recycling active task " + id);
}
- partitionGroup.close();
+ partitionGroup.clear();
closeTaskSensor.record();
transitionTo(State.CLOSED);
log.info("Closed clean and recycled state");
}
- /**
- * <pre>
- * the following order must be followed:
- * 1. first close topology to make sure all cached records in the
topology are processed
- * 2. then flush the state, send any left changelog records
- * 3. then flush the record collector
- * </pre>
- *
- * @param clean shut down cleanly (ie, incl. flush) if {@code true} --
- * otherwise, just close open resources
- * @throws TaskMigratedException if the task producer got fenced (EOS)
- */
- private void prepareClose(final boolean clean) {
- // Reset any previously scheduled checkpoint.
- checkpoint = null;
-
+ private void maybeScheduleCheckpoint() {
switch (state()) {
- case CREATED:
- // the task is created and not initialized, just re-write the
checkpoint file
- scheduleCheckpoint(emptyMap());
+ case RESTORING:
Review comment:
+1, IDEA also suggests it :)
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StandbyTask.java
##########
@@ -151,69 +151,24 @@ public void postCommit() {
}
}
- @Override
- public void prepareCloseClean() {
- prepareClose(true);
-
- log.info("Prepared clean close");
- }
-
- @Override
- public void prepareCloseDirty() {
- prepareClose(false);
-
- log.info("Prepared dirty close");
- }
-
- /**
- * 1. commit if we are running and clean close;
- * 2. close the state manager.
- *
- * @throws TaskMigratedException all the task has been migrated
- * @throws StreamsException fatal error, should close the thread
- */
- private void prepareClose(final boolean clean) {
- switch (state()) {
- case CREATED:
- case CLOSED:
- log.trace("Skip prepare closing since state is {}", state());
- return;
-
- case RUNNING:
- if (clean) {
- stateMgr.flush();
- }
-
- break;
-
- case RESTORING:
- case SUSPENDED:
- throw new IllegalStateException("Illegal state " + state() + "
while closing standby task " + id);
-
- default:
- throw new IllegalStateException("Unknown state " + state() + "
while closing standby task " + id);
- }
- }
-
@Override
public void closeClean() {
close(true);
-
log.info("Closed clean");
}
@Override
public void closeDirty() {
close(false);
-
log.info("Closed dirty");
}
@Override
public void closeAndRecycleState() {
- prepareClose(true);
+ suspend();
+ prepareCommit();
- if (state() == State.CREATED || state() == State.RUNNING) {
+ if (state() == State.CREATED || state() == State.SUSPENDED) {
Review comment:
The comment below is not accurate anymore: we do not write checkpoint
during recycle actually.
EDIT: actually, the updated offsetSnapshotSinceLastCommit seems not used
since after this function we would create a new StreamTask and in between we do
not check if commitNeeded at all. Could we remove line 175 then?
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StandbyTask.java
##########
@@ -232,7 +187,7 @@ public void closeAndRecycleState() {
private void close(final boolean clean) {
switch (state()) {
case CREATED:
- case RUNNING:
+ case SUSPENDED:
Review comment:
Ditto for line 195: we do not need to update the snapshot since we are
closing the task already.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -891,6 +821,9 @@ private void initializeTopology() {
}
private void closeTopology(final boolean clean) {
+ if (state() != State.RUNNING) {
Review comment:
nit: since this is a private function only called by `suspend`, we can
modify the caller such that we only call this in `RUNNING` not in `RESTORING`,
and then inside this function we do not need this check anymore.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java
##########
@@ -210,9 +214,8 @@ public void handleAssignment(final Map<TaskId,
Set<TopicPartition>> activeTasks,
tasksToRecycle.add(task);
} else {
try {
- task.prepareCloseClean();
- final Map<TopicPartition, OffsetAndMetadata>
committableOffsets = task
- .committableOffsetsAndMetadata();
+ task.suspend();
Review comment:
question: I cannot remember why we need to commit those still owned
tasks during handle-assignment, is that necessary? Or is that just an
optimization: since we are going to commit anyways, let's just commit everyone.
If that's the case, we can refresh the last-commit timestamp as well.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -378,42 +320,88 @@ public void prepareCommit() {
break;
case CREATED:
- case SUSPENDED:
case CLOSED:
throw new IllegalStateException("Illegal state " + state() + "
while preparing active task " + id + " for committing");
default:
throw new IllegalStateException("Unknown state " + state() + "
while preparing active task " + id + " for committing");
}
+
+ return committableOffsetsAndMetadata();
}
- @Override
- public void postCommit() {
+ private Map<TopicPartition, OffsetAndMetadata>
committableOffsetsAndMetadata() {
+ final Map<TopicPartition, OffsetAndMetadata> committableOffsets;
+
switch (state()) {
- case RUNNING:
- commitNeeded = false;
- commitRequested = false;
+ case CREATED:
+ case RESTORING:
+ committableOffsets = Collections.emptyMap();
- if (!eosEnabled) {
- stateMgr.checkpoint(checkpointableOffsets());
- }
+ break;
- log.debug("Committed");
+ case RUNNING:
+ case SUSPENDED:
+ final Map<TopicPartition, Long> partitionTimes =
extractPartitionTimes();
+
+ committableOffsets = new HashMap<>(consumedOffsets.size());
+ for (final Map.Entry<TopicPartition, Long> entry :
consumedOffsets.entrySet()) {
+ final TopicPartition partition = entry.getKey();
+ Long offset = partitionGroup.headRecordOffset(partition);
+ if (offset == null) {
+ try {
+ offset = mainConsumer.position(partition);
+ } catch (final TimeoutException error) {
+ // the `consumer.position()` call should never
block, because we know that we did process data
+ // for the requested partition and thus the
consumer should have a valid local position
+ // that it can return immediately
+
+ // hence, a `TimeoutException` indicates a bug and
thus we rethrow it as fatal `IllegalStateException`
+ throw new IllegalStateException(error);
+ } catch (final KafkaException fatal) {
+ throw new StreamsException(fatal);
+ }
+ }
+ final long partitionTime = partitionTimes.get(partition);
+ committableOffsets.put(partition, new
OffsetAndMetadata(offset, encodeTimestamp(partitionTime)));
+ }
break;
+ case CLOSED:
+ throw new IllegalStateException("Illegal state " + state() + "
while getting commitable offsets for active task " + id);
+
+ default:
+ throw new IllegalStateException("Unknown state " + state() + "
while post committing active task " + id);
+ }
+
+ return committableOffsets;
+ }
+
+ @Override
+ public void postCommit() {
+ switch (state()) {
case RESTORING:
- commitNeeded = false;
+ case RUNNING:
+ case SUSPENDED:
Review comment:
What about 1) move the line 387/388 out of the switch, also line 400
after the switch block, 2) and then make these three states separate branches,
so that we can avoid a mix of switch / if-else.
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -813,6 +727,10 @@ private void updateProcessorContext(final StampedRecord
record, final ProcessorN
* Currently only changelog topic offsets need to be checkpointed.
*/
private Map<TopicPartition, Long> checkpointableOffsets() {
+ if (state() == State.RESTORING) {
Review comment:
EDIT: actually, I think we need to accumulate the consumed offsets when
we just transited to suspend and then called prepareCommit, but if we are
already in suspended then it is actually okay to return an emptyMap. However
since we do not know if we have just transited to suspended and the below code
should not be a big overhead, we can just keep it as-is.
So please ignore my previous comment :)
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamTask.java
##########
@@ -813,6 +727,10 @@ private void updateProcessorContext(final StampedRecord
record, final ProcessorN
* Currently only changelog topic offsets need to be checkpointed.
*/
private Map<TopicPartition, Long> checkpointableOffsets() {
+ if (state() == State.RESTORING) {
Review comment:
Should we return emptyMap if we are SUSPENDED as well?
##########
File path:
streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java
##########
@@ -210,9 +214,8 @@ public void handleAssignment(final Map<TaskId,
Set<TopicPartition>> activeTasks,
tasksToRecycle.add(task);
} else {
try {
- task.prepareCloseClean();
- final Map<TopicPartition, OffsetAndMetadata>
committableOffsets = task
- .committableOffsetsAndMetadata();
+ task.suspend();
Review comment:
Even in that case, in line 205 we could check `task.commitNeeded() &&
task.isActive` right?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]