GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — BoundedReader: add getSplitPoints{Consumed,Remaining} (#257) · ilganeli/DataflowJavaSDK@230fe20

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop
    • HadoopFileSource.java
  • sdk/src
    • main/java/com/google/cloud/dataflow/sdk/io
      • AvroSource.java
      • BlockBasedSource.java
      • BoundedSource.java
      • CompressedSource.java
      • CountingSource.java
      • DatastoreIO.java
      • FileBasedSource.java
      • OffsetBasedSource.java
      • TextIO.java
      • range
        • OffsetRangeTracker.java
    • test/java/com/google/cloud/dataflow/sdk/io
      • AvroSourceTest.java
      • CompressedSourceTest.java
      • CountingSourceTest.java
      • FileBasedSourceTest.java
      • OffsetBasedSourceTest.java
      • TextIOTest.java
      • range
        • OffsetRangeTrackerTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java‎

Copy file name to clipboardExpand all lines: contrib/hadoop/src/main/java/com/google/cloud/dataflow/contrib/hadoop/HadoopFileSource.java
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,7 @@ static class HadoopFileReader<K, V> extends BoundedSource.BoundedReader<KV<K, V>
281281
private Configuration conf;
282282
private RecordReader<K, V> currentReader;
283283
private KV<K, V> currentPair;
284+
private volatile boolean done = false;
284285

285286
/**
286287
* Create a {@code HadoopFileReader} based on a file or a file pattern specification.
@@ -355,6 +356,7 @@ public boolean advance() throws IOException {
355356
}
356357
// either no next split or all readers were empty
357358
currentPair = null;
359+
done = true;
358360
return false;
359361
}
360362
} catch (InterruptedException e) {
@@ -431,6 +433,16 @@ private Double getProgress() {
431433
}
432434
}
433435

436+
@Override
437+
public final long getSplitPointsRemaining() {
438+
if (done) {
439+
return 0;
440+
}
441+
// This source does not currently support dynamic work rebalancing, so remaining
442+
// parallelism is always 1.
443+
return 1;
444+
}
445+
434446
@Override
435447
public BoundedSource<KV<K, V>> splitAtFraction(double fraction) {
436448
// Not yet supported. To implement this, the sizes of the splits should be used to
Collapse file

‎sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java‎

Copy file name to clipboardExpand all lines: sdk/src/main/java/com/google/cloud/dataflow/sdk/io/AvroSource.java
+110-56Lines changed: 110 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
package com.google.cloud.dataflow.sdk.io;
1818

19+
import static com.google.common.base.Preconditions.checkState;
20+
1921
import com.google.cloud.dataflow.sdk.annotations.Experimental;
2022
import com.google.cloud.dataflow.sdk.coders.AvroCoder;
2123
import com.google.cloud.dataflow.sdk.options.PipelineOptions;
@@ -38,18 +40,24 @@
3840
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
3941
import org.apache.commons.compress.compressors.snappy.SnappyCompressorInputStream;
4042
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
43+
import org.apache.commons.compress.utils.CountingInputStream;
4144

4245
import java.io.ByteArrayInputStream;
46+
import java.io.EOFException;
4347
import java.io.IOException;
4448
import java.io.InputStream;
4549
import java.io.PushbackInputStream;
4650
import java.nio.ByteBuffer;
4751
import java.nio.channels.Channels;
4852
import java.nio.channels.ReadableByteChannel;
53+
import java.nio.channels.SeekableByteChannel;
54+
import java.util.Arrays;
4955
import java.util.Collection;
5056
import java.util.zip.Inflater;
5157
import java.util.zip.InflaterInputStream;
5258

59+
import javax.annotation.concurrent.GuardedBy;
60+
5361
// CHECKSTYLE.OFF: JavadocStyle
5462
/**
5563
* A {@link FileBasedSource} for reading Avro files.
@@ -437,35 +445,32 @@ public double getFractionOfBlockConsumed() {
437445
* the total number of records in the block and the block's size in bytes, followed by the
438446
* block's (optionally-encoded) records. Each block is terminated by a 16-bit sync marker.
439447
*
440-
* <p>Here, we consider the sync marker that precedes a block to be its offset, as this allows
441-
* a reader that begins reading at that offset to detect the sync marker and the beginning of
442-
* the block.
443-
*
444448
* @param <T> The type of records contained in the block.
445449
*/
446450
@Experimental(Experimental.Kind.SOURCE_SINK)
447451
public static class AvroReader<T> extends BlockBasedReader<T> {
448452
// The current block.
449453
private AvroBlock<T> currentBlock;
450454

451-
// Offset of the block.
455+
// A lock used to synchronize block offsets for getRemainingParallelism
456+
private final Object progressLock = new Object();
457+
458+
// Offset of the current block.
459+
@GuardedBy("progressLock")
452460
private long currentBlockOffset = 0;
453461

454462
// Size of the current block.
463+
@GuardedBy("progressLock")
455464
private long currentBlockSizeBytes = 0;
456465

457-
// Current offset within the stream.
458-
private long currentOffset = 0;
459-
460466
// Stream used to read from the underlying file.
461-
// A pushback stream is used to restore bytes buffered during seeking/decoding.
467+
// A pushback stream is used to restore bytes buffered during seeking.
462468
private PushbackInputStream stream;
469+
// Counts the number of bytes read. Used only to tell how many bytes are taken up in
470+
// a block's variable-length header.
471+
private CountingInputStream countStream;
463472

464-
// Small buffer for reading encoded values from the stream.
465-
// The maximum size of an encoded long is 10 bytes, and this buffer will be used to read two.
466-
private final byte[] readBuffer = new byte[20];
467-
468-
// Decoder to decode binary-encoded values from the buffer.
473+
// Caches the Avro DirectBinaryDecoder used to decode binary-encoded values from the buffer.
469474
private BinaryDecoder decoder;
470475

471476
/**
@@ -480,51 +485,67 @@ public synchronized AvroSource<T> getCurrentSource() {
480485
return (AvroSource<T>) super.getCurrentSource();
481486
}
482487

488+
// Precondition: the stream is positioned after the sync marker in the current (about to be
489+
// previous) block. currentBlockSize equals the size of the current block, or zero if this
490+
// reader was just started.
491+
//
492+
// Postcondition: same as above, but for the new current (formerly next) block.
483493
@Override
484494
public boolean readNextBlock() throws IOException {
485-
// The next block in the file is after the first sync marker that can be read starting from
486-
// the current offset. First, we seek past the next sync marker, if it exists. After a sync
487-
// marker is the start of a block. A block begins with the number of records contained in
488-
// the block, encoded as a long, followed by the size of the block in bytes, encoded as a
489-
// long. The currentOffset after this method should be last byte after this block, and the
490-
// currentBlockOffset should be the start of the sync marker before this block.
491-
492-
// Seek to the next sync marker, if one exists.
493-
currentOffset += advancePastNextSyncMarker(stream, getCurrentSource().getSyncMarker());
494-
495-
// The offset of the current block includes its preceding sync marker.
496-
currentBlockOffset = currentOffset - getCurrentSource().getSyncMarker().length;
497-
498-
// Read a small buffer to parse the block header.
499-
// We cannot use a BinaryDecoder to do this directly from the stream because a BinaryDecoder
500-
// internally buffers data and we only want to read as many bytes from the stream as the size
501-
// of the header. Though BinaryDecoder#InputStream returns an input stream that is aware of
502-
// its internal buffering, we would have to re-wrap this input stream to seek for the next
503-
// block in the file.
504-
int read = stream.read(readBuffer);
505-
// We reached the last sync marker in the file.
506-
if (read <= 0) {
495+
long startOfNextBlock = currentBlockOffset + currentBlockSizeBytes;
496+
497+
// Before reading the variable-sized block header, record the current number of bytes read.
498+
long preHeaderCount = countStream.getBytesRead();
499+
decoder = DecoderFactory.get().directBinaryDecoder(countStream, decoder);
500+
long numRecords;
501+
try {
502+
numRecords = decoder.readLong();
503+
} catch (EOFException e) {
504+
// Expected for the last block, at which the start position is the EOF. The way to detect
505+
// stream ending is to try reading from it.
507506
return false;
508507
}
509-
decoder = DecoderFactory.get().binaryDecoder(readBuffer, decoder);
510-
long numRecords = decoder.readLong();
511508
long blockSize = decoder.readLong();
512509

513-
// The decoder buffers data internally, but since we know the size of the stream the
514-
// decoder has constructed from the readBuffer, the number of bytes available in the
515-
// input stream is equal to the number of unconsumed bytes.
516-
int headerSize = readBuffer.length - decoder.inputStream().available();
517-
stream.unread(readBuffer, headerSize, read - headerSize);
510+
// Mark header size as the change in the number of bytes read.
511+
long headerSize = countStream.getBytesRead() - preHeaderCount;
518512

519513
// Create the current block by reading blockSize bytes. Block sizes permitted by the Avro
520514
// specification are [32, 2^30], so this narrowing is ok.
521515
byte[] data = new byte[(int) blockSize];
522-
stream.read(data);
516+
int read = stream.read(data);
517+
checkState(blockSize == read, "Only %s/%s bytes in the block were read", read, blockSize);
523518
currentBlock = new AvroBlock<>(data, numRecords, getCurrentSource());
524-
currentBlockSizeBytes = blockSize;
525519

526-
// Update current offset with the number of bytes we read to get the next block.
527-
currentOffset += headerSize + blockSize;
520+
// Read the end of this block, which MUST be a sync marker for correctness.
521+
byte[] syncMarker = getCurrentSource().getSyncMarker();
522+
byte[] readSyncMarker = new byte[syncMarker.length];
523+
long syncMarkerOffset = startOfNextBlock + headerSize + blockSize;
524+
long bytesRead = stream.read(readSyncMarker);
525+
checkState(
526+
bytesRead == syncMarker.length,
527+
"When trying to read a sync marker at position %s, only able to read %s/%s bytes",
528+
syncMarkerOffset,
529+
bytesRead,
530+
syncMarker.length);
531+
if (!Arrays.equals(syncMarker, readSyncMarker)) {
532+
throw new IllegalStateException(
533+
String.format(
534+
"Expected the bytes [%d,%d) in file %s to be a sync marker, but found %s",
535+
syncMarkerOffset,
536+
syncMarkerOffset + syncMarker.length,
537+
getCurrentSource().getFileOrPatternSpec(),
538+
Arrays.toString(readSyncMarker)
539+
));
540+
}
541+
542+
// Atomically update both the position and offset of the new block.
543+
synchronized (progressLock) {
544+
currentBlockOffset = startOfNextBlock;
545+
// Total block size includes the header, block content, and trailing sync marker.
546+
currentBlockSizeBytes = headerSize + blockSize + syncMarker.length;
547+
}
548+
528549
return true;
529550
}
530551

@@ -535,32 +556,65 @@ public AvroBlock<T> getCurrentBlock() {
535556

536557
@Override
537558
public long getCurrentBlockOffset() {
538-
return currentBlockOffset;
559+
synchronized (progressLock) {
560+
return currentBlockOffset;
561+
}
539562
}
540563

541564
@Override
542565
public long getCurrentBlockSize() {
543-
return currentBlockSizeBytes;
566+
synchronized (progressLock) {
567+
return currentBlockSizeBytes;
568+
}
569+
}
570+
571+
@Override
572+
public long getSplitPointsRemaining() {
573+
if (isDone()) {
574+
return 0;
575+
}
576+
synchronized (progressLock) {
577+
if (currentBlockOffset + currentBlockSizeBytes >= getCurrentSource().getEndOffset()) {
578+
// This block is known to be the last block in the range.
579+
return 1;
580+
}
581+
}
582+
return super.getSplitPointsRemaining();
544583
}
545584

546585
/**
547586
* Creates a {@link PushbackInputStream} that has a large enough pushback buffer to be able
548-
* to push back the syncBuffer and the readBuffer.
587+
* to push back the syncBuffer.
549588
*/
550589
private PushbackInputStream createStream(ReadableByteChannel channel) {
551590
return new PushbackInputStream(
552591
Channels.newInputStream(channel),
553-
getCurrentSource().getSyncMarker().length + readBuffer.length);
592+
getCurrentSource().getSyncMarker().length);
554593
}
555594

556-
/**
557-
* Starts reading from the provided channel. Assumes that the channel is already seeked to
558-
* the source's start offset.
559-
*/
595+
// Postcondition: the stream is positioned at the beginning of the first block after the start
596+
// of the current source, and currentBlockOffset is that position. Additionally,
597+
// currentBlockSizeBytes will be set to 0 indicating that the previous block was empty.
560598
@Override
561599
protected void startReading(ReadableByteChannel channel) throws IOException {
600+
long startOffset = getCurrentSource().getStartOffset();
601+
byte[] syncMarker = getCurrentSource().getSyncMarker();
602+
long syncMarkerLength = syncMarker.length;
603+
604+
if (startOffset != 0) {
605+
// Rewind order to find the sync marker ending the previous block.
606+
long position = Math.max(0, startOffset - syncMarkerLength);
607+
((SeekableByteChannel) channel).position(position);
608+
startOffset = position;
609+
}
610+
611+
// Satisfy the post condition.
562612
stream = createStream(channel);
563-
currentOffset = getCurrentSource().getStartOffset();
613+
countStream = new CountingInputStream(stream);
614+
synchronized (progressLock) {
615+
currentBlockOffset = startOffset + advancePastNextSyncMarker(stream, syncMarker);
616+
currentBlockSizeBytes = 0;
617+
}
564618
}
565619

566620
/**
Collapse file

‎sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java‎

Copy file name to clipboardExpand all lines: sdk/src/main/java/com/google/cloud/dataflow/sdk/io/BlockBasedSource.java
+15-11Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -205,28 +205,32 @@ protected final boolean readNextRecord() throws IOException {
205205
}
206206

207207
@Override
208+
@Nullable
208209
public Double getFractionConsumed() {
209-
if (getCurrentSource().getEndOffset() == Long.MAX_VALUE) {
210-
return null;
211-
}
212-
Block<T> currentBlock = getCurrentBlock();
213-
if (currentBlock == null) {
214-
// There is no current block (i.e., the read has not yet begun).
210+
if (!isStarted()) {
215211
return 0.0;
216212
}
213+
if (isDone()) {
214+
return 1.0;
215+
}
216+
FileBasedSource<T> source = getCurrentSource();
217+
if (source.getEndOffset() == Long.MAX_VALUE) {
218+
// Unknown end offset, so we cannot tell.
219+
return null;
220+
}
221+
217222
long currentBlockOffset = getCurrentBlockOffset();
218-
long startOffset = getCurrentSource().getStartOffset();
219-
long endOffset = getCurrentSource().getEndOffset();
223+
long startOffset = source.getStartOffset();
224+
long endOffset = source.getEndOffset();
220225
double fractionAtBlockStart =
221226
((double) (currentBlockOffset - startOffset)) / (endOffset - startOffset);
222227
double fractionAtBlockEnd =
223228
((double) (currentBlockOffset + getCurrentBlockSize() - startOffset)
224229
/ (endOffset - startOffset));
230+
double blockFraction = getCurrentBlock().getFractionOfBlockConsumed();
225231
return Math.min(
226232
1.0,
227-
fractionAtBlockStart
228-
+ currentBlock.getFractionOfBlockConsumed()
229-
* (fractionAtBlockEnd - fractionAtBlockStart));
233+
fractionAtBlockStart + blockFraction * (fractionAtBlockEnd - fractionAtBlockStart));
230234
}
231235

232236
@Override

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.